Jump to content

Need help wont display database first result


davidolson

Recommended Posts

if i delete this code everything works

$number_of_rows = $completed_offer_stmt->fetch(PDO::FETCH_COLUMN);

if (!$number_of_rows){

print "No results";

}
$query_1 = "SELECT *

FROM offer_pending

WHERE status = 1

ORDER BY date_modified DESC LIMIT 10";

$completed_offer_stmt = $dbh->prepare($query_1);

$completed_offer_stmt->execute();


$number_of_rows = $completed_offer_stmt->fetch(PDO::FETCH_COLUMN);

if (!$number_of_rows){

print "No results";

}


while($completed_offer = $completed_offer_stmt->fetch(PDO::FETCH_ASSOC)){



$query_2 = "SELECT *

FROM offers

WHERE id= :completed_offer_id";

$offers_stmt = $dbh->prepare($query_2);

$offers_stmt->bindParam(':completed_offer_id', $completed_offer['offer_id']);

$offers_stmt->execute();

$offers = $offers_stmt->fetch(PDO::FETCH_ASSOC);

print "{$offers['name']} {$offers['points']}";



}
 
Link to comment
Share on other sites

to test if a PDO query that executed without any errors returned any rows at all, use the ->columnCount() method (a zero means no result set since you cannot select nothing/no-columns in a query.)

 


 

if you are going to actually use all the rows a query returned, but you also want to test if there are/are-not any rows, just use the ->fetchAll() method and use count() to determine how many rows there are.

Edited by mac_gyver
Link to comment
Share on other sites

Well, then, delete that code. It's wrong anyway.

 

->fetch retrieves a row from the database. It does NOT retrieve the record count. So, with that code you are retrieving the first row. Then you start your loop by retrieving the NEXT row, but you have never processed the first one.

 

 

Note: The reason prepared statements were invented (many years ago) was to speed up processing when running queries in a loop. But to benefit from that, you would PREPARE the statement OUTSIDE of the loop. HOWEVER, in this case (as in most cases) you can and should get all of the data in your first query using a JOIN.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.