Skip to content
Advertisement

PHP fails to insert into Mysql (auto increment)


I have made my Mysql Table link this:

enter image description here enter image description here

That problem occurs because i am not able to insert auto_increment into my mysql query.

index.php

<?php

        $name=$_POST["name"];
        $description=$_POST["description"];
        $image=$_POST["image"];
        $amount=$_POST["amount"];

 $sql=mysql_query("INSERT INTO `store`(`id`, `name`, `description`, `price`, `image`) VALUES (NULL,'".$name."','".$description."','".$amount."','".$image."')");




?>

I post to it by a HTML form and it does executes the query but i get no rows in that table. I thnk its because of auto_increment or Unique or Primary. i was told to use NULL in place of auto_increment value but it doesn’t work.

Any Help?

P.S Noob here!

EDIT: error is:

Deprecated: mysql_query(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in D:xampphtdocsHtmlHomeindex.php on line 9

Advertisement

Answer

To address the Issue of mysql_query being deprecated, I recommend PDO instead. It’s super easy and much safer with prepared staements. This snippet will provide a connection to the DB to make your queries:

$mysql_host = "localhost";
$mysql_db = "my_database";
$mysql_user = "my_user";
$mysql_password = "mypassword";
$db = new PDO('mysql:host='.$mysql_host.';dbname='.$mysql_db.';charset=utf8', $mysql_user, $mysql_password);

Once you have that on your page, you can use $db to interact with your database.

$q = $db->prepare("INSERT INTO `store` (`name`, `description`, `price`, `image`) VALUES (:name, :desc, :amt, :img)");
$q->execute(array(":name"=>$name, ":desc"=>$description, ":amt"=>$amount, ":img"=>$image));

Also, for auto-imcrement values, you can omit that field all together.

PS, there’s a stntax error. You’re missing a space before the opening parenthesis: store (

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement