简体   繁体   中英

Pulling data out of PHP array and echoing it in sections

you're probably very confused, having read the title. I'm building a simple comments section to my site. I've got a MySql query that gets dumped into an array, I then want to take different "sections" of each row and echo them out. Here is what I have so far, and I'm not getting anything echoed out.

$query = "SELECT * FROM fishing_comments WHERE fishing_id = $id";
$result = mysql_query($query);

  if (!$result) {
    die('Invalid query: ' . mysql_error());
                }


    while ($data = @mysql_fetch_assoc($result)){
    $row[] = $data;
        }

   echo($row['date_added']);
   echo($row['negative']);       
       echo($row['added_by']); 

You're not getting results because you're trying to access array keys that don't exist. You probably mean something like this:

echo $row[0]['date_added'];

or in a loop:

foreach($row AS $r)
{
    echo $r['date_added'];
}

Couple notes - mysql_ functions are deprecated. You should switch to mysqli or PDO. Also, it is not a good idea to suppress like this. @mysql_fetch_assoc should instead check the _num_rows on the query - for example mysqli_num_rows($result) if you were using mysqli...

if($result->num_rows > 0)
{
    while($data = $result->fetch_assoc())
    {
        $row[] = $data;
    }
}

Suppression is more memory intensive and unnecessary when the object will have something useful to check

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