简体   繁体   English

使用$ _SESSION的mysqli_query语法错误

[英]mysqli_query syntax error with $_SESSION used

I had got the error like this 我有这样的错误

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)

Here is my code (I used $_SESSION to get variable from the other page.) 这是我的代码(我使用$ _SESSION从另一页获取变量。)

$sql="insert into data(name,sex,time,suggest,eat,problem,student_suggest,tutor_suggest,other_suggest)   
values('$_SESSION['name']','$_SESSION['gender']','$_SESSION['time']','$_SESSION['suggest']','$_SESSION['eat']',  '$_SESSION['problem']','$_SESSION['student']','$_SESSION['tutor']','$_SESSION['other']')";

mysqli_query($cn,$sql) or die(mysqli_error($cn));

You need to proper write down variables. 您需要适当地写下变量。 It can't be : 不能是:

values('$_SESSION['name']',

It has to be: 它一定要是:

values('".$_SESSION['name']."',

Another good approach is to use PDO 另一个好的方法是使用PDO

$dbh = new PDO('mysql:host=localhost;dbname=data', $user, $pass);

$stmt = $dbh->prepare("INSERT INTO data (name, sex) VALUES (:name, :sex)");
$stmt->bindParam(':name', $_SESSION['name']);
$stmt->bindParam(':sex', $_SESSION['gender']);
$stmt->execute();

You are using single quote in worng sequnence and this generated wrong code .. 您正在按顺序使用单引号,这会生成错误的代码..

You could use string concat for avoid the problem 您可以使用字符串concat来避免该问题

but be carefulfor sqlijcection using php var inside sql, (you should use PDO and param binding. Anyway related to your question 但请注意在sql内使用php var进行sqlijcection,(您应使用PDO和param绑定。无论如何与您的问题有关

      $sql="insert into data(name,sex,time,suggest,eat,problem,student_suggest,tutor_suggest,other_suggest)   
      values(" . $_SESSION['name'] . ","
      . $_SESSION['gender'] . ","
      . $_SESSION['time'] . ","
      . $_SESSION['suggest'] . ","
      . $_SESSION['eat']', . ","
      . $_SESSION['problem'] . ","
      . $_SESSION['student'] . ","
      . $_SESSION['tutor'] . ","
      . $_SESSION['other'] . ")";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM