mysql query

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
peteblair
Forum Newbie
Posts: 2
Joined: Tue Sep 22, 2009 9:57 pm

mysql query

Post by peteblair »

I have the following sql and code which will return either a null set or a single row with one column.

Code: Select all

$sqlGetOrderID = "SELECT `Order_Id` FROM `Order` WHERE `Session_Id` = '$seshID'";
$result = mysql_query($sqlGetOrderID);
$row = mysql_fetch_object($result);
if($row->Order_Id <> "") { $orderID = $row->Order_Id; }
else $orderID = -1; 
Being very new to this, I'm wondering if there is a cleaner, shorter, or more elegant way to check if there is a result set and set the variable to either the return value or -1. This seams like a lot of code to check for a single return value.

Any thoughts would be much appreciated.

Thanks!
User avatar
Robert07
Forum Contributor
Posts: 113
Joined: Tue Jun 17, 2008 1:41 pm

Re: mysql query

Post by Robert07 »

Hello,
You can check for a result using the following:

Code: Select all

 
$sqlGetOrderID = "SELECT `Order_Id` FROM `Order` WHERE `Session_Id` = '$seshID'";
$result = mysql_query($sqlGetOrderID);
if (mysql_num_rows($result)>0) {
  $row=mysql_fetch_array($result);
  $orderID = $row['Order_id'];
} else $orderID = -1;
 
The code isn't really shorter, but if there are a lot of empty results then it saves a step during those executions of the script.
Regards,
Robert
peteblair
Forum Newbie
Posts: 2
Joined: Tue Sep 22, 2009 9:57 pm

Re: mysql query

Post by peteblair »

Thanks Robert!
Post Reply