我之前写过这样简单的代码,但我现在无法让它工作..我做错了什么?单击“添加”后,它只会将我发送回索引而不添加任何内容。
HTML页面上的表单:
<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代码:
<?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);
}
?>
数据库名为'project',表'groups',并且列有'id'(a.i。)和'name'。
答案 0 :(得分:0)
您正在冲突 MySQL 和 MySQLi
$conn = new mysqli($servername, $username, $password, $dbname); # MySQLi
mysql_query("INSERT INTO `groups`(`name`) VALUES ('$_POST[name]')"); # MySQL
仅供参考:
使用MySQLi。 Bcz MySQL扩展在PHP 5.5.0中已弃用,并且已在PHP 7.0.0中删除。相反,应该使用MySQLi或PDO_MySQL扩展名。
答案 1 :(得分:0)
用以下代码替换您的PHP代码:
<?php
if(isset($_POST["submit"]))
{
require ("sql_connect.php");
mysqli_query($conn,"INSERT INTO `groups`(`name`) VALUES ('$_POST[name]')");
header( "Location: index.php" );
}
?>