我正在用PHP编写一个简单的代码,通过将数据插入我的数据库服务器来测试我的MySql服务器
我正在执行来自互联网的文件
执行URL: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)
- 学习如何准备查询—这并不难
- 您将避免sql注入和缺少引号
- 使用
num_rows
检查记录是否已插入 - 如果
prepare()
调用返回false,则使用$conn->error
$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();
$sql = "INSERT INTO HighScores (name, score, level)
VALUES ('$name', '$score', '$level')";
像这样的更改查询