1

I am creating a function that will retrieve an id number from a table with multiple columns, put it in a variable which i want to use to send as a "claims number" in an email to a claimant and also echo on a confirmation screen. Here's what I have so far.

$sql = "SELECT id FROM warranty_claim where lname=$lname";
$result = mysql_query($sql);
$claim_id = $result;
Cœur
  • 37,241
  • 25
  • 195
  • 267
Scott Morrison
  • 153
  • 1
  • 8
  • 4
    Your code is vulnerable to SQL injection; also mysql_* suite of functions are deprecated. Consider using mysqli or PDO - this SO article can assist you further: http://stackoverflow.com/questions/1457131/php-pdo-prepared-statements – Dogoferis Apr 22 '13 at 14:26
  • mysql_query returns a result handle. you need to fetch a row from that handle, which will contain the per-row data. – Marc B Apr 22 '13 at 14:26
  • I'm vulnerable? I don't know much about that, how would I protect it? – Scott Morrison Apr 22 '13 at 18:13

5 Answers5

1
$result = mysql_fetch_array(mysql_query($sql));

$claim_id = $result['id'];
Ian Brindley
  • 2,197
  • 1
  • 19
  • 28
  • The shortest and the most simplistic approach. This definitely deserves an upvote. Don't ignore other comments that recommend you switch to PDO and MySQLi though. – Dzhuneyt Apr 22 '13 at 14:30
  • @ColorWP.com I figured there was enough rants about PDO and MySQLi about the place that someone clearly new to database programming didn't need an ear bashing :) Yet... :) – Ian Brindley Apr 22 '13 at 14:34
1

Supposing you are sure that you will receive 1 row.

$sql = "SELECT id FROM warranty_claim where lname=$lname";
$result = mysql_query($sql);
$c = mysql_fetch_assoc($result);
$claim_id = $c['lname'];

NB*: And get ready for a lecture. Someone is going to tell you that mysql is depracated. Start using MySQLi or PDO (recommended).

Touch
  • 1,481
  • 10
  • 19
0

Try :

$sql = "SELECT id FROM warranty_claim where lname=$lname";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$claim_id = $row[0];

or

$sql = "SELECT id FROM warranty_claim where lname=$lname";
$result = mysql_query($sql);

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
   $claim_id = $row['id'];
}
Antoine
  • 548
  • 4
  • 13
0

$row = mysql_fetch_array($result);

$claim_id = $row['id'];

please note that you should also check for errors (e.g. if($result === FALSE)). Also, there are other ways to fetch data - I recommend looking at mysql_fetch_array, mysql_fetch_row, mysql_fetch_assoc and mysql_fetch_object

Also, don't rely on the statement always returning exactly one row - make sure that the result is as expected: mysql_num_rows

MarioP
  • 3,752
  • 1
  • 23
  • 32
-1

Give this a try:

$sql        = "SELECT id FROM warranty_claim where lname='".$lname."'";
$result     = mysql_query($sql);
$objResult  = mysql_fetch_array($result);  
$claim_id   = $objResult['id'];
Daanvn
  • 1,254
  • 6
  • 27
  • 42