SQL错误(错误:无法执行INSERT INTO)

时间:2017-07-05 15:20:46

标签: php mysql sql database

我有一个我在phpmyAdmin上创建的数据库,它包含三列:id,name和number。 我通过phpmyadmin向数据库添加了3行数据。 我现在希望通过我的php文件向这个数据库添加数据。这是我用来添加数据并在浏览器上显示数据的代码:

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myfirstsite";

// Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}

$sql = "INSERT INTO hi (id, name, number)
VALUES ('99', 'Doe', '999999')";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}


//displaying data
$sql = "SELECT id, name, number FROM hi";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "id: " . $row["id"]. " - Name: " . $row["name"]. " " .                    $row["number"]. "<br>";
}
} else {
echo "0 results";
}

$conn->close();
?>

问题是我不明白为什么新数据没有放入数据库,但当前数据显示在屏幕上。

2 个答案:

答案 0 :(得分:2)

在您的代码中,您引用的$link不存在,应该是$conn

Chaneg this:

if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

答案 1 :(得分:-2)

您需要修复此问题

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

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

这也需要修复

if(mysqli_query($conn, $sql)){
     echo "Records inserted successfully";
}else{
     echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}