PDO select from where in array() [duplicate] - php

What is this?
This is a list of frequently asked questions regarding PHP Data Objects
Why is this?
As PDO has some features unknown to a regular PHP user, questions regarding prepared statements and error handling in PDO are quite frequent. So, this is just a place where all them can be found.
What should I do here?
If your question has been closevoted with this list, please find your question below and apply the fix to your code. It is also a good idea to take a brief look to other questions, to make yourself prepared for other common pitfalls.
The List
PDO query fails but I can't see any errors. How to get an error message from PDO?
How can I use prepared statements with LIKE operator?
How can I create a prepared statement for IN () operator?
Can I use a PDO prepared statement to bind an identifier (a table or field name) or a syntax keyword?
PDO prepared statement causes an error in LIMIT statement
See also
Reference - What does this symbol mean in PHP?
Reference - What does this error mean in PHP?
Reference - What is variable scope, which variables are accessible from where and what are “undefined variable” errors?

PDO query fails but I can't see any errors. How to get an error message from PDO?
To be able to see database errors, one have to set PDO errmode to exceptions. Exceptions are better than regular errors in many ways: they always contains a stack trace, they can be caught using try..catch or handled using dedicated error handler. And even unhandled, they act as regular PHP errors providing all the important information, following site-wide error reporting settings.
Note that setting this mode as a connection option will let PDO throw exceptions on connection errors too, which is very important.
So, here is an example for creating a PDO connection right way:
$dsn = "mysql:host=$host;dbname=$db;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// other options
);
$pdo = new PDO($dsn, $user, $pass, $opt);
Connecting this way, you will be always notified of all database errors, occurred during query execution. Note that you have to be able to see PHP errors in general. On a live site you have to peek into error logs, so, settings have to be
error_reporting(E_ALL);
ini_set('display_errors',0);
ini_set('log_errors',1);
while on a local development server it's ok to make errors on screen:
error_reporting(E_ALL);
ini_set('display_errors',1);
and of course you should never ever use error suppression operator (#) in front of your PDO statements.
Also, due to many bad examples telling you to wrap every PDO statement into try..catch block, I have to make a distinct note:
DO NOT use try..catch operator just to echo an error message. Uncaught exception is already excellent for this purpose, as it will act just the same way as other PHP errors - so, you can define the behavior using site-wide settings - so, you will have your error message without this useless code. While unconditionally echoed error message may reveal some sensitive information to a potential attacker, yet confuse a honest visitor.
A custom exception handler could be added later, but not required. Especially for new users, it is recommended to use unhandled exceptions, as they are extremely informative, helpful and secure.
Use try..catch only if you are going to handle the error itself - say, to rollback a transaction.

PDO prepared statement causes an error in LIMIT clause
For compatibility purposes, PDO will just emulate prepared statements by substituting placeholders with actual data, instead of sending them to the server separately, unless told otherwise. And with "lazy" binding (using array in execute()), PDO will treat every parameter as a string. As a result, the prepared LIMIT ?,? query becomes LIMIT '10', '10' which is invalid syntax that causes query to fail.
This issue can be solved either
by turning emulation mode off (as MySQL can sort all placeholders properly):
$conn->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
by binding and setting proper type (PDO::PARAM_INT) explicitly:
$stm = $pdo->prepare('SELECT * FROM table LIMIT ?, ?');
$stm->bindValue(1, $limit_from,PDO::PARAM_INT);
$stm->bindValue(2, $per_page,PDO::PARAM_INT);
$stm->execute();
$data = $stm->fetchAll();

How can I use prepared statements with LIKE operator?
Prepared statement can represent complete data literal only. Not a part of literal, nor a complex expression, nor identifier. But either string or number only. So, a very common pitfall is a query like this:
$sql = "SELECT * FROM t WHERE column LIKE '%?%'";
If you ponder on this query a bit, you'd understand that being inside of single quotes, a question mark become a literal question mark, without any special meaning for the prepared statements.
So, one have to send complete string literal using prepared statement. There are 2 possible ways:
either prepare FULL expression first:
$name = "%$name%";
$stm = $pdo->prepare("SELECT * FROM table WHERE name LIKE ?");
$stm->execute(array($name));
$data = $stm->fetchAll();
or use a concatenation inside the query
$sql = "SELECT * FROM t WHERE column LIKE concat('%',?,'%')";
though the latter seems too bloated.

Related

Sql How to limit query with postional argument? [duplicate]

What is this?
This is a list of frequently asked questions regarding PHP Data Objects
Why is this?
As PDO has some features unknown to a regular PHP user, questions regarding prepared statements and error handling in PDO are quite frequent. So, this is just a place where all them can be found.
What should I do here?
If your question has been closevoted with this list, please find your question below and apply the fix to your code. It is also a good idea to take a brief look to other questions, to make yourself prepared for other common pitfalls.
The List
PDO query fails but I can't see any errors. How to get an error message from PDO?
How can I use prepared statements with LIKE operator?
How can I create a prepared statement for IN () operator?
Can I use a PDO prepared statement to bind an identifier (a table or field name) or a syntax keyword?
PDO prepared statement causes an error in LIMIT statement
See also
Reference - What does this symbol mean in PHP?
Reference - What does this error mean in PHP?
Reference - What is variable scope, which variables are accessible from where and what are “undefined variable” errors?
PDO query fails but I can't see any errors. How to get an error message from PDO?
To be able to see database errors, one have to set PDO errmode to exceptions. Exceptions are better than regular errors in many ways: they always contains a stack trace, they can be caught using try..catch or handled using dedicated error handler. And even unhandled, they act as regular PHP errors providing all the important information, following site-wide error reporting settings.
Note that setting this mode as a connection option will let PDO throw exceptions on connection errors too, which is very important.
So, here is an example for creating a PDO connection right way:
$dsn = "mysql:host=$host;dbname=$db;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// other options
);
$pdo = new PDO($dsn, $user, $pass, $opt);
Connecting this way, you will be always notified of all database errors, occurred during query execution. Note that you have to be able to see PHP errors in general. On a live site you have to peek into error logs, so, settings have to be
error_reporting(E_ALL);
ini_set('display_errors',0);
ini_set('log_errors',1);
while on a local development server it's ok to make errors on screen:
error_reporting(E_ALL);
ini_set('display_errors',1);
and of course you should never ever use error suppression operator (#) in front of your PDO statements.
Also, due to many bad examples telling you to wrap every PDO statement into try..catch block, I have to make a distinct note:
DO NOT use try..catch operator just to echo an error message. Uncaught exception is already excellent for this purpose, as it will act just the same way as other PHP errors - so, you can define the behavior using site-wide settings - so, you will have your error message without this useless code. While unconditionally echoed error message may reveal some sensitive information to a potential attacker, yet confuse a honest visitor.
A custom exception handler could be added later, but not required. Especially for new users, it is recommended to use unhandled exceptions, as they are extremely informative, helpful and secure.
Use try..catch only if you are going to handle the error itself - say, to rollback a transaction.
PDO prepared statement causes an error in LIMIT clause
For compatibility purposes, PDO will just emulate prepared statements by substituting placeholders with actual data, instead of sending them to the server separately, unless told otherwise. And with "lazy" binding (using array in execute()), PDO will treat every parameter as a string. As a result, the prepared LIMIT ?,? query becomes LIMIT '10', '10' which is invalid syntax that causes query to fail.
This issue can be solved either
by turning emulation mode off (as MySQL can sort all placeholders properly):
$conn->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
by binding and setting proper type (PDO::PARAM_INT) explicitly:
$stm = $pdo->prepare('SELECT * FROM table LIMIT ?, ?');
$stm->bindValue(1, $limit_from,PDO::PARAM_INT);
$stm->bindValue(2, $per_page,PDO::PARAM_INT);
$stm->execute();
$data = $stm->fetchAll();
How can I use prepared statements with LIKE operator?
Prepared statement can represent complete data literal only. Not a part of literal, nor a complex expression, nor identifier. But either string or number only. So, a very common pitfall is a query like this:
$sql = "SELECT * FROM t WHERE column LIKE '%?%'";
If you ponder on this query a bit, you'd understand that being inside of single quotes, a question mark become a literal question mark, without any special meaning for the prepared statements.
So, one have to send complete string literal using prepared statement. There are 2 possible ways:
either prepare FULL expression first:
$name = "%$name%";
$stm = $pdo->prepare("SELECT * FROM table WHERE name LIKE ?");
$stm->execute(array($name));
$data = $stm->fetchAll();
or use a concatenation inside the query
$sql = "SELECT * FROM t WHERE column LIKE concat('%',?,'%')";
though the latter seems too bloated.

PDO query not working with array of parameters [duplicate]

What is this?
This is a list of frequently asked questions regarding PHP Data Objects
Why is this?
As PDO has some features unknown to a regular PHP user, questions regarding prepared statements and error handling in PDO are quite frequent. So, this is just a place where all them can be found.
What should I do here?
If your question has been closevoted with this list, please find your question below and apply the fix to your code. It is also a good idea to take a brief look to other questions, to make yourself prepared for other common pitfalls.
The List
PDO query fails but I can't see any errors. How to get an error message from PDO?
How can I use prepared statements with LIKE operator?
How can I create a prepared statement for IN () operator?
Can I use a PDO prepared statement to bind an identifier (a table or field name) or a syntax keyword?
PDO prepared statement causes an error in LIMIT statement
See also
Reference - What does this symbol mean in PHP?
Reference - What does this error mean in PHP?
Reference - What is variable scope, which variables are accessible from where and what are “undefined variable” errors?
PDO query fails but I can't see any errors. How to get an error message from PDO?
To be able to see database errors, one have to set PDO errmode to exceptions. Exceptions are better than regular errors in many ways: they always contains a stack trace, they can be caught using try..catch or handled using dedicated error handler. And even unhandled, they act as regular PHP errors providing all the important information, following site-wide error reporting settings.
Note that setting this mode as a connection option will let PDO throw exceptions on connection errors too, which is very important.
So, here is an example for creating a PDO connection right way:
$dsn = "mysql:host=$host;dbname=$db;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// other options
);
$pdo = new PDO($dsn, $user, $pass, $opt);
Connecting this way, you will be always notified of all database errors, occurred during query execution. Note that you have to be able to see PHP errors in general. On a live site you have to peek into error logs, so, settings have to be
error_reporting(E_ALL);
ini_set('display_errors',0);
ini_set('log_errors',1);
while on a local development server it's ok to make errors on screen:
error_reporting(E_ALL);
ini_set('display_errors',1);
and of course you should never ever use error suppression operator (#) in front of your PDO statements.
Also, due to many bad examples telling you to wrap every PDO statement into try..catch block, I have to make a distinct note:
DO NOT use try..catch operator just to echo an error message. Uncaught exception is already excellent for this purpose, as it will act just the same way as other PHP errors - so, you can define the behavior using site-wide settings - so, you will have your error message without this useless code. While unconditionally echoed error message may reveal some sensitive information to a potential attacker, yet confuse a honest visitor.
A custom exception handler could be added later, but not required. Especially for new users, it is recommended to use unhandled exceptions, as they are extremely informative, helpful and secure.
Use try..catch only if you are going to handle the error itself - say, to rollback a transaction.
PDO prepared statement causes an error in LIMIT clause
For compatibility purposes, PDO will just emulate prepared statements by substituting placeholders with actual data, instead of sending them to the server separately, unless told otherwise. And with "lazy" binding (using array in execute()), PDO will treat every parameter as a string. As a result, the prepared LIMIT ?,? query becomes LIMIT '10', '10' which is invalid syntax that causes query to fail.
This issue can be solved either
by turning emulation mode off (as MySQL can sort all placeholders properly):
$conn->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
by binding and setting proper type (PDO::PARAM_INT) explicitly:
$stm = $pdo->prepare('SELECT * FROM table LIMIT ?, ?');
$stm->bindValue(1, $limit_from,PDO::PARAM_INT);
$stm->bindValue(2, $per_page,PDO::PARAM_INT);
$stm->execute();
$data = $stm->fetchAll();
How can I use prepared statements with LIKE operator?
Prepared statement can represent complete data literal only. Not a part of literal, nor a complex expression, nor identifier. But either string or number only. So, a very common pitfall is a query like this:
$sql = "SELECT * FROM t WHERE column LIKE '%?%'";
If you ponder on this query a bit, you'd understand that being inside of single quotes, a question mark become a literal question mark, without any special meaning for the prepared statements.
So, one have to send complete string literal using prepared statement. There are 2 possible ways:
either prepare FULL expression first:
$name = "%$name%";
$stm = $pdo->prepare("SELECT * FROM table WHERE name LIKE ?");
$stm->execute(array($name));
$data = $stm->fetchAll();
or use a concatenation inside the query
$sql = "SELECT * FROM t WHERE column LIKE concat('%',?,'%')";
though the latter seems too bloated.

Changing from mysqli to pdo

I do not have a problem with this code it surprisingly works fine but I really don't understand how it works or even is it right, so:
My queries with mysqli for ajax post or get calls were like this:
$con = mysqli_connect('localhost','root','','db') or die(header('Location: ./404.php'));
$add = "INSERT INTO table (id, id2, id3) VALUES('','$fid','')";
if(mysqli_query($con, $add)){
echo "added";
}
$remove = "DELETE FROM table WHERE id2='$fid'";
if(mysqli_query($con, $remove)){
echo "removed";
}
$getInfo = "SELECT * FROM table";
$result = $con->query($getInfo);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
//do something
}
}
And for $_POST or $_GET values I used mysqli_real_escape_string
Here is converted to PDO:
try{
$con = new PDO('mysql:host=localhost;dbname=db;charset=utf8mb4', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$get = $con->query("SELECT * FROM table");
foreach($get->fetchAll(PDO::FETCH_ASSOC) as $row){
$data['0'] = $row['name'];
$data['1'] = $row['email'];
return $data;
}
$add = $con->prepare("INSERT INTO table (id, id2, id3) VALUES(:f1,:f2,:f3)");
$add->execute(array(':f1' => '', ':f2' => $fid, ':f3' => ''));
echo "added";
$remove = $con->prepare("DELETE FROM table WHERE id2=:f1");
$remove->bindValue(':f1', $fid, PDO::PARAM_STR);
$remove->execute();
echo "removed";
}catch(PDOException $ex){
echo "error";
}
Now this works but I don't really know is it properly written with pdo where I don't need to use something like mysqli_real_escape_string with mysqli or something like that.
And all I could find on web is that how it is written now what part of code is doing what for example when I use in mysqli insert, update or delete I use
if(mysqli_query($con, $sql)){echo "success";}else echo 'fail';
How can I do that with pdo?
And also for using try and catch I don't know do I need to use it for every query or as I added above?
Just to say again I am new to pdo, I don't understand it very well and this code from above works but I do not know is it written the right way?
First off, let me congratulate you for going with PDO. Out of all the experienced PHP developers I know, it's near unanimous that they prefer PDO to mysqli.
I highly recommend you read through this guide to using PDO. It should answer all your questions and even answer a few you will likely have in the future.
To your specific questions:
No you do not need to escape anything anymore, so long as you are using prepared statements with placeholders. Escaping existed exactly because people were interpolating variables into SQL statements and that could confuse the quoting you needed to enclose strings.
With prepared statements that issue no longer exists, which also means that there is no longer the danger of SQL injection. SQL injection takes advantage of string concatenation to transform the original SQL statement into an entirely different one, again using quotes, which is why a non-escaped string accepted from user input was the attack vector for SQL injection. Both problems are solved using parameters and prepared statements.
As for error handling with PDO, you want to utilize PDO::ERRMODE_EXCEPTION which is discussed in the manual here.
Unfortunately, the default for PDO is PDO::ERRMODE_SILENT which essentially ignores database errors and just sets PDO object variables you would have to check yourself.
With that said, you can fix this by adding the error mode when you create the PDO connection object or just afterwards. Examples are on the PDO error mode page I linked.
As for Try-Catch blocks, in general an exception is not something you want to catch specifically unless you have some functional code to work around the error. Wrapping every sql call just so you can report an error message is bad, both from the point of view of DRY as well as being an anti-pattern. With the proper error mode, SQL errors will throw exceptions that you can handle in your error handler, and in general are things you shouldn't be eating up and continuing on from.
Your error handler should be (in production) logging the error to disk/emailing a sysadmin or site owner, and displaying a professional looking non-specific error message informing the user of the problem and that should be happening for all exceptions.

PHP Postgres PDO driver does not support prepared statement?

Am I losing my mind, or does the Postgres PDO driver just not support prepared statements, but instead emulates them client side?
The following code returns NO ERROR for the prepare() call, even though it should. Instead, it returns the applicable error when execute() is called.
Edit: Since according to Daniel Vérité I'm wrong, I added his suggested code. I still get the error. My code now looks like the below, with Daniel's line added.
<?php
$pdo = new PDO("pgsql:host=myhost;dbname=mydatabase");
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // as suggested by Daniel
$sth = $pdo->prepare('COMPLETE GARBAGE');
echo "[prepare] errorInfo = " . print_r($sth->errorInfo(), true);
$sth->execute();
echo "[execute] errorInfo = " . print_r($sth->errorInfo(), true);
PHP version 5.3.15, PHP Postgres client version 9.1.4, Postgres server version 9.2.1.
See http://www.php.net/manual/en/pdo.prepare.php
Note:
Emulated prepared statements does not communicate with the database
server so PDO::prepare() does not check the statement.
(in fact real prepared statements are not sent immediately anyway, see answer to Q2 below)
Anyway you may issue:
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
to get real prepared statements implemented with the SQL PREPARE command.
See http://www.php.net/manual/en/pdo.setattribute.php for more.
On further discussion and tests, two questions arise:
Q1. Why does pdo::getAttribute(PDO::ATTR_EMULATE_PREPARES) yield an error?
Indeed setAttribute doesn't error out but getAttribute(PDO::ATTR_EMULATE_PREPARES) says:
'SQLSTATE[IM001]: Driver does not support this function: driver does
not support that attribute'
Looking at the documentation for pdo::getAttribute, it says The constants that apply to database connections are as follows, and a number of constants follow from PDO::ATTR_AUTOCOMMIT to PDO::ATTR_TIMEOUT, and it's remarkable that PDO::ATTR_EMULATE_PREPARES is not in them. So strictly speaking, we should not expect getAttribute(PDO::ATTR_EMULATE_PREPARES) to work, anyway.
Now looking at the source code to be sure, it appears that the pdo_pgsql driver provides a pdo_pgsql_get_attribute function that has a switch statement on:
PDO_ATTR_CLIENT_VERSION
PDO_ATTR_SERVER_VERSION
PDO_ATTR_CONNECTION_STATUS
PDO_ATTR_SERVER_INFO
and that's it. No trace of PDO_ATTR_EMULATE_PREPARES which is why ultimately this error appears.
On the other hand, the function pdo_pgsql_set_attr has a switch statement on:
PDO_ATTR_EMULATE_PREPARES
PDO_PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT
which confirms that this attribute is actually taken into account when set.
So PDO is just inconsistent with getAttribute that doesn't match setAttribute.
Q2 - When prepare emulation is false, why doesn't a bogus statement immediately raise an error when prepared?
Consider this piece of code in pgsql_statement.c:
if (!S->is_prepared) {
stmt_retry:
/* we deferred the prepare until now, because we didn't
* know anything about the parameter types; now we do */
S->result = PQprepare(H->server, S->stmt_name, S->query,
stmt->bound_params ? zend_hash_num_elements(stmt->bound_params) : 0,
S->param_types);
It shows that PQprepare is used (so that's a "real" prepared statement), but also that the statement is not immediately sent to the server. That's why the dbo::prepare("bogus statement") won't return false: it's actually not sent to the server for lack of parameter types.

What is the PDO equivalent of function mysql_real_escape_string?

I am modifying my code from using mysql_* to PDO. In my code I had mysql_real_escape_string(). What is the equivalent of this in PDO?
Well No, there is none!
Technically there is PDO::quote() but it is rarely ever used and is not the equivalent of mysql_real_escape_string()
That's right! If you are already using PDO the proper way as documented using prepared statements, then it will protect you from MySQL injection.
# Example:
Below is an example of a safe database query using prepared statements (pdo)
try {
// first connect to database with the PDO object.
$db = new \PDO("mysql:host=localhost;dbname=xxx;charset=utf8", "xxx", "xxx", [
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
} catch(\PDOException $e){
// if connection fails, show PDO error.
echo "Error connecting to mysql: " . $e->getMessage();
}
And, now assuming the connection is established, you can execute your query like this.
if($_POST && isset($_POST['color'])){
// preparing a statement
$stmt = $db->prepare("SELECT id, name, color FROM Cars WHERE color = ?");
// execute/run the statement.
$stmt->execute(array($_POST['color']));
// fetch the result.
$cars = $stmt->fetchAll(\PDO::FETCH_ASSOC);
var_dump($cars);
}
Now, as you can probably tell, I haven't used anything to escape/sanitize the value of $_POST["color"]. And this code is secure from myql-injection thanks to PDO and the power of prepared statements.
It is worth noting that you should pass a charset=utf8 as attribute, in your DSN as seen above, for security reasons, and always enable
PDO to show errors in the form of exceptions.
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
so errors from you database queries won't reveal sensitive data like your directory structure, database username etc.
Last but not least, there are moments when you should not trust PDO 100%, and will be bound to take some extra measures to prevent sql injection, one of those cases is, if you are using an outdated versions of mysql [ mysql =< 5.3.6 ] as described in this answer
But, using prepared statements as shown above will always be safer, than using any of the functions that start with mysql_
Good reads
PDO Tutorial for MySQL Developers
There is none*! The object of PDO is that you don’t have to escape anything; you just send it as data. For example:
$query = $link->prepare('SELECT * FROM users WHERE username = :name LIMIT 1;');
$query->execute([':name' => $username]); # No need to escape it!
As opposed to:
$safe_username = mysql_real_escape_string($username);
mysql_query("SELECT * FROM users WHERE username = '$safe_username' LIMIT 1;");
* Well, there is one, as Michael Berkowski said! But there are better ways.
$v = '"'.mysql_real_escape_string($v).'"';
is the equivalent of $v = $this->db->quote($v);
be sure you have a PDO instance in $this->db so you can call the pdo method quote()
There is no need of mysql_real_escape_string in PDO.
PDO itself adjust special character in mysql query ,you only need to pass anonymous parameter and bind it run time.like this
Suppose you have user table with attribute name,email and password and you have to insert into this use prepare statement like this
you can pass name as => $name="Rajes'h ";
it should execute there is no need of equivalent of mysql_real_escape_string
$stmt="INSERT into user(name,email,password) VALUES(:name,:email,:password)";
try{
$pstmt=$dbh->prepare($stmt);//$dbh database handler for executing mysql query
$pstmt->bindParam(':name',$name,PDO::PARAM_STR);
$pstmt->bindParam(':email',$email,PDO::PARAM_STR);
$pstmt->bindParam(':password',$password,PDO::PARAM_STR);
$status=$pstmt->execute();
if($status){
//next line of code
}
}catch(PDOException $pdo){
echo $pdo->getMessage();
}
The simplest solution I've found for porting to PDO is the replacement for mysql_real_escape_string() given at https://www.php.net/manual/en/mysqli.real-escape-string.php#121402. This is by no means perfect, but it gets legacy code running with PDO quickly.
#samayo pointed out that PDO::quote() is similar but not equivalent to mysql_real_escape_string(), and I thought it might be preferred to a self-maintained escape function, but because quote() adds quotes around the string it is not a drop in replacement for mysql_real_escape_string(); using it would require more extensive changes.
In response to a lot of people's comments on here, but I can't comment directly yet (not reached 50 points), there ARE ACTUALLY needs to use the $dbh->quote($value) EVEN when using PDO and they are perfectly justifiable reasons...
If you are looping through many records building a "BULK INSERT" command, (I usually restart on 1000 records) due to exploiting InnoDb tables in MySQL/Maria Db. Creating individual insert commands using prepared statements is neat, but highly inefficient when doing bulk tasks!
PDO can't yet deal with dynamic IN(...) structures, so when you are building a list of IN strings from a list of user variables, YOU WILL NEED TO $dbh->quote($value) each value in the list!
So yes, there is a need for $dbh->quote($value) when using PDO and is probably WHY the command is available in the first place.
PS, you still don't need to put quotes around the command, the $dbh->quote($value) command also does that for you.
Out.
If to answer the original question, then this is the PDO equivalent for mysql_real_escape_string:
function my_real_escape_string($value, $connection) {
/*
// this fails on: value="hello'";
return trim ($connection->quote($value), "'");
*/
return substr($connection->quote($value), 1, -1);
}
btw, the mysqli equivalent is:
function my_real_escape_string($value, $connection) {
return mysqli_real_escape_string($connection, $value);
}

Categories