This question already has answers here:
Why is PDO better for escaping MySQL queries/querystrings than mysql_real_escape_string?
(6 answers)
Closed 9 years ago.
$q = "INSERT INTO articles VALUES( mysql_real_escape_string($_GET["article"]) )
$req = $bdd->prepare($q);
$req ->execute();
I've been working on another server where mysql_real_escape_string() is still not obsolete, and now I'm moving the site to another mysql server which apparently doesn't accept this function anymore. And, it's pretty clear I need to use some PDOs
SO what's the PDO equivalent for mysql_real_escape_string()? I'm trying something like this
$idc = new PDO(...);
$q = "INSERT INTO articles VALUES( $idc->quote(($_GET["article"])));
$req = $bdd->prepare($q);
$req ->execute();
I do use prepared statements, but I suspect my PDO::quote is wrong somewhere.
But it doesn't render the same result...
Thank you.
PDO::quote is the equivalent of mysql_real_escape_string. If there's some reason you can't use a prepared statement, you can use it like this:
$q = "INSERT INTO articles VALUES (" . $idc->quote($_GET["article"]) . ")";
A significant difference is that it includes the surrounding quotes around the string, while mysql_real_escape_string doesn't (so you would have to put quotes in your INSERT string).
Use prepared statements(preferred) or PDO::quote()
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I have this mysql query:
$sql = "INSERT INTO lijsten(naam, niveau, nederlands, duits, frans, grieks,
engels, latijn, spaans, wiskunde, natuurkunde, scheikunde, geschiedenis,
economie, aardrijkskunde, ANW, godsdienst)
VALUES(\$_POST["naam"]\,\$_POST["niveau"]\,\$_POST["nederlands"]\,\$_POST["duits"]\,\$_POST["frans"]\,\$_POST["grieks"],\$_POST["engels"]\,\$_POST["latijn"]\,\$_POST["spaans"]\,\$_POST["wiskunde"]\,\$_POST["natuurkunde"]\,\$_POST["scheikunde"]\,\$_POST["geschiedenis"]\,\$_POST["economie"]\,\$_POST["aardrijkskunde"]\,\$_POST["ANW"]\,\$_POST["godsdienst"]\)";
It is sent to the database with this function:
function connectDB($sql) {
$DBcon = mysql_connect(host, user, pass) or die(mysql_error());
mysql_select_db(database);
$result = mysql_query($query) or die(mysql_error());
mysql_close($DBcon);
return $result;
But when i try to run it, it gives me a php parse error:
PHP Parse error: syntax error, unexpected 'naam' (T_STRING) in /media/usbdisk/website/www/boeken/naardb.php on line 11
Could somebody tell me what mistake i am making? I already have tried many ways of putting the query, but none of them worked.
You should never build queries like this.
This is not how you escape values
mysql_ is deprecated and you should be using prepared statements
Example in PDO:
$sql = "INSERT INTO lijsten(naam, niveau, nederlands, duits, frans, grieks,
engels, latijn, spaans, wiskunde, natuurkunde, scheikunde, geschiedenis,
economie, aardrijkskunde, ANW, godsdienst)
VALUES(:naam,:niveau .......)";
if($stmt = $pdo->prepare($sql)){
$stmt->bindValue(:naam, $_POST["naam"]);
.....
$stmt->execute();
}
There are several mistakes, but I'll start with the issue.
unexpected 'naam' (T_STRING)...
Is caused because PHP was not expecting a string there. You're escaping parts of the query, but you really just need to concatenate the $_POST variables.
I would advise setting the posts variables to their own variables to simplify your query and format the query like this answer outlines: Using php variables inside MySQL insert statement
IE: $naam = $_POST["naam"]; etc...
The biggest issue is that you're using a deprecated method, you should use PDO (Prepared) queries
PHP deprecated methods.
You should definitely look into using PDO and preparing your statement.
A couple quick reference for PDO:
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
http://php.net/manual/en/book.pdo.php
Good luck!
Try to concat the variables in your query like this:
"INSERT INTO lijsten(naam, niveau, nederlands, duits, frans, grieks,
engels, latijn, spaans, wiskunde, natuurkunde, scheikunde, geschiedenis,
economie, aardrijkskunde, ANW, godsdienst)
VALUES("
.mysql_escape_string($_POST['naam']).
")";
and to read about sql injections too.
The #meda answer is the correct example of how to create SQL calls, using PDO.
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
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.
prepare() seems a bit tedious and unnecessary for a majority of my code. If I send a string in a SQL command, why can't I just sanitize it with real_escape_string? What's the difference? That's what I've been doing all the time and it worked well against SQL injections... Thanks.
Escaping is just as effective at SQL injection defense as using query parameters.
Both methods are also less effective if you fail to do them consistently.
Both methods are useful only for protecting individual values in SQL expressions. They don't support other dynamic parts of the query. For example, if you want to ORDER BY a user-specified column. Neither query parameters nor escaping functions handle that.
So basically, it is a matter of style and personal preference.
I prefer query parameters because I think this:
$sql = "INSERT INTO mytable (columna, columnb, columnc) VALUES (?, ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$a, $b, $c]);
Is more clear than this:
$sql = "INSERT INTO mytable (columna, columnb, columnc) VALUES ('".mysqli_real_escape_string($conn, $a)."', '".mysqli_real_escape_string($conn, $b)."', '".mysqli_real_escape_string($conn, $c)."')";
mysqli_query($conn, $sql);
You can't seriously be saying that fiddling with all those open-quotes/close-quotes and . string concatenation is easier than using prepare() with query parameters.
Re your comments about a hypothetical query() function with parameters.
First of all, it's not necessary. Using prepare() and execute() together is a small price to pay for writing secure code, and by insisting on doing it with a single function, you just sound lazy. I suppose you don't check the return value of functions that return false on error, either?
For what it's worth, it'd be easy to write a wrapper function to do both, because PHP supports varargs implicitly.
function myquery() {
global $pdo;
$params = func_get_args();
$sql = array_shift($params);
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
return $stmt; // so we can fetch(), etc.
}
This question already has answers here:
Real escape string and PDO [duplicate]
(3 answers)
Closed 10 years ago.
I would like to know how to escape strings in pdo .
I have been escaping the springs like in the code bellow but now with pdo I do not know how to do it
$username=(isset($_POST['username']))? trim($_POST['username']): '';
$previlage =(isset($_GET['previlage']));
$query ="SELECT * FROM site_user
WHERE username = '".mysql_real_escape_string($_SESSION['username'])."' AND previlage ='Admin'";
$security = mysql_query($query)or die (mysql_error($con));
$count = mysql_num_rows($security);
Well, you can use PDO::quote, but, as said in its own docpage...
If you are using this function to build SQL statements, you are
strongly recommended to use PDO::prepare() to prepare SQL statements
with bound parameters instead of using PDO::quote() to interpolate
user input into an SQL statement.
In your case it can look like this:
$query = "SELECT *
FROM site_user
WHERE username = :username AND previlage = 'Admin'";
$sth = $dbh->prepare($query);
$sth->execute(array(':username' => $_SESSION['username']) );
mysql_* function will not work in PDO. WHY? Because PDO doesnt use mysql to connect to a databases, as far as input sanitization, PDO uses prepared statements you can find a good tutorial for that here: pdo