1

Please check my code below. When I insert values to the actor and movie table i get the different primary key but the the same values. I want to put all the same values into one primary key( expendables 3 should be in the primary key 19). Is this possible?By the way my primary key is auto_increment.See the picture below.

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>
1
  • Please help me out guys. Commented Mar 8, 2015 at 8:16

1 Answer 1

2

First let me say, that you shouldn't use your code in production, because you can use it for sql injection. But for learning, you have to possibilities to solve this issue:

  1. Check first if the movie already exists in your database, by an additional query:

    SELECT * FROM movie where movie_name=$movie

  2. You set an unique constraint on the movie_name column. But then you have to be sure, to check if the insert query does not fail:

    ALTER TABLE movie ADD CONSTRAINT movie_name UNIQUE (movie_name);

But the best way is, to use the unique constraint and check if the movie already exists.

Edit1

You have to check if the actor and the movie already exist in the tables. if they exists you must fetch their id (actor_no, movie_no) from the database:

$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 ...

This code is not perfect (sql injection) but it should solve the issue.

UPDATE Debugging the code shows me, that there were more issues than expected, Wrong column names... . With the following code it should work:

<?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);
?>

Hope it work now.

Sign up to request clarification or add additional context in comments.

12 Comments

I used the step 2 and it worked, for the actor and movie table. However in the movie_actor table the primary key adds another id..
@JayGorio i think this is an other issue. But can you please provide the movie_actor table definition?
Yeah there's seems an issue here because the 0 in the movie_actor table value should have an actor number..
@JayGorio I think movie_no should not be an primary key in this table, because there are many actors in a movie and typically not just one ;) so you must be able to insert one movie_no multiple times. It is more an foreign key, as actor_no should be one too. But to solve this issue you have to remove the primary key and auto_increment definition from the movie_no column.
I got you.I will try now
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.