SQL - 错误:INSERT INTO表

时间:2016-12-13 04:52:58

标签: php sql database insert

我无法弄清楚是什么原因造成了这个插入错误。它应该只是一个简单的插入,但无论我做什么或改变它都不会接受它。我已经在多个来源验证了语法,看起来很好。

数据库和表也都打印成功消息。

以下代码:

    <?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "CREATE DATABASE IF NOT EXISTS db_test";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
mysql_select_db(db_test, $conn);
$sql = "CREATE TABLE IF NOT EXISTS test_table (
ID INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
Email VARCHAR(50) NOT NULL,)";
// create variables
$full_name=$_POST['full_name'];
$email=$_POST['email'];
//Execute the query
$sql = "INSERT INTO 'test_table' (ID, Name, Email)
            VALUES('NULL', '$full_name' , '$email')";
            if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

3 个答案:

答案 0 :(得分:0)

在您发布的代码中,以下是错误:

1.创建数据库后关闭连接,然后选择数据库。允许$conn->close();

2.选择数据库mysql_select_db(db_test, $conn);时出现语法错误。

3.您不执行create table $sql查询。

4.您将表格字段ID设置为NULL,即表格的Primary key。 希望它有效....

<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "CREATE DATABASE IF NOT EXISTS db_test";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
//select database
mysql_select_db($conn,'db_test');
$sql = "CREATE TABLE IF NOT EXISTS test_table (
ID INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
Email VARCHAR(50) NOT NULL
)";
//create table
if ($conn->query($sql) === TRUE) {
echo "table created successfully";
} else {
echo "Error creating tabel: " . $conn->error;
}
// create variables
$full_name=$_POST['full_name'];
$email=$_POST['email'];
//Execute the query
$sql = "INSERT INTO test_table (Name, Email)
            VALUES('$full_name' , '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

答案 1 :(得分:0)

查询中的表名不应该引用,因此正确的查询将是 -

INSERT INTO test_table (ID, Name, Email) VALUES('NULL', '$full_name' , '$email')

答案 2 :(得分:0)

您的ID是自动递增的,因此您无需为id

赋值

你可以这样写

INSERT INTO test_table (ID, Name, Email) VALUES(NULL, '$full_name' , '$email')

OR

INSERT INTO test_table (Name, Email) VALUES('$full_name' , '$email')