Dylan Lynch Dylan Lynch - 1 year ago 43
SQL Question

Why doesn't this simple PHP code to add data to my db work?

I wrote simple code like this before but I can't get it to work now.. What do I do wrong? After clicking 'Add' it just sends me back to index without adding anything.

Form on the HTML page:

<h1>Project groups</h1>
<a href="index.php">Back</a>
<form name="groupadd" action="" method="POST">
name group: <input type="text" name="name" placeholder="Group C" />
<input type="submit" name="submit" value="Add" />

PHP code:

require ("sql_connect.php");
mysql_query("INSERT INTO `groups`(`name`) VALUES ('$_POST[name]')");
header( "Location: index.php" );


$servername = "localhost";
$username = "root";
$password = "usbw";
$dbname = "project";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);

The database is called 'project', the table 'groups' and it has the columns 'id'(a.i.) and 'name'.

Answer Source

You are Conflicting MySQL and MySQLi

$conn = new mysqli($servername, $username, $password, $dbname); # MySQLi
mysql_query("INSERT INTO `groups`(`name`) VALUES ('$_POST[name]')"); # MySQL


Use MySQLi. Bcz MySQL extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.

Check this answer