我正在尝试读写数据库。这是我到目前为止的代码:
$mysql = mysqli_connect("example.com", "johndoe", "abc123"); // replace with actual credidentials
$username = mysqli_real_escape_string("username");
$sql = "CREATE DATABASE IF NOT EXISTS dbname";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating database: " . mysqli_error($mysql);
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($mysql);
$mysql = mysqli_connect("example.com", "johndoe", "abc123", "dbname"); // replace with actual credidentials
$sql = "CREATE TABLE IF NOT EXISTS Users(ID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(ID), username CHAR(15), password CHAR(15), email CHAR(50))";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating table: " . mysqli_error($mysql);
}
$sql = "INSERT INTO Users(username, password, email) VALUES(" . $username . ", " . $password . ", " . $email . ")";
if (!mysqli_query($mysql, $sql)) {
echo "Error: " . mysqli_error($mysql);
}
mysqli_close($mysql);
但是,当我尝试运行它时,它有一个错误:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , )' at line 1
有人能告诉我如何解决这个问题吗?
答案 0 :(得分:1)
mysqli_real_escape_string也需要连接参数......
$username = mysqli_real_escape_string($mysql,"username");
答案 1 :(得分:0)
重写你的第二个SQL查询..
$sql = "INSERT INTO Customers(`username`, `password`, `email`) VALUES ('$username','$password','$email')";
问题是有不正当的逃避。
Sidenote:
切换到 PreparedStatements
可以更好地抵御SQL注入攻击!
答案 2 :(得分:0)
使用preapred语句:http://hu1.php.net/mysqli_prepare他们会自动逃避参数...
顺便说一下。你最后一个sql中的params没有被正确地转义和连接。
答案 3 :(得分:0)
在插入数据库 you can use below function to santizie them properly,
之前转义字符并使其清晰<?php
function cleanInput($input) {
$search = array(
'@<script[^>]*?>.*?</script>@si', // Strip out javascript
'@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags
'@<style[^>]*?>.*?</style>@siU', // Strip style tags properly
'@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments
);
$output = preg_replace($search, '', $input);
return $output;
}
?>
最后输出时,要在页面上转义'
,请使用:
htmlspecialchars($quote_str, ENT_QUOTES);
或htmlentities($quote_str, ENT_QUOTES);