php - 如何避免在 php mysql 中插入相同的主键和值

标签 php mysql database mysqli

请检查下面我的代码。当我向类型转换和电影表插入值时,我得到了不同的主键,但得到了相同的值。我想将所有相同的值放入一个主键(expendables 3 应该在主键 19 中)。这可能吗?对了,我的主键是auto_increment。见下图。

movie
movie_no movie_name         release_year
      38 Expendables 3      2013-02-13
      40 Kiss of the Dragon 2014-10-03

actor
actor_no name
      81 Jet Li
      82 Sylvester Stallone

movie_actor
movie_no actor_no rate 
      51        0 Good
      48       91 Excellent
       0       92 Excellent
       0       93 Excellent

.

$dbc = @mysqli_connect('localhost','root','black98765','activity_7b')
       OR die("Could not connect to MySQL: ".mysqli_connect_error());

//insert into actor table
$q = "INSERT INTO actor (name)
    VALUES ('$actor')
    ON DUPLICATE KEY UPDATE
    name='$actor'";
//execute the query to get primary key value
$r = mysqli_query($dbc,$q);
//assign to variable below
$actor_no = mysqli_insert_id($dbc);

//insert into movie table   
$q2 = "INSERT INTO movie (movie_name, release_year)
        VALUES ('$movie',DATE_FORMAT('$year','%Y-%m-%d'))
        ON DUPLICATE KEY UPDATE
        movie_name='$movie', release_year=DATE_FORMAT('$year','%Y-%m-%d')";
//execute the query to get primary key value        
$r2 = mysqli_query($dbc,$q2);
//assign to variable below
$movie_no = mysqli_insert_id($dbc);

$q3 = "INSERT INTO movie_actor (movie_no, actor_no, rate)
        VALUES ($movie_no, $actor_no, '$rate')";        
//connect and insert $q 
$r3 = mysqli_query($dbc,$q3);
if($r && $r2 && $r3){
    echo "Inserted Successfully!";
}else{
    echo "Failed to Insert Data!";
    mysqli_error($dbc);
}
mysqli_close($dbc);
?>

.

<?php
if(isset($_POST['submit'])){
    if($_SERVER['REQUEST_METHOD'] == 'POST'){
        $error = array();
        //choose actor
        if(!isset($_POST['actor'])){
            $error[] = "Please choose of the following actors!";
        }else{
            $actor = $_POST['actor'];           
        }
        //choose movie
        if(!isset($_POST['movie'])){
            $error[] = "Please choose of the following movies!";
        }else {
            $movie = $_POST['movie'];               
        }
        //choose release year
        if(!isset($_POST['year'])){
            $error[] = "Please choose of the following release year!!";
        }else{
            $year = $_POST['year'];
        }
        //choose rate
        if(!isset($_POST['rate'])){
            $error[] = "Please choose of the following rate!";
        }else{
            $rate = $_POST['rate'];
        }
        //if no errors
        if(empty($error)){
            require('connect.php');
        }else{
            echo "<p>System Error!</p>";
            foreach($error as $msg){
                echo $msg."<br/>\n";
            }
        }       
    }
}
?>
<form action="form.php" method="POST">
<p>Select the Actor and the Movie they Starred In</p>

<p><label for="actor">Name of Actor:</label></p>
<ul><input type="radio" name="actor" value="Jet Li"/>Jet Li
<input type="radio" name="actor" value="Sylvester Stallone"/>Sylvester Stallone
<input type="radio" name="actor" value="Jason Statham"/>Jason Statham</ul>

<p><label for="movie">Name of Movie:</label></p>
<ul><input type="radio" name="movie" value="Expendables 3"/>Expendables 3
<input type="radio" name="movie" value="Rocky"/>Rocky
<input type="radio" name="movie" value="Kiss of the Dragon"/>Kiss of the Dragon</ul>

<p><label for="year">Release Year:</label>
<input type="text" name="year" placeholder="yyyy-mm-dd" value="<?php if(isset($_POST['submit'])) echo $_POST['year'];?>"</p>

<p><label for="rate">Rate:</label>
<input type="radio" name="rate" value="Excellent"/>Excellent
<input type="radio" name="rate" value="Good"/>Good
<input type="radio" name="rate" value="Worst"/>Worst</p>
<p><input type="submit" name="submit" value="Insert"/></p>
</form>

最佳答案

首先让我说,你不应该在生产中使用你的代码,因为你可以将它用于 sql 注入(inject)。但是为了学习,你必须有解决这个问题的可能性:

  1. 首先通过附加查询检查电影是否已存在于您的数据库中:

    SELECT * FROM movie where movie_name=$movie

  2. 您在 movie_name 列上设置了唯一约束。但是你必须确定,检查插入查询是否没有失败:

    改变表电影 添加约束 movie_name UNIQUE (movie_name);

但最好的方法是,使用唯一约束并检查电影是否已经存在。

编辑1

您必须检查表中是否已经存在 Actor 和电影。如果他们存在,你必须从数据库中获取他们的 id (actor_no, movie_no):

$dbc = @mysqli_connect('localhost', 'root', 'black98765', 'activity_7b')
OR die("Could not connect to MySQL: " . mysqli_connect_error());

$actor_query = "SELECT * FROM actor where name='$actor'";

$actor_result = mysqli_query($dbc, $actor_query);
$actor_data = mysqli_fetch_array($actor_result, MYSQLI_NUM);

$actor_no = null;

// Check if actor already exists
if ($actor_data[0] > 1) {
    // Actor already exists in the table, so we get just the primary id from the existing
    $actor =  mysqli_fetch_assoc($actor_result);
    $actor_no = $actor['actor_no'];
} else {
    // Actor does not exist in the table, so we will create a new entry
    //insert into actor table
    $q = "INSERT INTO actor (name) VALUES ('$actor')";
    //execute the query to get primary key value
    $r = mysqli_query($dbc, $q);
    //assign to variable below
    $actor_no = mysqli_insert_id($dbc);
}

// Do the same with the movie ...

此代码并不完美(sql 注入(inject)),但它应该可以解决问题。

更新 调试代码告诉我,问题比预期的要多,错误的列名...。使用以下代码它应该可以工作:

<?php
$dbc = @mysqli_connect('localhost', 'root', 'black98765', 'activity_7b')
OR die("Could not connect to MySQL: " . mysqli_connect_error());

$actor_query = "SELECT * FROM actor where name='$actor'";

$actor_result = mysqli_query($dbc, $actor_query);

$actor_data = mysqli_fetch_array($actor_result);

$actor_no = null;

// Check if actor already exists
if (isset($actor_data['actor_no'])) {
    $actor_no = (int)$actor_data['actor_no'];
} else {
    // Actor does not exist in the table, so we will create a new entry
    //insert into actor table
    $q = "INSERT INTO actor (name) VALUES ('$actor')";
    //execute the query to get primary key value
    $r = mysqli_query($dbc, $q);

    if ($r) {
        echo "Inserted actor successfully!";
        //assign to variable below
        $actor_no = mysqli_insert_id($dbc);
    } else {
        echo "Failed to insert actor data!";
        mysqli_error($dbc);
    }
}
//insert into movie table
$movie_query = "SELECT * FROM movie where movie_name='$movie'";

$movie_result = mysqli_query($dbc, $movie_query);

$movie_data = mysqli_fetch_array($movie_result);

$movie_no = null;
// Check if movie already exists
if (isset($movie_data['movie_no'])) {
    $movie_no = $movie_data['movie_no'];
} else {
    //movie does not exist in the table, so we will create a new entry
    //insert into actor table
    $q2 = "INSERT INTO movie (movie_name, release_year) VALUES ('$movie',DATE_FORMAT('$year','%Y-%m-%d'))";
    //execute the query to get primary key value
    $r2 = mysqli_query($dbc, $q2);

    if ($r2) {
        echo "Inserted move successfully!";
        //assign to variable below
        $movie_no = mysqli_insert_id($dbc);
    } else {
        echo "Failed to Insert Data!";
        mysqli_error($dbc);
    }


}
if (null !== $movie_no && null !== $actor_no) {
    $q3 = "INSERT INTO movie_actor (movie_no, actor_no, rate) VALUES ($movie_no, $actor_no, '$rate')";

//connect and insert $q
    $r3 = mysqli_query($dbc, $q3);
    if ($r3) {
        echo "Inserted Successfully!";
    } else {
        echo "Failed to Insert Data!";
        mysqli_error($dbc);
    }

} else {
    echo "Failed to Insert Data!";
}
mysqli_close($dbc);
?>

希望它现在能工作。

关于php - 如何避免在 php mysql 中插入相同的主键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28924343/

相关文章:

php - 未捕获的 PPConnectionException Http 响应代码 400

php - 无法从mysql查询获取数据到 Controller

php - 任何特殊的 php 函数可以使字符串 'url' 对地址栏友好?

python - 在/管理控制台中加载新模型时出现问题

mysql - 从 mysql 目录外的 mysql 表查询?

mysql - Phalcon 更新模型不起作用

php - 我无法删除 Magento 2.2.6 中生成的文件夹/代码

mysql - 使用代理键时插入表

php - MySQL数据库设置帮助

sql - 如何创建一个 CHECK 约束,允许用户从今天起只输入 DateTime?