PHP - Insert variables in double quote strings - php

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!

Related

Inputting an apostrophe in my search box throws up an error [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I have a perplexing issue that I can't seem to comprehend...
I have two SQL statements:
The first enters information from a form into the database.
The second takes data from the database entered above, sends an email, and then logs the details of the transaction
The problem is that it appears that a single quote is triggering a MySQL error on the second entry only! The first instance works without issue, but the second instance triggers the mysql_error().
Does the data from a form get handled differently from the data captured in a form?
Query 1 - This works without issue (and without escaping the single quote)
$result = mysql_query("INSERT INTO job_log
(order_id, supplier_id, category_id, service_id, qty_ordered, customer_id, user_id, salesperson_ref, booking_ref, booking_name, address, suburb, postcode, state_id, region_id, email, phone, phone2, mobile, delivery_date, stock_taken, special_instructions, cost_price, cost_price_gst, sell_price, sell_price_gst, ext_sell_price, retail_customer, created, modified, log_status_id)
VALUES
('$order_id', '$supplier_id', '$category_id', '{$value['id']}', '{$value['qty']}', '$customer_id', '$user_id', '$salesperson_ref', '$booking_ref', '$booking_name', '$address', '$suburb', '$postcode', '$state_id', '$region_id', '$email', '$phone', '$phone2', '$mobile', STR_TO_DATE('$delivery_date', '%d/%m/%Y'), '$stock_taken', '$special_instructions', '$cost_price', '$cost_price_gst', '$sell_price', '$sell_price_gst', '$ext_sell_price', '$retail_customer', '".date('Y-m-d H:i:s', time())."', '".date('Y-m-d H:i:s', time())."', '1')");
Query 2 - This fails when entering a name with a single quote (for example, O'Brien)
$query = mysql_query("INSERT INTO message_log
(order_id, timestamp, message_type, email_from, supplier_id, primary_contact, secondary_contact, subject, message_content, status)
VALUES
('$order_id', '".date('Y-m-d H:i:s', time())."', '$email', '$from', '$row->supplier_id', '$row->primary_email' ,'$row->secondary_email', '$subject', '$message_content', '1')");
You should be escaping each of these strings (in both snippets) with mysql_real_escape_string().
http://us3.php.net/mysql-real-escape-string
The reason your two queries are behaving differently is likely because you have magic_quotes_gpc turned on (which you should know is a bad idea). This means that strings gathered from $_GET, $_POST and $_COOKIES are escaped for you (i.e., "O'Brien" -> "O\'Brien").
Once you store the data, and subsequently retrieve it again, the string you get back from the database will not be automatically escaped for you. You'll get back "O'Brien". So, you will need to pass it through mysql_real_escape_string().
For anyone finding this solution in 2015 and moving forward...
The mysql_real_escape_string() function is deprecated as of PHP 5.5.0.
See: php.net
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_real_escape_string()
PDO::quote()
You should do something like this to help you debug
$sql = "insert into blah values ('$myVar')";
echo $sql;
You will probably find that the single quote is escaped with a backslash in the working query. This might have been done automatically by PHP via the magic_quotes_gpc setting, or maybe you did it yourself in some other part of the code (addslashes and stripslashes might be functions to look for).
See Magic Quotes
You have a couple of things fighting in your strings.
lack of correct MySQL quoting (mysql_real_escape_string())
potential automatic 'magic quote' -- check your gpc_magic_quotes setting
embedded string variables, which means you have to know how PHP correctly finds variables
It's also possible that the single-quoted value is not present in the parameters to the first query. Your example is a proper name, after all, and only the second query seems to be dealing with names.
You can do the following which escapes both PHP and MySQL.
<?
$text = '';
?>
This will reflect MySQL as
How does it work?
We know that both PHP and MySQL apostrophes can be escaped with backslash and then apostrophe.
\'
Because we are using PHP to insert into MySQL, we need PHP to still write the backslash to MySQL so it too can escape it.
So we use the PHP escape character of backslash-backslash together with backslash-apostrophe to achieve this.
\\\'
You should just pass the variable (or data) inside "mysql_real_escape_string(trim($val))"
where $val is the data which is troubling you.
I had the same problem and I solved it like this:
$text = str_replace("'", "\'", $YourContent);
There is probably a better way to do this, but it worked for me and it should work for you too.
mysql_real_escape_string() or str_replace() function will help you to solve your problem.
http://phptutorial.co.in/php-echo-print/

' <--- in mysql text don't get inserted in database

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.

Column count doesn't match value count at row 1 (columns and values are equal)

I'm getting the error: Column count doesn't match value count at row 1
I think, normally this error occurs if the count of the columns and the values aren't equal, but in my code they are...(3).
This is my php code:
$tempsongtitel = $_POST['songtitle'];
$tempinterpret = $_POST['interpret'];
$templink = $_POST['link'];
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link) values ('$tempsongtitel, $tempinterpret, $templink')") or die(mysql_error());
You missed some quotes. Should be:
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link) values ('$tempsongtitel', '$tempinterpret', '$templink')") or die(mysql_error());
Otherwise, you were trying to insert all three POST values into the first field.
Moreover, the mysql_ extension has been deprecated and is on the way out and is highly discouraged, especially if you are creating new software.
AND I'll presume you are first sanitizing your data? You're not really taking user input and placing it directly into the database, are you? Even if you don't do any data validation, you should escape your data in the query... easiest and most foolproof way to do that is by using parameterized queries.
The root cause is that your values are all in one set of quotes instead of quoted individually. I think this is a pretty common error, and in my experience it is an easy mistake to make, but not immediately obvious when scanning over your code. You can fix it like this (quick fix, still using deprecated mysql, but with post values escaped):
$tempsongtitel = mysql_escape_string($_POST['songtitle']);
$tempinterpret = mysql_escape_string($_POST['interpret']);
$templink = mysql_escape_string($_POST['link']);
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link)
values ('$tempsongtitel', '$tempinterpret', '$templink')") or die(mysql_error());
If you can, it would be much better to update your code to use PDO. You could use a prepared statement like this:
$stmt = $pdo->prepare("INSERT INTO tMusic (Songtitel, Interpret, Link) VALUES (?, ?, ?)");
$stmt->bindValue(1, $tempsongtitel);
$stmt->bindValue(2, $tempinterpret);
$stmt->bindValue(3, $templink);
$stmt->execute();
Among the many benefits of using this database extension rather than the old mysql functions it should not be possible to make an error like this in your code. In the prepared statement, there are no quotes around the parameter markers, so if you have VALUES ('?, ?, ?'), or even VALUES ('?', '?', '?') You would get bind errors when trying to bind the values, and the problem would become apparent pretty quickly.
I've found that, even though it's not 100% necessary and it's more time consuming, properly quoting and backticking EVERYTHING helps prevent this from happening.
$myQuery = "INSERT INTO `tMusic` (
`Songtitel`,
`Interpret`,
`Link`
) VALUES (
'$tempsongtitel',
'$tempinterpret',
'$templink'
);";
$runQuery = mysqi_query($DBi, $myQuery) or die(mysqli_error($DBi));
The formatting you use is up to you but this helps me make sure I have a one to one relationship and that I've quoted everything.
Of course that's using mysqli_* in place of the deprecated mysql_* functions AND that's assuming you've set $tempsongtitel, $tempinterpret and $templink properly.

Issue storing data to SQL DB

I am trying to store some form data to a SQL database using the following query:
$sql = "INSERT INTO attendees (first_name, surname, partner, phone) VALUES ($first_name, $surname, $partner, $phone)";
It works perfectly if I hard code the values to test it, but when using these variables, it breaks and gives me Error 1054
$first_name = $_POST['first_name'];
$surname = $_POST['surname'];
$partner = $_POST['partner'];
$phone = $_POST['phone'];
Could anyone help?
$sql = "INSERT INTO attendees (first_name, surname, partner, phone) VALUES ($first_name, $surname, $partner, $phone)";
should be
$sql = "INSERT INTO attendees (first_name, surname, partner, phone) VALUES ('$first_name', '$surname', '$partner', '$phone')";
you are missing quotes around field content.
Warning: your code is vulnerable to SQL injection attacks
try to use PHP Prepared statement and wiki page http://en.wikipedia.org/wiki/Prepared_statement . Or at-least use mysqli_real_escape_string
Err 1054 means that you are using a column name that doesn't exist.
In this case, as there doesn't seem to be anything wrong with your insert statement (assuming that all the variables have data in them) it means you have likely typo'ed a column name.
On second thoughts, you probably need single quotes around the strings, but the first part of my answer still stands.
First of all, stop using mysql_ functions and look for PDO and prepared statements: if you'll do as suggested, this problem will sort by itself.
Anyway, the problem is that the query will replace the values with the strings contained in your $_POST array... but without string delimiters.
This means that mysql will look at them as column names, and spaces will break them!
solution:
$sql = "INSERT INTO attendees (first_name, surname, partner, phone) VALUES ('$first_name', '$surname', '$partner', '$phone')";
NOTICE that this will leave you wide open to SQL injection attacks!
with PDO it'll look something similar to this:
$stmt = $db->prepare("INSERT INTO attendees (first_name, surname, partner, phone) VALUES (:fname, :sname, :partn, :phone)");
$stmt->execute(array(':fname' => $first_name, ':sname' => $surname_name, [the others]))
which will is much more secure and plainly better all around.
Please escape and verify your inputs, otherwise you'll be vulnerable to SQL injections.
Here's a list of good solutions on how to do that: http://bobby-tables.com/php.html
Basically try to use prepared statements if possible, otherwise use mysql_real_escape_string()

Inserting $variable or $_POST value into mysql table [duplicate]

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

Categories