Mysql Select Where

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
User avatar
funkyfela
Forum Newbie
Posts: 4
Joined: Sun Jul 20, 2008 6:03 pm
Contact:

Mysql Select Where

Post by funkyfela »

How do i use $sql "select from order where id = $id";
cos i used this but am not getting my results display. the idea is to display any id i want from a range.
thanks
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Mysql Select Where

Post by Apollo »

You have to specify the fields you want from your order table. Or use * if you want everything. For example:

Code: Select all

$r = mysql_query("select customer_name, total_amount from order where id=$id") or die("SQL error: ".mysql_error());
$data = mysql_fetch_assoc($r);
// now $data['customer_name'], $data['total_amount'] contain values for this id
If you want all columns, use "select * from order where id=$id"

If you want data from a range of ids instead of just one id, use "select * from order where id>=$first_id and id<=$last_id", and iterate through the resulting data like this:

Code: Select all

$r = mysql_query("select id, customer_name from order where id>=$first_id and id<=$last_id") or die("SQL error: ".mysql_error());
$n = mysql_num_rows($r);
for ($i=0; $i<$n; $i++)
{
 $data = mysql_fetch_assoc($r);
 // $data['id'], $data['customer_name'] now contain values from this row (one particular order id)
}
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

Re: Mysql Select Where

Post by Mordred »

1. Maybe MySQL has something against the column named 'order', as it is a reserved word. Always use backticks (at the tilde ~ key) around SQL names: `order`
2. Your query might be vulnerable to SQL injection, always quote end escape the values:

Code: Select all

 
$id = mysql_real_escape_string($id);
$sql = "select * from `order` where `id` = '$id'";
Read my paper for more examples
Post Reply