-3

I am trying to insert a new game and an image into my database and I have the following code:

$insert_query = "INSERT INTO Games (name, release_date, description, developer, publisher)
VALUES ('$name', '$release_date', '$description', '$developer', '$publisher')";
$insert = mysqli_query($mysql,$insert_query);

if (!$insert)
{
    echo("Error description: " . mysqli_error($mysql));
}
$row = mysqli_fetch_assoc($insert);
$id = $row['id'];

echo $id;

$newImageName =  "games".$id.".".$imageExt2;
$imageDestination = 'GamePictures/'.$newImageName;
move_uploaded_file($imageTmpName, $imageDestination);
$update_query = "UPDATE Games SET image = '$newImageName' WHERE name = '$name'";

The row gets inserted in the database, but I still get the error and it doesn't print an error message. Because of this error I also get a move_uploaded_file: failed error.

Does anyone know how I can fix this?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Max de Boer
  • 262
  • 3
  • 10
  • Why aren't you setting the name when you do the insert? You should parameterize your query. Do you execute the update? – user3783243 Jan 27 '20 at 22:52
  • Probably need https://www.php.net/manual/en/mysqli.insert-id.php for `$id` assignment (although doesn't really make sense as previously noted) – user3783243 Jan 27 '20 at 23:04

2 Answers2

3

You can't fetch data from an INSERT query; it doesn't provide a result set, only a true/false success indication (see the manual or @BillKarwin answer). To achieve what (I presume) you are trying to do (fetch the last insert id) just use mysqli_insert_id:

$id = mysqli_insert_id($mysql);
Nick
  • 138,499
  • 22
  • 57
  • 95
2

Read the documentation: https://www.php.net/manual/en/mysqli.query.php

For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

Since your SQL is INSERT, and INSERT does not return a result, this line will return TRUE.

$insert = mysqli_query($mysql,$insert_query);

The boolean value TRUE is not a mysqli_result object, so you can't use it as the argument to a function that needs a mysqli_result.

It makes no sense to try to fetch results from an INSERT in MySQL.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828