htmlspecialchars not working [duplicate] - php

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
My code is:
$description = $_POST['description'];
$description = htmlspecialchars($description);
I use it to insert some description into a table:
$insertBillIndexQuery = "INSERT INTO $billIndexTableName (type, exp_category, shopping_date, shop, description, total_amount, paid, due, mode_of_payment) VALUES ('Expense', '$exp_category', '$billDate', '$shop', '$description', '$total_amount', '$paid', '$due', '$modeOfPayment')";
This works fine usually. However, when I type a special character such as a single quote, the system breaks, and I get an Error Querying Database error. I'm sure that the single quotes are causing the problem. Am I using htmlspecialchars wrong?

You need to do the conversion using ENT_HTML401 for converting ' into '. According to the manual:
' (single quote)
' (for ENT_HTML401) or ' (for ENT_XML1, ENT_XHTML or ENT_HTML5), but only when ENT_QUOTES is set

Related

Passing variable from shell exec to mysql_query [duplicate]

This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
Closed 5 years ago.
I'm trying to read temperature from sensor DHT22 connected to raspberry pi and write it to mysql DB via PHP script.
I'm getting the temperature like this:
$temp = shell_exec('./temp.py');
Script returns number like 45 or 45.7 etc... The same as humidity.. When I echo it in the same script, it works.
And the thing, which I cannot pass through is here:
$sql='INSERT INTO values (id, date, time, timestamp, temp, hum) VALUES ("", NOW(), NOW(), NOW(), "$temp", "$hum")';
$result = MySQL_Query($sql);
But in DB is always written $temp and $hum, not the actual values. I think that I've already tried all possible combinations of quotation marks, etc...
What can be possibly wrong? Thanks in advance for the answers.
$sql="INSERT INTO values (id, date, time, timestamp, temp, hum) VALUES (\"\", NOW(), NOW(), NOW(), \"$temp\", \"$hum\")";
$result = MySQL_Query($sql);
Notice the double quotes.
There is a difference between double and single quotes:
Double quotes are parsed by the php engine. You can put variables inside them, and can be used to display escaped special characters.
Single quotes, on the other hands, are displayed as they are. They are not parsed by PHP and do not require escaping, except for the ' to tell the interpreter whether the quote is the end of the string or part of it.
You were using single quotes, that's why your string isn't parsed into variables.
Further information could be found in the PHP Manual

Preparing HTML Form Input for SQL Database using PHP [duplicate]

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

PHP/MySQL string [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
Basically I'm trying to insert a value in a table from a textarea.
$sql_insert = "INSERT INTO message_admin (message, lastedit_ip, lastedit_date) VALUES ('".$_POST["message"]."', '".$_SERVER['REMOTE_ADDR']."', '".date("d/m/Y")."');";
Thing is if I type either the symbol ' or " in my text area, I will get PHP debug because PHP will take it as if I closed my string (is that the right expression, even?)
Hope you did understand me
Use addslashes()
$sql_insert = "INSERT INTO message_admin (message, lastedit_ip, lastedit_date) VALUES ('".addslashes($_POST["message"])."', '".addslashes($_SERVER['REMOTE_ADDR'])."', '".date("d/m/Y")."');";

PHP and SQL parsing single quotes [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I've done some searching here and have not found what I'm looking for.
I've got a form that gets filled out, upon submitting it adds it to an SQL database (using PHP). However, if someone puts an apostrophe or single quote, it will blow up...I need to be able to either parse each text field to check for single quotes to escape them out or find some other way for this to work. Here is my SQL statement...if it helps.
$query = "INSERT INTO workshopinfo (Year, Presentername, email, bio, arrival, title, description, costyn, matcost, schedlimit, additionalinfo, typeofws, verified)" .
"VALUES ('$year', '$presentername', '$email', '$bio', '$arrival', '$title', '$description', '$costyn', '$matcost', '$schedlimit', '$additionalinfo', '$typeofws', '$verified')";
So of course a single quote will blow it up, as will a double quote...it fails every time. There is likely an easy solution to this.
I may have just found it after posting. The php functon addslashes() works in this case.
You can use PDO with prepared statements to handle quotes in SQL requests :
$req = $bdd->prepare("INSERT INTO yourTable (a, b, c) VALUES (:a, :myb, :c)");
$req->bindParam("a", $name, PDO::PARAM_STR); // string
$req->bindParam("myb", $title, PDO::PARAM_STR); // string
$req->bindParam("c", $identifier, PDO::PARAM_INT); // integer
$req->execute();
With this, you avoid all SQL injections.
Documentation : http://php.net/manual/en/book.pdo.php

Protect SQL query from special characters [duplicate]

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

Categories