How could I change the printf's %s function to PHP variables?

The title may be strange, but I think this is a legitimate problem. It’s mostly PHP but it does have a little database stuff in it. I want to know how to change the %s to actual PHP variables.

Here’s what I’m focused on:

    printf('

  </div><div class="flol">
        <h1>%s</h1>
        <br>
        <h2>By %s</h2>
        <br>
        <br>
        <h3>%s</h3>
  </div>

  <div class="flor">
    <div style="float:right; background-color:#333; padding:10px;">
    <img src="assets/placeholder.jpg" height="200" width="200">
    </div>
  </div>
    ', $row[0],$row[1], $row[2]);

How to I change the %s’s to $row[0], $row[1], etc.?

Simple. Don’t use printf. Use echo instead. Even better, use the output tags. And I mean for the variables. Don’t echo pure HTML.

Example

<?= $row['some_column'] ?>
1 Like

Have you tried running that code? It does exectly what you want it to :slight_smile:

Below alternatives will result to the same output.

$var1 = 'var1';
$var2 = 'var2';
$var3 = 'var3';

printf('</div><div class="flol">
        <h1>%s</h1>
        <br>
        <h2>By %s</h2>
        <br>
        <br>
        <h3>%s</h3>
  </div></div>', $var1, $var2, $var3);

or…

echo "</div><div class=\"flol\">
        <h1>$var1</h1>
        <br>
        <h2>By $var2</h2>
        <br>
        <br>
        <h3>$var3</h3>
  </div></div>";

or…

echo '</div><div class="flol">
<h1>'.$var1.'</h1>
<br>
<h2>By '.$var2.'</h2>
<br>
<br>
<h3>'.$var3.'</h3>
</div></div>';

or…

echo <<<EOT
</div><div class="flol">
<h1>$var1</h1>
<br>
<h2>By $var2</h2>
<br>
<br>
<h3>$var3</h3>
</div></div>
EOT;

Also, never just output something from the database to the screen. Always apply htmlspecialchars first to prevent Cross Site Scripting (XSS) attacks.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.