This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
My question concerns why one piece of code works and two that does not, and how i can get the code that does not work to work.
The code that works:
mysql_select_db("webuser1", $con);
mysql_query("INSERT INTO users (column 1, column2) VALUES ('value1', 'value2')");
mysql_close($con);
Code no1 that does not ($var1 contains 'value1' etc.):
mysql_select_db("webuser1", $con);
mysql_query("INSERT INTO users (column 1, column2) VALUES ($var1, $var2)");
mysql_close($con);
And code no2 that does not work ($_POST['value1'] contains 'value1' etc.):
mysql_select_db("webuser1", $con);
mysql_query("INSERT INTO users (column 1, column2) VALUES ($_POST['value1'], $_POST['value2'])");
mysql_close($con);
Am i not supposed to be able to insert $var or $_POST in mysql? I hope you do not find this Q stupid but i have been looking around for solutions but i have not understood them.
Thank you
In SQL, string values need to be quoted:
VALUES ('value1', 'value2')"
When you use variables:
VALUES ($var1, $var2)");
They are not quoted … unless the quotes are in the values themselves.
So if $var1 = 'value1'; $var2 = 'value2' then (after the variables are interpolated in your string) your SQL looks like this:
VALUES (value1, value2)"
You could resolve your immediate problem by adding quotes:
VALUES ('$var1', '$var2')");
but this doesn't fix your major security vulnerability and lets your data break the query in different ways.
You should avoid creating SQL statements by assembling strings from variables. This way leads to SQL Injection security holes. Use an interface that supports bound arguments. They will handle quoting and escaping for you.
mysql needs single quotes to enclose a string... so you would need something like this:
mysql_query("INSERT INTO users (column 1, column2) VALUES ('".$_POST['value1']."', '".$_POST['value2']."')");
for everything that is not a string you won't need the single quotes (')
as mentioned before you should not forget to escape strings that you want to put into the database.
for example use prepared statements. by binding the parameters it is ensured that your passed value is of the type you specified within the prepared statement.
Seems like you're not escaping and quoting your arguments to mysql properly.
To insert variables in MySQL you need to escape them at least: $var = mysql_real_escape_string($_POST['variable']) and then ".. VALUES ('".$var."')"
You should also probably consider using libraries for connecting to MySQL like DOCTRINE: http://www.doctrine-project.org/ that handles this for you.
Use this solution, its 100% works
mysql_query("INSERT INTO users (column 1, column2) VALUES ('{$_POST[value1]}', '{$_POST[value2]}')");
when you use {}, you dont need write value in ' '
mysql_select_db("webuser1", $con);
mysql_query("INSERT INTO users (column 1, column2) VALUES ('$var1', '$var2')");
mysql_close($con);
When not using Apostrophes around values, it is supposed to be non string value.
Your variables are not recognized as variables. They are a part of your string.
Try:
mysql_query("INSERT INTO users (column 1, column2) VALUES ('".$var1."', '".$var2."')");
Same for your second problem.
Because the POST variables have ' in them, you have to concatenate instead.
I.E.
mysql_query("INSERT INTO users (column 1, column2) VALUES (".$_POST['value1'].", ".$_POST['value2'].")");
Or
mysql_query("INSERT INTO users (column 1, column2) VALUES ({$_POST['value1']}, {$_POST['value2']})");
It's also a good idea to put quotes around the variables, in case its empty (or a string rather than an integer)
$var1=$_POST['variable_name1'];
$var2=$_POST['variable_name2'];
$q="INSERT INTO `users` (`column 1`, `column2`) VALUES ($var1, $var2)";
$result=mysql_query($q);
Related
I'm new here. I started PHP recently and I am wondering how I could insert variables, and put them into single quotes, into a double quotes string.
Here's what I tried :
$query = "INSERT INTO Table (Name, Activity) VALUES ('$name', '$activity');";
But when I check $query, it contains that : INSERT INTO Table (Name, Activity) VALUES (,);. I don't understand why it does that because when, instead of writing the above code, I write this one : $query = "INSERT INTO Table (Name, Activity) VALUES ($name, $activity);"; (without the single quotes), the string contains this : INSERT INTO Table (Name, Activity) VALUES (Robert, Book-seller);. Does anybody have a clue ?
how I could insert variables, and put them into single quotes, into a double quotes string.
Don't do that. It leaves you vulnerable to SQL injection attacks. Instead use prepared statements with bound parameters as described in this post.
I tried your statement:
$query = "INSERT INTO Table (Name, Activity) VALUES ('$name', '$activity');";
And It worked perfectly with me. I guess you need to check the values you passing in $name and $activity. (for Robert, Book-Seller its working nicely).
Still You may try this. It might help:
$query = "INSERT INTO Table (Name, Activity) VALUES (\"$name\", \"$activity\");";
And a note for caution: as Alex Howansky says, don't do that. it leaves you vulnerable to SQL injection attacks.
Hope it helps. All the best!
Hello i'm a beginner so please at least try to give me a hint,a example.
English isn't my main language so please endure it.
If somebody type " Hello my name is J'hon ' the text don't insert in database, but if he type 'Hello my name is jhon' it does. I think it is something about '
Ok so i'm having the problem that if someone types
'Hello my name is J[color=#FF0000]'[/color]hon J'onz. ' is not inserted in the database..
This is the script:
mysqli_query($DB_H, "INSERT INTO tickets (name, continutscurt, continut,type,status) VALUES ('".$_SESSION['username']."', '".$_POST['titlu']."', '".$_POST['continut']."', $numar, 0)");
You should really use prepared statements when dealing with any kind of user-input. If you for any weird reason isn't using prepared statements, take a look at the function mysqli::real_escape_string. This will deal with special characters, such as ', which may break the SQL.
With using prepared statements, your code would look like
if ($stmt = $DB_H->prepare("INSERT INTO tickets (`name`, continutscurt, continut, `type`, `status`) VALUES (?, ?, ?, ?, ?)")) {
$stmt->bind_param("ssssi", $_SESSION['username'], $_POST['titlu'], $_POST['continut'], $numar, 0);
$stmt->execute();
$stmt->close();
} else {
echo mysqli_error($DB_H);
}
If you however want to use mysqli::real_escape_string, you'll need to bind the SESSIONs and POSTs to a variable where in you insert instead, like this (you can also do it directly in the query, but this makes for cleaner code).
$username = mysqli_real_escape_string ($DB_H, $_SESSION['username']);
$titlu = mysqli_real_escape_string ($DB_H, $_POST['titlu']);
$continut = mysqli_real_escape_string ($DB_H, $_POST['continut']);
$numar = mysqli_real_escape_string ($DB_H, $numar);
if (!mysqli_query($DB_H, "INSERT INTO tickets (`name`, continutscurt, continut, `type`, `status`) VALUES ('$username', '$titlu', '$continut', '$numar', 0")) {
echo mysqli_error($DB_H);
}
I also put backticks ` around name, status and type, as these are keywords in SQL. This isn't strictly necessary, but it's good practice with words that are listed as either reserved words or keywords, more info on this list of keywords.
You shouldn't take for granted that your queries are successful, so I added an if-block around them. Errors shouldn't be displayed unless in production/development.
References:
http://php.net/manual/en/mysqli.real-escape-string.php
http://php.net/manual/en/mysqli.prepare.php
How can I prevent SQL injection in PHP?
https://dev.mysql.com/doc/refman/5.7/en/keywords.html
The issue is SQL Injection.
You have potentially unsafe values being included within the SQL text.
To see this, break up the code a little bit.
$sql = "INSERT INTO tickets ...'" . $val . "' ... ";
echo $sql;
The echo is there just as a way to see what's going on, for you to examine the contents of the string containing the SQL text. And then take that string over to another client, and test it. And you will see what the the problem is.
... VALUES ( ..., 'J'onz. ', ...
isn't valid. That single quote is ending the string, so the string is just 'J', and the next part, MySQL is going to try to interpret as part of the SQL, not the string value. (This is a nefarious vulnerability. Cleverly constructed strings and wreak havoc on your application and your database.)
One approach to fixing that is to sanitize the values, so they can be safely included.
... VALUES ( ..., 'J\'onz. ', ...
^^
... VALUES ( ..., 'J''onz. ', ...
^^
As a simple demonstration try these queries:
SELECT 'J\'onz. '
SELECT 'J''onz. '
SELECT 'J'onz. '
(The first two will return the string you expect, and the third will cause an error.)
The take away is that potentially unsafe values that are going to included in the text of a SQL statement need to be properly escaped. Fortunately, the MySQL client library includes mysqli_real_escape_string function. Variables that may potentially contain a single quote character can be run through that function, and the return from the function can be included in the SQL text.
$sql = "INSERT INTO tickets ...'"
. mysqli_real_escape_string($DB_H,$val)
. "' ... ";
Again, echo out the $sql and you can see that a single quote has been escaped, either by preceding it with a backslash character, or replacing it with two sinqle quotes.
There's a much better pattern than "escaping" strings. And that's to use prepared statements with bind placeholders.
The SQL text can be a static string:
$sql = 'INSERT INTO mytable (mycol) VALUES ( ? )'
And then you msyqli_prepare the statement.
And then supply values for the placeholders with a call to mysqli_bind_param.
And then call mysqli_execute.
With this pattern, we don't need to mess with running the "escape string" function to sanitize the inputs.
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
Many posts similar to mine,none of them work.
Have an array $data['date'], $data['name'], $data['value'].
Trying to insert into MySQL table MyValues (Date, Name, Value)
Have tried 7-8 different methods, none working.
Would like something like
for ($a=0;$a<10;$a++) {
mysql_query("INSERT INTO MyValues('Date','Index_Name','Index')
VALUES ($data['date'][$a] ,$data['name'][$a], $data['value'][$a])"
}
Have also tried foreach, building a single string to give to MySQL, etc.
Get this error
Warning: mysql_error() expects parameter 1 to be resource, boolean given on line 45
columnName shouldn't be wrap with single quotes as they are identifiers not string literals.
INSERT INTO `Values` (Date,Index_Name,Index) VALUES (....)
one more thing, the only identifier here that needs to be wrap with backtick is the tableName VALUES because it is a Reserved Keyword.
MySQL Reserved Keywords List
When to use single quotes, double quotes, and backticks in MySQL
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
Since Values is a reserved word, you can't use it as is for a table name. You must use backticks to enclose it. Similarly, it is not valid to use single quotes to name columns, you need backticks there too.
Try this:
$out = Array();
$esc = "mysql_real_escape_string";
foreach($data['date'] as $k=>$v) {
$out[] = "('".$esc($data['date'][$k])."', '".$esc($data['name'][$k])."', "
."'".$esc($data['value'][$k])."')";
}
mysql_query("INSERT INTO `Values` (`Date`, `Index_Name`, `Index`) values ".implode(",",$out));
try this, use $a++ not $ee++
for ($a=0;$a<10;$a++) {
mysql_query("INSERT INTO `Values` (`Date`,`Index_Name`,`Index`)
VALUES ('".$data['date'][$a]."' ,'".$data['name'][$a]."', '".$data['value'][$a]."' ")
}
First, I believe you want your query values quoted, so the result is 'value' and not just value. Example:
mysql_query("INSERT INTO Values(Date,Index_Name,Index) VALUES ('$data['date'][$a]' ,'$data['name'][$a]', '$data['value'][$a]');
If you are doing multiple queries, do something like:
$q = "INSERT INTO Values(Date,Index_Name,Index) VALUES ";
for {
// Add to the string here for each insert item
}
mysql_query($q);
Additionally, please start phasing out PHP's mysql_* library in favor of mysqli or PDO.
First of all, just use PDO/mysqli with prepared statements so you wont ever have any issues like this.
This will solve it though (column names with back-ticks instead of single quotes, and escaped data):
for ($a=0;$a<10;$a++) {
mysql_query("INSERT INTO `Values` (`Date`,`Index_Name`,`Index`)
VALUES ('".mysql_real_escape_string($data['date'][$a])."' ,
'".mysql_real_escape_string($data['name'][$a])."',
'".mysql_real_escape_string($data['value'])[$a]."'");
}
And try to avoid reserved names for your columns like indexand values.
This works:
for ($a=0;$a<10;$a++) {
mysql_query("INSERT INTO Values('Date','Index_Name','Index')
VALUES ('".$data['date'][$a]."','".$data['name'][$a]."','".$data['value'][$a]."')"
}
I have a page that gets a couple of variables from the url through a php GET method. The address would be
sampledomain.com/sample.php?id=11&in=16&lang=1
Then I use $in = $_GET['in']; and $id =$_GET['id']; to get the values.
Now, I have a MySQL statement like this:
mysql_query("INSERT INTO tagovi_rel (column1, column2) values ('$in', '$some_variable') ") or die(mysql_error());
It just doesn't work even though the $in value is correct (I checked that). What's really strange is, when I put $id (or any numeric value) instead of $in, it inserts it! Both $id and $in are numeric, out of desperation I tried using $in_num = intval($in) and then inserting $in_num but no luck. No error is thrown.
The $some_variable part is irrelevant to this problem, the statement behaves the same with or without it.
This is a real conundrum for me, why would the statement work for one variable but not the other?
Yeah, I have ['in'] on the page, I mistyped it here.
that's the problem.
the only your problem.
it is obvious that nothing mysterious in a variable name, expecially when this variable gets interpolated and do not interfere with SQL at all.
thus, the only possible reason left - the typo again.
And as you fail to post the correct code here, it is become impossible to even find that typo for you. You have to do it yourself.
The only thing you can do to help yourself is to print out each interpolated variables and compare them.
Instead of silly one-liner a sane programmer would separate his code into several lines for the better readability/maintainability:
$sql = "INSERT INTO tagovi_rel (column1, column2) values ('$in', '$some_variable')";
mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
thus you can comment out the actual query execution and print the query out instead, for the debugging purposes.
And thus you'll be able to see yourself, if there is any difference in a variable names.
$sql1 = "INSERT INTO tagovi_rel (column1, column2) values ('$in', '$some_variable')";
$sql2 = "INSERT INTO tagovi_rel (column1, column2) values ('$id', '$some_variable')";
var_dump($sql1==$sql2,$sql1,$sql2);
first of all $in = $_GET[in']; has to be $in = $_GET['in']; you forgot a quote, and also in php when you do '$in' the result will be (STRING) $in but when you put "$in" then you will get the value of the variable.
Secondly try
mysql_query("INSERT INTO tagovi_rel (column1, column2) values (".$in.", ".$some_variable.") ") or die(mysql_error());
I'm having a problem with sprintf(), using it to store a mysql query into a var to use it later.
just to inform, I'm using adodb library for database related operations.
being $value=25.5 and $id=5 for example, i have something like
$value = number_format($baseValue, 2, ".", "");
$query = sprintf("Insert into table_name (id, value) values (%d, $.02f)", $id, $value);
$db->Execute($query);
there's a condition before this that decides if there is another $query being made before this one. if that first query doesn't run this one runs ok being the query
Insert into table_name (id, value) values (5, 25.50)
but if the first query runs then i get an error on this one because the query turns out as
Insert into table_name (id, value) values (5, 25,50)
i tried to print $value just right before the sprintf() and it still has the right format, why on earth is this happening and how do i solve it?
Edit: $value isn't even used or changed until this moment
You are basically doing a equivalent number to string conversion twice, first with number_format() and then with printf() and the %f modifier. Replacing $.02f with %s should be enough.
The reason why printf() is not generating a valid English format number is because it's using the regional settings (see setlocale() for further info). Given that SQL expects a fixed format, it's more reliable to use number_format().
Update: The ADOdb library seems to support prepared statemens. They are normally a simpler and more robust mechanism than injecting values into your SQL code:
$rs = $DB->Execute("select * from table where key=?",array($key));
while (!$rs->EOF) {
print_r($rs->fields);
$rs->MoveNext();
}
Stick some single quotes around your values. The 25,50 will be interpreted as two fields, for a start (and I'm pretty sure mySQL won't like 25.50 without quotes either.
$query = sprintf("Insert into table_name (id, value) values ('%d', '$.02f')", $id, $value);
Will result in:
Insert into table_name (id, value) values ('5', '25.50')