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

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

Related

htmlspecialchars not working [duplicate]

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

Can't Save MySQL Query [duplicate]

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.

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

String performacne: PHP vs MySQL [duplicate]

This question already has answers here:
Doing calculations in MySQL vs PHP
(6 answers)
Closed 7 years ago.
Are there any performance concerns of note when using MySQL's CONCAT() function in a select query? Is it faster/slower/negligible to do a simple select, and format strings for a view using PHP after the result set from the database is returned? Or is a more complicated SQL query with multiple calls to CONCAT() that returns a string already formatted for the view a better approach?
ie is this:
select CONCAT(lastname, ', ', firstname) from people;
Faster/Slower/No difference from this:
<?php
$query = 'Select lastname, firstname from people';
...
$name = $data['lastname'] . ', ' . $data['firstname']; //OR
$name = sprintf("%s, %s", $data['lastname'], $data['firstname']);
?>
You're better off in almost all cases by doing filtering and data massaging with the SQL engine versus on the web server.
Unless you are planning to do hundreds of thousands such operations at once, it will not matter where you do the string concatenation from a performance point of view. The possible time savings will be so minuscule, they will probably not even be measurable.

Categories