PaoPaoMC
PaoPaoMC

Reputation: 87

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.)

$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));

Upvotes: 1

Views: 80

Answers (2)

Tomasz Adamczyk
Tomasz Adamczyk

Reputation: 261

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

$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();

Upvotes: 1

ScaisEdge
ScaisEdge

Reputation: 133360

You are using single quote in worng sequnence and this generated wrong code ..

You could use string concat for avoid the problem

but be carefulfor sqlijcection using php var inside sql, (you should use PDO and param binding. Anyway related to your question

      $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'] . ")";

Upvotes: 1

Related Questions