Prepare and execute

Often when using PDO, I want to prepare an instruction and then execute it only once. I do this so that I can make sure that all of my parameters are properly shielded.

As I understand it, by preparing the instruction and then executing it, you send 2 requests to the MySQL server, so this will actually be slower than manually escaping the parameters and sending one request through PDO :: query .

Is there no way to send a parameterized request plus parameter values ​​in one fell swoop?


I wrote a little test,

$t = new WxTimer(); for($i=0; $i<1000; ++$i) { $db->prepare("SELECT user_id, $i FROM wx_user WHERE user_id=?")->execute($i)->fetch(); } echo $t->elapsed().PHP_EOL; 

and launched it using ATTR_EMULATE_PREPARES . If the ATTR_EMULATE_PREPARES parameter ATTR_EMULATE_PREPARES set to true (which is the default value by default), it works about twice as fast (295 ms versus 639 ms).

Curious that this statement

 $db->query("SELECT user_id, $i FROM wx_user WHERE user_id=".$db->quote($i))->fetch(); 

It works in about 633 ms with emulation or 301 ms with emulation, despite the fact that no ready-made operators appear.

(If you are curious about syntax, I tried several methods in the PDO class)

+4
source share
2 answers

It depends on the setting of PDO :: ATTR_EMULATE_PREPARES ,

If you use emulation of prepared statements, then pdo will emulate the prepared statement for you, the deletion process will be performed using pdo. This way, it will send only one query to the database.

+1
source

look here: http://php.net/manual/en/pdo.quote.php

example:

 $pdo = new PDO ("mysql:host=$hostname;dbname=$dbname","$username","$pw"); $str = "gh'gh"; $str = $pdo->quote($str); $pdo->query ("UPDATE table SET field=$str") 

I think you want to.

for:

 $str = "gh'gh"; echo $pdo->quote($str); 

the output will be:

 'gh\'gh' 
-1
source

Source: https://habr.com/ru/post/1486502/


All Articles