Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 } ?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...