Reputation: 3
I am a little new to php, and I am trying to retrieve a raw from the database and the result is always empty. I have used the following code to insert a record in the table and it worked.
INSERT INTO `registeration`.`cars` (`lnumber`, `type`, `model`, `motor`, `owner`
,`expdate`) VALUES ('123654', 'Nissan maxima', '2008',
'1500', 'name name', '2013-11-30');
The result was 1 raw inserted
The code used in the php file is:
if (isset($_GET["lnumber"])) {
$lnumber = $_GET['lnumber'];
echo $lnumber;
$result = mysql_query("SELECT * FROM cars WHERE lnumber = $lnumber");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
....code....
}
} else {
// no car found
$response["success"] = 0;
$response["message"] = "No cars found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
However, the results are always: 123654{"success":0,"message":"No cars found"}
Upvotes: 0
Views: 2671
Reputation: 11117
Just remove this test if (!empty($result))
and add die(mysql_error());
$result = mysql_query("SELECT * FROM cars WHERE lnumber = $lnumber") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
....code....
} else {
// no car found
$response["success"] = 0;
$response["message"] = "No cars found";
// echo no users JSON
echo json_encode($response);
}
Upvotes: 0
Reputation: 769
First, you'll want to look into moving away from mysql_*
and into mysqli_*
or PDO. Second, you need to fetch the information appropriately:
$result = mysql_query("SELECT * FROM cars WHERE lnumber = '$lnumber'");
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo $row['car'];
}
}
else
{
// No cars.
}
Then do whatever it is you're going to do with the database information.
Upvotes: 0
Reputation: 360572
Your code is incorrect. The mysql function return boolean false on FAILURE, e.g. when an error occurs. mysql_query either return a result handle (query ran successfully) or a boolean FALSE (something blew up).
A result set which has no rows is NOT an error. It's simply an empty set. The code should be more like
$result = mysql_query($sql) or die(mysql_error()); // handle any error conditions
if (mysql_num_rows($result) == 0) {
echo 'no records found';
} else {
... build your json here ...
}
And as others have said above, the mysql_*() functions are obsolete and deprecated. You should be using mysqli or PDO instead.
And again as others have said, you are vulnerable to SQL injection attacks. Read up and learn about how to prevent those before you do any more work with PHP/sql
Upvotes: 1