user652792
user652792

Reputation:

SESSION var in mysql query

Is it possible to use $_SESSION[var] in INSERT and SELECT statements of mysql as in below

$query = "INSERT INTO table1 (id, var1, var2)
            VALUES (NULL, '$_SESSION[var1]', '$_SESSION[var2]')";
mysql_query($query);
die(mysql_error()); 

NOTE: I have session_start(); at the start of all my pages.

Upvotes: 1

Views: 228

Answers (2)

Mike Purcell
Mike Purcell

Reputation: 19999

Good idea to sanitize your vars before executing queries against them:

$var1 = mysql_real_escape_string($_SESSION['var1']);
$var2 = mysql_real_escape_string($_SESSION['var2']);

$query = 
    "INSERT INTO table1 (id, var1, var2) " .
    "VALUES (NULL, '" . $var1 . "', '" . $var2 . "')";

mysql_query($query) or die(mysql_error()); 

Note that your last time line of code die(mysql_error()) will cause the script to stop execution regardless of whether or not an error occured.

Also, you may want to look into PDO for your database interaction.

Upvotes: 2

gview
gview

Reputation: 15421

Yes. In my opinion the best way to specify an array variable in an interpolated string is to put curly brackets around it so that you can utilize single quotes around the array key:

$query = "INSERT INTO table1 (id, var1, var2)
              VALUES (NULL, '{$_SESSION['var1']}', {$_SESSION['var2']}')";

Upvotes: 1

Related Questions