This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 8 years ago.
I'm trying to change the content of a string (from user's input), I'd like to remove any character that will let my query fail. For example, if I insert a second name with a " ' " in it, the query will fail.
Since I have to then output these rows from the DB, I'm wondering if there's any way to insert the string in the database while replacing the special character with its HTML value so that when I'm outputting it, the browser will do the rest.
I'm leaving you an example:
$string = $_POST['user_input']; // Let it be Lol'd
$sql = "INSERT INTO table(field) VALUES('$string')";
Now without anything done to the string I'd get the query as:
INSERT INTO table(field) VALUES('Lol'd')
What I'm looking for is something to turn the ' into ' so that in the DB it's saved Lol'd but when I echo it it'll just print Lol'd
There are lot of solutions. You can use a function like htmlentities():
$string = htmlentities($_POST['user_input']); // Let it be Lol'd
$sql = "INSERT INTO table(field) VALUES('$string')";
To read the string from your MySQL table, use html_entity_decode()
try this
$string = str_replace("'","\'",$_POST['user_input']);
$sql = "INSERT INTO table(field) VALUES('$string')";
Related
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 3 years ago.
I'm currently testing a html form which sends the data through php to the sql database. The problem I'm facing is special characters break the form and don't update the database. I haven't tested all the special characters but mainly ` and ' are the culprits. I've tried mysql_escape_string, preg_replace and add_slashes with no success. What am I missing?
$description = preg_replace('/[^A-Za-z0-9\ %&$=+*?()!.-]/', ' ', $_POST['description']);
$description = preg_replace("/[\n\r]/"," ",$description);
// Items Insert
foreach ($item as $index=>$value) {
$sqlItems .= "
INSERT INTO quote_items (quote_id, item, description, amount, gst)
VALUES ('$last_id', '$item[$index]', '$description[$index]', '$amount[$index]', '$gst[$index]');
";
}
Thanks in advance!
you can try this (a little dirty) but it should allow those 2 characters to be saved
$sqlItems .= '
INSERT INTO `quote_items` (quote_id, item, description, amount, gst)
VALUES ("'.$last_id.'", "'.$item[$index].'", "'.$description[$index].'", "'.$amount[$index].'", "'.$gst[$index].'");
';
EDIT: sorry had the quotes reversed
Can you post you DB call?
Those two characters in particular look like they would conflict in a DB call.
The ` is usually wrapped a table or column name
and the ' is usually wrapped around values.
Both of these would cause a problem but without code its hard to say
This question already has answers here:
Escaping single quote in PHP when inserting into MySQL [duplicate]
(8 answers)
Closed 7 years ago.
I'm having an issue with my MySQL query/php, I try to update a row in my database that will work usually, but when the string has a ' in it, for example
I don't like green eggs and ham.
The ' in it will cancel the whole response out and not update the row, so if I put something like this without the ' for example:
I dont like green eggs and ham.
The string will save to the row. Below is the MySQL query used and where I get the string from.
$NewMessage = $_POST['message123'];
mysql_query("UPDATE Account SET `function` = 'Message', `note` = '$NewMessage' WHERE `id` = '$ID' AND `Online` = '1'");
If you need anymore source or anything, please let me know, let me know what you think, thanks!
Use *_real_escape_string
$NewMessage = mysql_real_escape_string($_POST["message123"]);
But of course, mysql_* API is already deprecated and I would recommend to you to use prepared statement instead.
Hey friend you are need to change single ' with '' commas 2 times. then it is insert your value correct in table other generate error.
Real escape string use where we are need value like this doest. if we user value in database like it does't then right one is use '' 2 time single commas no doule commas
Use simply addslashes() To read more about it click here
E.g in you code simply use addslashes() something like this
$NewMessage = addslashes($_POST['message123']);
I hope it will work for you.
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
This string works:
$sql = 'SELECT * FROM Bar_Info WHERE b_id=' .
$db->real_escape_string($_GET['b_id']);
However, this one does not:
$sql = 'SELECT * FROM Bar_Info WHERE BarLink=' .
$db->real_escape_string($_GET["BarLink"]);
b_id are variables and BarLink are names of bars some including hyphens. An example being: granite-city
Is there any reason the second example of code would not work?
You need to quote your SQL parameters:
$sql = 'SELECT * FROM Bar_Info WHERE BarLink=\'' . $db->real_escape_string($_GET["BarLink"]).'\'';
The first query likely works because you just use numbers, but the second one uses a string.
PS: Quoting is necessary in both cases as otherwise you are vulnerable to SQL injection.
strings in SQL queries have to be surrounded by quotation marks, while integers don't. So if "BarLink" contains strings, you'll have to add those:
$sql = 'SELECT * FROM Bar_Info WHERE BarLink="' . $db->real_escape_string($_GET["BarLink"]).'"';
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
How to escape single quotes in MySQL
(19 answers)
Closed 8 years ago.
I want to add single quotes word like "Dwi'q" and "Jum'at" in PHP MYSQL,
but I cant add that word, I try search anything but I dont found it.
my query is:
$query=mysql_query("INSERT INTO `pln`(`ppno`,`persno`,`pernum`,`psgrup`,`lv`,`pos`,`nppsimkp`,`persub`,`busrea`,`pdthr`,`gk`,`marstakey`,`bkey`,`bakun`,`numtd`,`email`,`bdate`) VALUES ('".$ppno."','".$persno."','".$pernum."','".$psgrup."','".$lv."','".$pos."','".$nppsimkp."','".$persub."','".$busrea."','".$pdthr."','".$gk."','".$marstakey."','".$bkey."','".$bakun."','".$numtd."','".$email."','".$bdate."')") or die(mysql_error());
Thanks for help.
In simple.. you can escape it with backslash..
$search_keyword="jum\'at";
but i recommend you to first sanitize the value before passing it into query.. using php function called
mysql_real_escape_string($search_keyword)
for ex;
$search_keyword=mysql_real_escape_string("jum'at");
first do this:
$a = mysql_real_escape_string("Dwi'q");
$b = mysql_real_escape_string("Jum'at");
and then run your query providing these variables in your query.
In order to insert values with ' you need to use mysqli_real_escape_string or mysql_real_escape_string. Also it better to use always when you are inserting values into DB in order to avoid SQL Injection.
And one more thing Please stop using mysql_* functions and start using mysqli_* function or PDO
Example
Using mysql_real_escape_string
$a = "some one's text";
$a = mysql_real_escape_string($a);
Using mysqli_real_escape_string
$con = mysqli_connect("localhost","dbusername","dbpassword","dbname");
$a = "some one's text";
$a = mysqli_real_escape_string($con,$a);
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 9 years ago.
I have a simple comments page a user enter a text into a textarea and the hit comment button to send the comment to a php page :
<?php
$reply = strip_tags($_POST['reply']);
$comment_id = strip_tags($_POST['id']);
$id = strip_tags($_POST['user_id']);
$date = strip_tags($_POST['date']);
$time = strip_tags($_POST['time']);
$server_root = "./";
if(file_exists("{$server_root}include-sql/mysql.class.php"))
{
include_once("{$server_root}include-sql/mysql.class.php");
}
include_once("{$server_root}config.php");
$db1;
$db1 = new db_mysql($conf['db_hostname'],
$conf['db_username'],
$conf['db_password'],
$conf['db_name']);
$db1->query("SET NAMES utf8");
$current_server_date = date('Y-m-d H:i:s');// Your local server time
date_default_timezone_set('Asia/Istanbul');
$current_pc_date = date('Y-m-d H:i:s');
$sql = $db1->query(
'INSERT INTO replies1 (reply, comment_id, date, time, timestamp, user_id)
VALUES ("$reply", $comment_id, "$date", "$time", "$current_pc_date", $id)');
?>
the problem is : when a user enter any comment with apostrophe it does not store it in the database ? why does that happened? Is my code has something wrong? I added everything the double quotes and stripe_tags.? did i miss something?
You should escape all input which is coming directly from the user with mysqli_real_escape_string()!
Otherwise its not only not working properly but its also highly unsafe to hacker-attacks. (mysql-injection)
The strip_tags() seems unnecessary.
Instead, you should
either escape the DB input appropriately
or use prepared statements at the first place.
As you hide your MySQL implementation in an own class, I don't see how you implement these. How to escape or to prepare depends on the MySQL interface you use.
Keep in mind that mysql_*() is deprecated. You should either use mysqli or PDO.