Dylan Lynch Dylan Lynch - 5 months ago 10
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:

<body>
<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" />
</form>
</body>


PHP code:

<?php
if(isset($_POST["submit"]))
{
require ("sql_connect.php");
mysql_select_db("project");
mysql_query("INSERT INTO `groups`(`name`) VALUES ('$_POST[name]')");
header( "Location: index.php" );
}
?>


sql_connect:

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

You are Conflicting MySQL and MySQLi

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

FYI :

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