当我尝试将数据插入数据库时出错。所以我制作了留言系统。
以下是代码:http://pastebin.com/U6SQ907H 这是sumbit代码:
if(isset($_POST['writemessage'])){
$text = $_POST['text'];
$from = $userid;
$username = $_POST['username'];
//$sql = "SELECT id FROM users WHERE username='$to'";
// $result = mysqli_query($conn,$sql);
// $sendto = mysqli_fetch_array($result,MYSQLI_ASSOC);
$getuserid = 'SELECT ID FROM users WHERE username = "' . mysqli_escape_string($conn,$username) . '"';
$sqluserid = mysqli_query($conn,$getuserid) or die('Error connecting to database');
//$user_id = mysql_result($result, 0, "user_id");
$user_id = mysqli_fetch_array($sqluserid,MYSQLI_ASSOC);
$sendto = $user_id["ID"];
$query_send_mess = "INSERT INTO messages (from, touser, text, date, isread)
VALUES ( '$from', '$sendto', '$text',NOW(),0)";
echo "<script>alert('".$query_send_mess."')</script>";
$send_message = mysqli_query($conn,$query_send_mess) or die("Error: ".mysqli_error($conn));
if (!$send_message) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($conn) == 1) { //If the Insert Query was successfull.
echo '<div class="alert alert-success">Message sent successful </div>';
} else { // If it did not run OK.
echo '<div class="alert alert-info">You could not send message due to a system
error. We apologize for any
inconvenience.</div>';
die(mysqli_error($conn));
}
}
但是当我尝试发送消息时,我收到了这个错误:
错误:您的SQL语法出错;检查与您的MariaDB服务器版本对应的手册,以便在'from,touser,text,date,isread'附近使用正确的语法VALUES('2','3','test',NOW(),0)'at第1行
可能是什么问题
答案 0 :(得分:2)
from
是mysql中的保留关键字。你不能这样使用它。
尝试此查询:
"INSERT INTO messages (`from`, `touser`, `text`, `date`, `isread`)
VALUES ( '$from', '$sendto', '$text',NOW(),0)"
答案 1 :(得分:1)
From
是一个保留的术语,除非在反引号中才能使用。您还可以更改列名称。 https://dev.mysql.com/doc/refman/5.5/en/keywords.html
例如:
$query_send_mess = "INSERT INTO messages (`from`,
您的代码也可以按原样进行SQL注入。您应该使用参数化查询。
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php