0

How can you use a function in a (EOT function/text block), for better understanding, I want you take a look at my example:

include "db.inc.php";
$sql="SELECT * FROM image";
$result = mysqli_query($conn, $sql) or die(mysqli_error($mysqli));
while($topic_info = mysqli_fetch_array($result)){
    $img_id=$topic_info['id'];
    $img_name=$topic_info['name'];
    
    $display_block .= <<<END_OF_TEXT
        <div>
        <img src="images/${img_name}">
        <strong>print_r($topic_info)</strong>
    </div>
END_OF_TEXT;
    
}

echo $display_block;

How to use a function like print_r in that variable?

amir
  • 85
  • 5
  • 1
    It is a very bad idea to use `die(mysqli_error($$conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Dec 23 '20 at 21:47
  • I read that and that was helpful, can you tell me exactly where I shoud use this line of code mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); instead od die? I mean should I write the code exactly after mysqli_connect() or somewhere else? – amir Dec 23 '20 at 23:28
  • 1
    Just add that line right before `mysqli_connect()` – Dharman Dec 23 '20 at 23:28

1 Answers1

1

You can't make function calls within HEREDOC text blocks, so you won't be able to recursively print that array, that way.

What you can do is set the optional 2nd parameter of print_r to TRUE, which returns the printed string instead of 'print' it. That way, you can assign it to a variable and include it in the HEREDOC block like the other variables already are.

while($topic_info = mysqli_fetch_array($result)) {

    $img_id=$topic_info['id'];
    $img_name=$topic_info['name'];
    $topic_info_string = print_r($topic_info, true);

    $display_block .= <<<END_OF_TEXT
    <div>
        <img src="images/{$img_name}"/>
        <strong>$topic_info_string</strong>
    </div>
END_OF_TEXT;

}

https://www.php.net/manual/en/function.print-r.php