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"}
Your code is incorrect. The mysql function return boolean false on FAILURE, eg 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
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.
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);
}
谢谢大家的宝贵意见和建议,我不想以错误的方式开始,我是一名Android开发人员,我需要为正在工作的项目学习php,很高兴知道这些示例已经很老了。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.