【问题标题】:How to select latest ID to create new rows in new table in same PHP file?如何选择最新的 ID 在同一个 PHP 文件的新表中创建新行?
【发布时间】:2026-02-03 16:50:02
【问题描述】:

我想通过输入名称在 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;
    }
?>

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    首先,请不要使用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');
    

    【讨论】:

    • 感谢您的建议!顺便问一下,PDO 是一种新型的 mySQL 编码吗?因为我是 mysql 的初学者..
    • 简而言之,PDO 是一个扩展,它抽象了与数据库服务器的连接,并自动处理其他任务,例如正确转义传入的值。虽然一开始学习可能看起来很吓人,但值得努力学习它是如何工作的,因为坚持使用 mysql_* 类型函数的好处远远超过了坏处
    【解决方案2】:

    这是一件容易的事。

    如果查询成功执行,您的 addRestaurant 代码不应返回 true,而是应返回最后插入的 id。你的代码应该如下所示

    $response = array();  
    
    $name = "test1"; 
    
    if ($rid = addRestaurant($name) == true){
        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(); //This will return the last inserted id
            return $rid;
        } else { 
            return false;
        }   
    }
    
    function addRating($rid){
        //$test = mysql_query("SELECT MAX(RID) FROM restaurants");
        //$return = mysql_fetch_assoc($test); 
        //$rid = $return['MAX(RID)'];
    
        $result = mysql_query("INSERT INTO rating(`Clealiness`, `Service`, `Quality`, `RID`) VALUES (0, 0, 0, $rid");
        if ($result) {
            return true;
        } else {
            return false;
        }
    ?>
    

    希望这能解决您的问题。 谢谢

    【讨论】:

    • 感谢您的建议,它仍然显示相同的错误..我可以知道您的代码中的 line3 有什么错误吗?
    • 我刚刚复制了您的代码并对其进行了调整。如果可能有错误,但我不能说没有看到错误。你能启用错误吗?将 error_reporting(1) 放在该 php 文件的顶部,然后编辑您的帖子并放置您收到的错误消息。这样我就可以看到错误并为您提供相应的帮助。
    • 我编辑了我尝试过的最新版本.. 结果触发 (addRating == true) 为假。为什么插入是假的?我在 mySQL 的查询中尝试过,它有效.. 很奇怪..
    【解决方案3】:

    您的表结构在这里很重要。如果您正在为两个表的 ID 使用增量 ID,则可以使用 mysqli_insert_id (http://www.php.net/manual/en/mysqli.insert-id.php) 从您的第一个查询中获取最后插入的 ID。

    1) 添加餐厅 2)在您的代码中选择您的最后一个插入ID 3) 附加到您的评分查询

    试试 Julian H. Lam 的 PDO,因为它也很有效。

    【讨论】:

      最近更新 更多