This question already has an answer here:
- How can I prevent SQL injection in PHP? 28 answers
Ok so here is the question. I am trying to insert a variable into my query that is pre-defined. However it is not working. The query works if I just give it a value, but when I insert a variable into it, it fails. help?
$connection = new mysqli('localhost', 'user', 'pass', 'db');
$username = "test";
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $connection->query("INSERT INTO users (username, password, email, firstName, lastName, createDate) VALUES ('".$username."', 'test', 'test', 'test', 'test', 'test')")){
echo "success";
$result->close();
}
else {
echo "error";
}
$connection->close();
?>
If I replace $username with any value, it works.. Am I missing something here?
Since ther was some discussion above i thought id provide the following examples in pdo and mysqli for comparison:
MySQLi:
PDO:
In this case, looking at the context of your question it is better to assign the username variable with some data like
$username=$_POST['username'];
This might help...otherwise avoid the double quotes and simply put down
$username
The best answer to it is we must assign the variable we want into another variable. For example:
Hello this is for anyone who might still need accomplish what was asked in original question.
A reason why someone possibly might want to not use prepared statements--from: http://www.php.net/manual/en/mysqli.quickstart.statements.php
Cheers!
Its been a long time and probably you've already found out the answer but just in case, it turns out that its actually a simple problem where you put Double quotes and dots in the mysqli query statement at VALUES('".$username"'), but if you just leave it in single quotes and just write the variable name inside the quotes like, VALUES('$username'), it will work. I think it applies for new versions of php though not sure i.e. Change
to
Notice in the VALUE field my variable is not enclosed in double quotes or concatenated in periods i.e. VALUES ('$username'), since it will save the periods as a value.
this works for me but I've noticed a problem in running the query with the same values again, it brings an error but it can be avoided by adding a column in your database table for an auto increment id to make sure that a value is being changed every time you run the query
Hope this helps