Scott Morrison
Scott Morrison

Reputation: 153

How to I retrieve data from a mysql table cell and put it into a variable in php?

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;

Upvotes: 1

Views: 317

Answers (5)

Daanvn
Daanvn

Reputation: 1266

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'];

Upvotes: -1

MarioP
MarioP

Reputation: 3832

$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

Upvotes: 0

Antoine
Antoine

Reputation: 558

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'];
}

Upvotes: 0

Touch
Touch

Reputation: 1491

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).

Upvotes: 1

Insyte
Insyte

Reputation: 2236

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

$claim_id = $result['id'];

Upvotes: 1

Related Questions