我的PHP代码中有一个奇怪的错误,每次我输入一个值时,它会抛出一个错误,表示第一个值不存在... 我插入数据库的第一个值($ from)是错误中的值。 我试图用其他值更改位置,但每次第一个值都有错误。 这是我的代码的问题吗?
<?php
$from = $_GET['from'];
$to = $_GET['to'];
$message = $_GET['message'];
$time = new DateTime();
$time = date('Y-m-d H:i:s');
$con = mysqli_connect("localhost","root","","encrypchat");
if(mysqli_connect_errno($con))
{
echo "Failed to connect to MySql: " . mysqli_connect_error();
}
$check="SELECT * FROM `users` WHERE `username` = '$to'";
$rs = mysqli_query($con,$check);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
echo $data[0];
echo "<br />";
if($data[0] >= 1) {
echo "<br />"."USER EXISTS";
$sql="INSERT INTO ".$to."_msgs (`from_user`, `to_user`, `message`,`time`)
VALUES (`$from`, `$to`, `$message`,`$time`)";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
if(!$data[0]){
echo "<br />"."USER DOESNT EXIST";
}
mysqli_close($con);
?>
答案 0 :(得分:1)
VALUES (`$from`, `$to`, `$message`,`$time`)";
这些应该是撇号,而不是后退,表示表或列名。
答案 1 :(得分:0)
尝试删除反引号,并在值列表中使用单引号,如
$sql="INSERT INTO ".$to."_msgs (`from_user`, `to_user`, `message`,`time`)
VALUES ('$from', '$to', '$message','$time')";
答案 2 :(得分:0)
确保您的 GET变量中包含值。
你在insert查询中的变量中使用反引号(`),它应该是单引号(&#39;)
在将变量值的字符串用于查询之前,先将其转义,以避免某些 SQL注入。
我还建议你使用 POST 方法,而不是 GET 方法,如果你有太多的变量要传递。
<?php
/* ESTABLISH CONNECTION */
$con = mysqli_connect("localhost","root","","encrypchat");
if(mysqli_connect_errno($con))
{
echo "Failed to connect to MySql: " . mysqli_connect_error();
}
/* USE MYSQLI_REAL_ESCAPE_STRING IN YOUR VARIABLES */
$from = mysqli_real_escape_string($con,$_GET['from']);
$to = mysqli_real_escape_string($con,$_GET['to']);
$message = mysqli_real_escape_string($con,$_GET['message']);
$time = new DateTime();
$time = date('Y-m-d H:i:s');
$check="SELECT * FROM `users` WHERE `username` = '$to'";
$rs = mysqli_query($con,$check); /* EXECUTE QUERY */
/* YOU CAN ALSO DIRECTLY USE IT TO $data=mysqli_num_rows($rs); AND USE $data IN YOUR CONDITIONS INSTEAD OF $data[0] */
$data = mysqli_fetch_array($rs,MYSQLI_NUM);
echo $data[0];
echo "<br />";
if($data[0] >= 1) { /* IF A RECORD HAS BEEN FOUND */
echo "<br />"."USER EXISTS";
$sql="INSERT INTO ".$to."_msgs (`from_user`, `to_user`, `message`,`time`)
VALUES ('$from', '$to', '$message','$time')"; /* YOU CAN USE BACKTICKS ON THE COLUMN NAME, BUT NOT FOR THE VARIABLES TO BE INSERTED */
if (!mysqli_query($con,$sql)) { /* IF QUERY FAILED */
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
else if(!$data[0]){ /* MADE IT INTO ELSE IF INSTEAD OF IF ONLY */
echo "<br />"."USER DOESNT EXIST";
}
mysqli_close($con);
?>