views:

196

answers:

1

I am writing a PHP script to add items to a shopping basket. My shopping basket table has fields for the userid, product id, session id, notes and a few others. Some of the fields can be blank. For example:

if someone isn't signed in, then I will store their session id in the table and, if they sign in, add their userid so I have a permanant way to match the items in the table to the user. If they are, I'll add the userid. When it comes to the INSERT query, can I do something like this:

$add_sql = "INSERT into sessionBasket (userid) VALUES ( '". isset($_SESSION["userid"]) ? $_SESSION["userid"] : "") ."'";

It would save me so much time on variable checking and branching because people could be signed in or not, items could have notes or not, that sort of thing.

+1  A: 

Yikes! SQL Injection! you could lose your whole database

You should be looking at prepared statements for your sql insertion.

You need to use the mysqli interface but it goes like this:

$statement = $db_connection->prepare("insert into ... VALUES(?)");
$statement->bind_param("id", $sid);
$statement->execute();

This will prevent sql injection attacks.

At an absolute minimum you should at least escape the string.

$sid = isset($_SESSION[userid]) ? mysql_real_escape_string($_SESSION[userid])) : '';
$add_sql = "insert into ... values($sid)";
Byron Whitlock
I know, I know - I was just giving you the bare bones that relate to my problem, heh. I do JavaScript pattern matching and replace any illegal characters as they're typed, then I run a PHP regex, then I do mysqli_real_escape_string and trim each input and if they pass that, I only insert once I'd also done htmlspecialchars(). So, trust me when I tell you that no databse injection is possible :)
but, actually, you answered my question anyway: i'll just do the assignment as a separate step.