我正在用PHP编写一个简单的代码来测试我的MySql服务器,将数据插入我的数据库服务器
我正在从互联网上执行该文件
执行的网址:Scores2.php?n=asdad&l=345&s=241
PHP代码:
<?php
$servername = "sql3.freesqldatabase.com";
$username = "MY USERNAME";
$password = "MY PASSWORD";
$dbname = "MY DBNAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = (string)$_GET['n'];
$score = (int)$_GET['s'];
$level = (int)$_GET['l'];
$sql = "INSERT INTO HighScores (name, score, level)
VALUES ($name, $score, $level)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
当我执行文件时,浏览器会显示以下错误:
Error: INSERT INTO HighScores (name, score, level) VALUES (asdad, 241, 345)
Unknown column 'asdad' in 'field list'
我检查了 phpMyAdmin 中的控制面板并执行了相同的语句,但没有变量,并且有效
行类型:
名称:文字
得分:int(11)
级别:int(11)
答案 0 :(得分:2)
$sql = "INSERT INTO HighScores (name, score, level)
VALUES ('$name', '$score', '$level')";
像这样更改查询
答案 1 :(得分:2)
num_rows
检查是否已插入记录$conn->error
调用返回false,请使用prepare()
。
$name = (string)$_GET['n'];
$score = (int)$_GET['s'];
$level = (int)$_GET['l'];
$sql = "INSERT INTO HighScores (name, score, level)
VALUES (?, ?, ?)";
if ($stmt = $conn ->prepare($sql)) {
$stmt->bind_param("s", $name);
$stmt->bind_param("i", $score);
$stmt->bind_param("i", $level);
$stmt->execute();
if($stmt->num_rows > 0){
echo "New record created successfully";
}else{
echo "no rows affected";
}
$stmt->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn ->close();