简体   繁体   中英

Confused by result of printing associative array with PHP

I'm trying to use foreach to print the results of a SQL query from an associative array. I'm trying different things and one works while the other gives an error.

I'm specifically asking about why this portion $row[first_name] gives different results.

This code works:

<?php
 include 'connect_db.php';
 $stmt = $conn->query("SELECT people.first_name, people.last_name FROM people");
 $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

 foreach ($results as $row) {
    echo "<form action='/test.php' method='post'>
   <input type='text' name='first_name' value=$row[first_name]>
  <input type='submit' value='Click'> <br>
 </form>"; 
 }  
?>

But the following code gives an error saying: Notice: Use of undefined constant first_name - assumed 'first_name'

<?php
 include 'connect_db.php';
 $stmt = $conn->query("SELECT people.first_name, people.last_name FROM people");
 $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

 foreach ($results as $row) {
 echo $row[first_name]; 
 }  
?>

I'm obviously using $row[first_name] incorrectly in the 2nd example but I can't figure out how.

The keys in an associative array returned from MySQL are strings - you need to quote them:

echo $row['first_name'];
# Here ---^----------^

When using an undefined constant, PHP will automatically assume a string was intended. [sic]

PHP assumes that you mean the name of the constant itself, just as if you called it as a string

Example: https://3v4l.org/C7PgT

As noted in the PHP 7.x, it will result in an ERROR as opposed to a warning in future versions, so its use should be avoided in favor of using quoted strings

Why $foo[bar] is wrong: [sic]

Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. The reason is that this code has an undefined constant ( bar ) rather than a string ( 'bar' - notice the quotes). if there is no defined constant named bar , then PHP will substitute in the string 'bar' and use that.

This does not mean to always quote the key. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them.

When you used it within a double-quoted context ( "$var" ), PHP's lexer automatically used the text within the brackets ( $var[text] ) as a string.

Also PHP's lexer has issues when using array or objects within double quotes.

echo "value=$row['first_name']"; //results in a syntax error

Example: https://3v4l.org/K6fUd

To resolve this issue you would need to wrap your array with curly-brackets

echo "value={$row['first_name']}";

Excample: https://3v4l.org/aQ1sJ


Instead I highly suggest conforming to single quotes for all PHP output to save you from having to read between different syntax and HTML syntax uniformity.

foreach ($results as $row) {
    echo '<form action="/test.php" method="post">
   <input type="text" name="first_name" value="' . $row['first_name'] . '">
  <input type="submit" value="Click"><br>
 </form>'; 
 }  

Alternatively using HEREDOC or NOWDOC depending on desired output.

foreach ($rows as $row) {
    echo <<<EOT
value="{$row['first_name']}"
EOT;

}

Example (including HEREDOC): https://3v4l.org/7K5ap

My preferred method is to ensure all HTML syntax is output directly or to the output buffer. As it allows for most IDE's, such as PHPStorm, to automatically distinguish it as HTML and not PHP code, to ensure HTML syntax is valid and matches with other tags.

<?php foreach ($results as $row) { ?>
<form action="/test.php" method="post">
    <input type="text" name="first_name" value="<?php echo $row['first_name']; ?>">
    <input type="submit" value="Click"><br>
</form>
<?php } ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM