This question already has an answer here:
PHP: 7 PDO fetch(All) tries to convert types to associated type
(1 answer)
Closed 6 years ago.
I'm converting some existing code from mysqli to PDO to use prepared statements/bind variables to help prevent SQL injection on queries, but I've run into a problem with fetching the results and using json as input to JavaScript.
After executing the query, I use this code to build the results array:
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()) {
$json[] = $row;
}
echo json_encode($json);
The problem is that it seems any of my database columns that are not strings are returned without double quotes around them, unlike when I used mysqli, which wrapped all values in double quotes. How do I fix this? Is there a way to get the results with all the values as strings?
Here's the comparison of results - note that 'ID' is my auto number column and in the PDO results it is NOT wrapped in double quotes:
PDO
[{"ID":55,"Entry_Form_Number":1005,"Barcode_Text":"2017-1005","Entrant_Name":"aa
bb","Model_Name":"cc","Category_Name":"Dioramas","Paid":1,"DatePaid":"09-Feb-17
11:28AM","DateCreated":"03-Feb-17
01:11PM","DateLastUpdated":"09-Feb-17
11:28AM","LastUpdatedBy":"wf_boxoffice"},{"ID":56,"Entry_Form_Number":1006,"Barcode_Text":"2017-1006","Entrant_Name":"aa
bb","Model_Name":"cc","Category_Name":"Dioramas","Paid":1,"DatePaid":"09-Feb-17
11:28AM","DateCreated":"03-Feb-17
01:16PM","DateLastUpdated":"09-Feb-17
11:28AM","LastUpdatedBy":"wf_boxoffice"},{"ID":59,"Entry_Form_Number":1009,"Barcode_Text":"2017-1009","Entrant_Name":"aa
bb","Model_Name":"cc","Category_Name":"Original
Sculpt/Scratchbuilt","Paid":1,"DatePaid":"09-Feb-17
11:28AM","DateCreated":"04-Feb-17
10:32AM","DateLastUpdated":"09-Feb-17
11:28AM","LastUpdatedBy":"wf_boxoffice"},{"ID":62,"Entry_Form_Number":1010,"Barcode_Text":"2017-1010","Entrant_Name":"aa
bb","Model_Name":"cc","Category_Name":"Dioramas","Paid":1,"DatePaid":"09-Feb-17
11:28AM","DateCreated":"08-Feb-17
08:31PM","DateLastUpdated":"09-Feb-17
11:28AM","LastUpdatedBy":"wf_boxoffice"},{"ID":63,"Entry_Form_Number":1011,"Barcode_Text":"2017-1011","Entrant_Name":"aa
bb","Model_Name":"cc","Category_Name":"Dinosaurs","Paid":0,"DatePaid":null,"DateCreated":"09-Feb-17
08:12PM","DateLastUpdated":"09-Feb-17
08:12PM","LastUpdatedBy":"wf_anon"},{"ID":64,"Entry_Form_Number":1012,"Barcode_Text":"2017-1012","Entrant_Name":"aa
bb","Model_Name":"cc","Category_Name":"Horror
Figures","Paid":0,"DatePaid":null,"DateCreated":"10-Feb-17
07:55AM","DateLastUpdated":"10-Feb-17
07:55AM","LastUpdatedBy":"wf_anon"}]
MYSQLI
[{"ID":"55","Entry_Form_Number":"1005","Barcode_Text":"2017-1005","Entrant_Name":"aa
bb","Model_Name":"cc","Category_Name":"Dioramas","Paid":"1","DatePaid":"09-Feb-17
11:28AM","DateCreated":"03-Feb-17
01:11PM","DateLastUpdated":"09-Feb-17
11:28AM","LastUpdatedBy":"wf_boxoffice"},{"ID":"56","Entry_Form_Number":"1006","Barcode_Text":"2017-1006","Entrant_Name":"aa
bb","Model_Name":"cc","Category_Name":"Dioramas","Paid":"1","DatePaid":"09-Feb-17
11:28AM","DateCreated":"03-Feb-17
01:16PM","DateLastUpdated":"09-Feb-17
11:28AM","LastUpdatedBy":"wf_boxoffice"},{"ID":"59","Entry_Form_Number":"1009","Barcode_Text":"2017-1009","Entrant_Name":"aa
bb","Model_Name":"cc","Category_Name":"Original
Sculpt/Scratchbuilt","Paid":"1","DatePaid":"09-Feb-17
11:28AM","DateCreated":"04-Feb-17
10:32AM","DateLastUpdated":"09-Feb-17
11:28AM","LastUpdatedBy":"wf_boxoffice"},{"ID":"62","Entry_Form_Number":"1010","Barcode_Text":"2017-1010","Entrant_Name":"aa
bb","Model_Name":"cc","Category_Name":"Dioramas","Paid":"1","DatePaid":"09-Feb-17
11:28AM","DateCreated":"08-Feb-17
08:31PM","DateLastUpdated":"09-Feb-17
11:28AM","LastUpdatedBy":"wf_boxoffice"},{"ID":"63","Entry_Form_Number":"1011","Barcode_Text":"2017-1011","Entrant_Name":"aa
bb","Model_Name":"cc","Category_Name":"Dinosaurs","Paid":"0","DatePaid":null,"DateCreated":"09-Feb-17 08:12PM","DateLastUpdated":"09-Feb-17
08:12PM","LastUpdatedBy":"wf_anon"},{"ID":"64","Entry_Form_Number":"1012","Barcode_Text":"2017-1012","Entrant_Name":"aa
bb","Model_Name":"cc","Category_Name":"Horror
Figures","Paid":"0","DatePaid":null,"DateCreated":"10-Feb-17
07:55AM","DateLastUpdated":"10-Feb-17
07:55AM","LastUpdatedBy":"wf_anon"}]
No you can't. PDO doesn't provides such method to convert result.
So if you need string you need to do strval yourself.
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:
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')";
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 2 years ago.
Which means, at the moment, are the safest for screening data in php to send them to the mysql database.
Thank, you )
I believe mysql_real_escape_string() mysqli_real_escape_string() is the best way to escape input data
Later edit since everything is deprecated now and information must be valid:
Try to use PDO as prepared statements are much safer or mysqli_*() functions if you really need to keep old code somewhat up-to-date.
Currently the most preferred way to insure your safety is prepared statements.
example:
$preparedStatement = $db->prepare('SELECT * FROM memebers WHERE username = :username');
$preparedStatement->execute(array(':username' => $username));
$rows = $preparedStatement->fetchAll();
then when displaying your data use htmlspecialchars()
validMySQL($var) {
$var=stripslashes($var);
$var=htmlentities($var);
$var=strip_tags($var);
$var=mysql_real_escape_string($var);
return $var
}
The above code helps to sanitize most invalid data, just remember that you've to be connected to mysql database for mysql_real_escape_string to work...
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 3 years ago.
How do I escape quotes in PHP when trying to query a MySQL database?
Without adding addslashes on every value:
$fname = addslashes("Value's with quote''s'");
$lname = addslashes("Value's with quote''s'");
The proper way is using prepared statements, e.g. via PDO.
If you can't do that, you have to process all values which are passed into a database query with mysql_real_escape_string() - and no, doing that simply on all $_POST data is not an option since that would render them unusable for HTML output, etc. You could create a $_ESC or something similar though... but note that this variable will not be superglobal!
You ought to escape special characters (not only quotes) on every string value (it's useless to escape values you're not going to enclose in quotes in a query. Those values require another treatment).
To avoid boring repetitive typing you can apply an escaping function to array items in a loop.
In case you're using MySQL and for INSERT/UPDATE queries, you can use this helper function:
function dbSet($fields) {
$set = '';
foreach ($fields as $field) {
if (isset($_POST[$field])) {
$set .= "`$field`='" . mysql_real_escape_string($_POST[$field]) . "', ";
}
}
return substr($set, 0, -2);
}
It is used like this:
$id = intval($_POST['id']);
$table = 'users';
$fields = explode(" ","name surname lastname address zip fax phone");
$query = "UPDATE `$table` SET ".dbSet($fields).", `date`=NOW() WHERE id=$id";
Also don't forget to set proper encoding using mysql_set_charset() as it's required for the mysql_real_escape_string() function.
A good idea would be using PDO prepared statements as described here.
It will automatically escape those characters.
Firstly, don't use addslashes() - it is not recommended for use with escaping DB query strings because it doesn't escape everything that actually needs to be escaped; there are some characters that can still get through.
The correct solution depends on the database you're using. Assuming you're using MySQL, the correct function to use instead of addslashes() is mysql_real_escape_string().
You probably notice that using this on every line is even more verbose than addslashes(), so it doesn't really answer your question.
If your fields are all separate variables (as per your example), then you're really stuck with doing that for a bunch of lines of code.
If you're using an array (eg $_POST), then you can do it in a loop, which will make things a lot neater - you can do things like this:
foreach($_POST as $key=>$value) {
$sqlstrings[$key]="`".$key"` = '".mysql_real_escape_string($value)."'";
}
$sql = "update table ".implode(' ',$sqlstrings)." where id=".$update_id;
A more up-to-date method for doing SQL is to use an object model rather than manually building the queries. PHP has a number of libraries that may help: mysqli is an improved MySQL library, and PDO is a database-neutral library. Either of these would give you much better security and flexibility than building the SQL code directly. However if you already have a lot of code in place then they would represent a fairly significant overhead of code changes, so you may want to go with the mysql_real_escape_string() option discussed above in the short term. I do recommend investating them them though.