简体   繁体   中英

How do you select multiple rows from a mysql table?

I have a php script that is supposed to get multiple rows from a table and then wrap each row as an array into another array.

$comQy = "SELECT * FROM comments WHERE user = '$user' ORDER BY DESC;";
$comSt = $db->prepare($revQy);
$comRes = $comSt->execute();
$coms = $comSt->fetchAll();

Later in the page, I try to echo one of the elements of the array and then it doesn't work but doesn't return an error.

<div id="comUser">
<?php echo $coms[0]['user'] ?>
</div>

I appreciate all help and I am sorry if I have made a fairly simple mistake in the php script.

This could be the problem of

  • missing the field name for the ORDER BY clause in the SQL query
  • missing the variable declaration $revQy
  • missing the object variable declaration $revSt

$comSt = $db->prepare($revQy);
$comRes = $revSt->execute();

Enabling error reporting is a good practice during development. Add these lines of code at the top of your script.

error_reporting(E_ALL);
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
$comQy = "SELECT * FROM comments WHERE user = :user ORDER BY 1 DESC;";
$comSt = $db->prepare($comQy);
$comRes = $comSt->execute(array( 'user' => $user ));

$comSt->setFetchMode(PDO::FETCH_ASSOC);
$coms = $comSt->fetchAll();

try to use msqli procedural method (im just a newbie too)

$sql = 'SELECT * FROM comments WHERE user = "'.$user.'" ORDER BY fieldname DESC';
$result = mysqli_query($db_connection, $sql);
while($row = mysqli_fetch_assoc($result)){
    echo $row['user'];
}

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