【问题标题】:How can I insert into 2 table in PHP?如何在 PHP 中插入 2 个表?
【发布时间】:2018-12-13 22:05:17
【问题描述】:

我在 MySQL 中有 3 个表:

  • 国家

  • 语言

  • country_language(它有另外 2 个表的 id)

我想将namedescription 插入country 表,将country idlangid 插入country_language 表。

我该怎么做?

它在更新部分工作,但是当我想添加一个新国家时,它没有将 2 个 id 插入 country_language,只是名称和描述。

php

$name = mysqli_real_escape_string($connect, $_POST["name"]);  
$description = mysqli_real_escape_string($connect, $_POST["description"]); 
$id=$_POST["country_id"];

if($id != '')  
{  
    // Update query     
    $message = 'Data Updated';    

}  
else  
{  
    mysqli_query($connect, "START TRANSACTION");
    mysqli_query($connect, "INSERT INTO country(name, description) VALUES('$name', '$description')");
    if(is_array($_POST["language"])) {
        $values = Array();
        foreach($_POST["language"] as $c2_id) $values[] = "($id, $c2_id)";

        mysqli_query($connect, "INSERT INTO country_language(country_id, language_id) VALUES ".implode(",", $values));
    }
    mysqli_query($connect, "COMMIT");        
    $message = 'Data Inserted';

}  

【问题讨论】:

  • 您对 SQL 注入持开放态度:您不得在查询中使用原始用户输入。查看准备好的语句
  • the manual 对这么多人来说是个谜
  • 请查看 PHP PDO 和准备好的语句。这种编码现在太过时了。
  • 使用多个逗号分隔值列表不是标准 SQL,并且与执行单独查询相比并没有任何好处。如果您进行常规插入,那么代码看起来会更干净且更便携。还要检查您的 $_POST 数组以确保 $_POST["language"] 确实是一个数组

标签: php mysql


【解决方案1】:

实际上,在更新期间,您将 $id 作为国家/地区 id 并且可能在您的表中 country_languagecountry_id 不为空,这就是为什么要更新它的工作

进入代码的插入部分或其他部分,$id 什么都没有,您也没有将新插入的国家/地区 ID 的值分配给 $id,因此使代码什么都不做

您可以做的只是在检查$POST['language']的if条件之前使用下面的代码获取插入国家表的行的最后插入ID

$id = mysqli_insert_id($connect);

然后使用这个$id 插入到country_language 表中,它会工作

【讨论】:

    【解决方案2】:
    // Using prepared statements you dont need to do this, and its safer    
    // $name = mysqli_real_escape_string($connect, $_POST["name"]);  
    // $description = mysqli_real_escape_string($connect, $_POST["description"]); 
    
    $id = isset($_POST["country_id"]) ? $_POST["country_id"] : '';
    
    if($id != '') {  
        // Update query   
        . . .
    
        $message = 'Data Updated';    
    } else {  
        $connect->begin_transaction();
        $sql = "INSERT INTO country (name, description) 
                    VALUES(?,?)");
        // prepare the query and bind paramters to the ?
        $ins = $conect->prepare($sql);
        $ins->bind_params('ss', $_POST["name"], $_POST["description"]);
        // execute the query
        $res = $ins->execute();
    
        // test to see if insert worked
        if ( ! $res ) {
            // insert failed.
            echo $connect->error;
            // no rollback required as nothing has been updated anyway
            exit;
        }
    
    
        // capture the new id created by above INSERT
        $new_ctry_id = $connect->insert_id;
    
        // Using a foreach loop so it will run 
        // for each occurance in $_POST["language"]
        // so only need to check it exists
    
        if(isset($_POST["language"])) {
            // prepare the statement outside the loop 
            // and execute it with new params as many times as you like
            $sql = "INSERT INTO country_language 
                        (country_id, language_id) VALUES(?,?)";
            $ins2 = $connect->prepare($sql);
    
            foreach($_POST["language"] as $lang) {
                // bind the new parameters each time round the loop
                $ins2->bind_params('is', $new_ctry_id, $lang);
    
                $res = $ins2->execute();
    
                // test to see if insert worked
                if ( ! $res ) {
                    echo 'Insert of languages failed with ' . $connect->error;
                    // run rollback to remove the insert of the country
                    $connect->rollback();
                    exit;
                }
            }
        }
    
        // if we get here, all is well and we must commit the changes we made
        $connect->commit();
    
        $message = 'Data Inserted';
    }  
    

    【讨论】:

      猜你喜欢
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-24
      相关资源
      最近更新 更多