我想通过输入名称在 RESTAURANT 表中创建一家餐厅。 RestaurantID(RID) 是自动递增的。 但与此同时,我想在 RATING 表中用最新添加的 RID 创建一行。
其他帖子中的几个问题与我的情况不同,我不知道如何解决这个问题。必须从这里寻求帮助..
这段代码的测试结果是:{"success":0,"message":"Fail to create Rating table for this restaurant!"
餐厅名称已成功添加,但评级表不起作用。有什么想法吗?还是我应该反过来将 RID 添加到评级表中?
这是我的代码:
$response = array();
$name = "test1";
if ($rid = addRestaurant($name)){
echo "$rid"; // now it displays the right id
if(addRating($rid) == true){
$response["success"] = 1;
$response["message"] = "Restaurant Successfully Created!";
echo json_encode($response);
}else{
$response["success"] = 0;
$response["message"] = "Fail to create Rating table for this restaurant!";
echo json_encode($response);
}
}else{
$response["success"] = 0;
$response["message"] = "Fail to create Restaurant! Please Try Again Later!";
echo json_encode($response);
}
function addRestaurant($name){
// mysql inserting a new row
$result = mysql_query("INSERT INTO restaurants (Name)VALUES('$name')");
// check if row inserted or not
if ($result) {
$rid = mysql_insert_id();
echo "$rid"; //this gives me correct RID of "84" latest one.
return $rid;
} else {
return false;
}
}
function addRating($rid){
echo "$rid"; // here also the latest ID. but why return false?
$result = mysql_query("INSERT INTO `rating`(`Clealiness`, `Service`, `Quality`, `RID`) VALUES ('0', '0', '0', $rid");
if ($result) {
return true;
} else {
return false;
}
?>
最佳答案
首先,不要使用mysql_query
!它已被弃用(或即将被弃用),并且很容易引入 SQL injection vulnerabilities into your code .
相反,使用类似 PDO 的库.
从那里开始,一旦您执行了 INSERT 查询,you can retrieve the last inserted ID ,并在另一个查询中使用它。
一些伪代码:
$queryObj = $dbHandler->prepare('statement');
$queryObj->execute();
$last_id = $dbHandler->lastInsertId();
$dbHandler->prepare('another statement with $last_id');
关于php - 如何选择最新 ID 以在同一个 PHP 文件的新表中创建新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15445862/