simonb
simonb

Reputation: 17

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.

Upvotes: 0

Views: 83

Answers (3)

Sithu
Sithu

Reputation: 4862

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);

Upvotes: 3

John V
John V

Reputation: 875

$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();

Upvotes: 2

Pantamtuy
Pantamtuy

Reputation: 243

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'];
}

Upvotes: -1

Related Questions