简体   繁体   中英

PHP insert query issue (foreign key)

I'm trying to insert values in a table with a foreign key through php. The table is called games (id, title, year,genre, publisher_id). The other table does not contain foreign keys and it is as it follows: publisher (id,company, adress, prizes, published)...

Here's the code:

<h4>Insert new Game</h4>
    <form method="get">    

        <input type="text" name="new-game"                      
            <button type="submit">Submit Game</button>
    </form>

<?php



  if (isset($_GET["new-game"])){
     require("MGconfig.php");

      $newgame= $_GET["new-game"];


      $id= mysqli_query($connection, "select max(id) from games");
      $maxid= mysqli_fetch_row($id)[0]+1;
      $publisher_id=mysqli_query($connection, "select title, company from publisher, games where publisher.id=publisher_id");



      $insert ="insert into games (title, id, publisher_id) values (".$newgame.",".$maxid.",".$publisher_id.")";

      $result=mysqli_query($connection,$insert);

      if (!$result) {
        echo "Erro na query ..." .mysqli_error($connection);
      }
   }


   ?>

I get this error (points to the $insert line):Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\\xampp\\htdocs\\PHP\\MG_Dinamico\\admin.php on line 127

This is the config file:

    <?php

    $user = 'root';
    $pwd = '';
    $server = 'localhost';
    $bdschema = 'MG';


    $connection = mysqli_connect($server,$user, $pwd, $bdschema);

if (mysqli_connect_error()) {
    echo "Error to DB ..." .mysqli_error($connection);
    exit;
};

mysqli_set_charset($connection, "utf8");
//print_r($connection);


?>

I dont know how to put the query working...suggestions? Thanks in advance!

You are getting this:

$publisher_id=mysqli_query($connection, "select title, company from publisher, games where publisher.id=publisher_id");

is returning an object, maybe an array

and in this line :

$insert ="insert into games (title, id, publisher_id) values (".$newgame.",".$maxid.",".**$publisher_id**.")";

you aren't passing an string but the object.

I think that could be the error

First you have to make the query fetch after the query executes eevn if it is for the single row or for multiple rows of data.

Note: Another important thing is that you cant get the id from the select statement which you have made since you are selecting only the title,company from publisher so that you have to include id also in that select statement.

$publisher_id=mysqli_query($connection, "select id title, company from publisher, games where publisher.id=publisher_id");

After that you have to run the fetch loop so that it fetches the value and you can select the publisher id from that.

<?php
$publisher_id=mysqli_query($connection, "select id title, company from publisher, games where publisher.id=publisher_id");
$count = $publisher_id->num_rows;
if($count==0)
{
    $pub_id='';
}
else
{
    while($row =$publisher_id->fetch_assoc())
    {
        $pub_id = $row['id'];// This will store the publisher ID
    }
}
?>

Now you can insert the data into the foreign key table so that it will have some values that matches the corresponding limit.

$insert ="insert into games (title, id, publisher_id) values ('".$newgame."','".$maxid."','".$pub_id."')";

Assuming the publisher id to be NULL in the foreign key relation table.

SUGGESTION FOR THE POSTED ANSWER OF icenine

Note: It is not advised to post the code as answer and then ask for corrections first. If you are the owner of the question you can directly re-edit the question ad post over there. Please follow the SO rules and regulations when you are over here which has tones of people really wanting to help the needy.

Error: 1

Question:

Notice: Trying to get property of non-object in C:\\xampp\\htdocs\\PHP\\MG_Dinamico\\admin.php on line 125.

The below select query that you have made will never work.

  $publisher_id=mysqli_query($connection, "select id, title, company from publisher, games where publisher.id=publisher_id");

This error comes from the admin.php since you don't get any value from the above select statement.

Answer with Explanations:

Since in the Where condition you have used publisher.id=publisher_id which is totally not advisable. You will not be getting any publisher_id in the query and the query will return FALSE . Please follow the note below this line and check what is wrong in your Statement and then you proceed further.

Ensure you have the correct query over here and then your entire code will work well.

Note: You first put echo to the Select Statement and then break the execution by putting the exit; and you copy the statement that is echoed and place it in SQL of the DB and then check whether any error occurs in insertion. If no error occurs remove the echo and delete the exit;

After you get the result from the above query you will get the publisher id and after that you can insert the data into the another table.

Error:2

Change the Insert Query as per the suggestion given (foreign key table) you are missing the ticks over the table column values.

Now you can insert the data into the foreign key table so that it will have some values that matches the corresponding limit.

$insert ="insert into games (title, id, publisher_id) values ('".$newgame."','".$maxid."','".$pub_id."')";

Assuming the publisher id to be NULL in the foreign key relation table.

Since sometimes it may not have the relations ID.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM