Page 1 of 1
Mysql Select Where
Posted: Mon Jul 21, 2008 11:54 pm
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
Re: Mysql Select Where
Posted: Tue Jul 22, 2008 1:34 am
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)
}
Re: Mysql Select Where
Posted: Tue Jul 22, 2008 3:16 am
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