1

I'm trying to set the image src from a variable which is defined in a function with a mysql query but it doesn't get the path.

Here is the function:

function bilderAbfrage($richtigesArray) {
 echo "ayy";
 $zahl = $GLOBALS["zaehler"];
 echo "$zahl";
 $pdo = new PDO('mysql:host=localhost;dbname=datagame', 'root', 'root');
 $sql = "SELECT * FROM bilder WHERE DateIDFS = $richtigesArray[$zahl]";

    foreach ($pdo->query($sql) as $row) {
        echo $row['Path'];     // here it does print the right path of the image
        $bild1 = $row['Path'];
        $bild2 = $row['Path2'];
        $bild3 = $row['Path3'];
        $bild4 = $row['Path4'];

    }

}

Here are the images where it doesn't get the variables. I tried it with global but it didn't work:

<div class="row1">
        <img src="<?php global $bild1; echo $bild1; ?>" alt="<?php global $bild1; echo $bild1; ?>" id="pic1" class="pic1">
        <img src="<?php global $bild2; echo $bild2;?>" id="pic2" class="pic2">
        <?php echo "hey"; 
        ?>
      </div>
      <div class="row2">
        <img src="<?php global $bild3; echo $bild3; ?>" class="pic3">
        <img src="<?php global $bild4; echo $bild4; ?>" class="pic4">
      </div>
3
  • Does this answer your question? Giving my function access to outside variable Commented Jan 18, 2020 at 21:41
  • The global keyword goes inside your function bilderAbfrage declaration. See the link @Dharman mentions above. Commented Jan 18, 2020 at 21:44
  • omg, the mistake was, that i didnt global it in the function before giving them the path, I made them global after I gave them the path. Thanks for the help and yea i still have to make the prepared statements Commented Jan 18, 2020 at 21:59

1 Answer 1

1

One little error I tried to make the bild1 - bild4 global after I gave them the path.

Correct:

function bilderAbfrage($richtigesArray){
echo "ayy";
$zahl = $GLOBALS["zaehler"];
echo "$zahl";
$pdo = new PDO('mysql:host=localhost;dbname=datagame', 'root', '5718orii');
$sql = "SELECT * FROM bilder WHERE DateIDFS = $richtigesArray[$zahl]";

    foreach ($pdo->query($sql) as $row) {
        global $bild1, $bild2, $bild3, $bild4;
        echo $row['Path'];
        $bild1 = $row['Path'];
        $bild2 = $row['Path2'];
        $bild3 = $row['Path3'];
        $bild4 = $row['Path4'];

    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.