Export “query” from “mysqli->prepare”

风流意气都作罢 提交于 2019-12-01 18:49:49

I know that this would be useful for debugging, but it is not the way prepared statements work. Parameters are not combined with a prepared statement on the client-side. PHP should never have access to the query string combined with its parameters.

The SQL statement is sent to the database server when you do prepare(), and the parameters are sent separately when you do execute(). MySQL's general query log does show the final SQL with values interpolated after you execute(). Below is an excerpt from my general query log. I ran the queries from the mysql CLI, not from PHP, but the principle is the same.

081016 16:51:28 2 Query       prepare s1 from 'select * from foo where i = ?'
                2 Prepare     [2] select * from foo where i = ?
081016 16:51:39 2 Query       set @a =1
081016 16:51:47 2 Query       execute s1 using @a
                2 Execute     [2] select * from foo where i = 1

Re your comment:

@Baily is correct, MySQL has no client-side solution to return the full query with parameters interpolated. It's not the fault of PHP.

To enable the logging that I mention above, use this command, either in the MySQL client or submitted from PHP via an API:

SET GLOBAL general_log = ON;

You should turn off the log when you're done collecting information, because it does cost some overhead to be logging every query.

SET GLOBAL general_log = OFF;

PS: Changing the logging settings dynamically requires MySQL 5.1 or later. In earlier versions, you have to restart mysqld when you change logging.

Prepared statements don't work like that, theres a reason you aren't able to see the statement, because its supposed to be able to be passed to database without manipulation.

So the only solution to this is to just attach your data to your string, and echo or save to variable.

EDIT to include the security concern you commented on..

//Assume you're using $_GET to get the id
$data = mysql_real_escape_string($_GET['yourID']);

$yourStatement = 'SELECT `id`,`info` FROM `propertys` WHERE id>';
$savedStatement = $yourStatement.$data;

echo $savedStatement;
//Will return 'SELECT `id`,`info` FROM `propertys` WHERE id>4'

if ($stmt = $mysqli->prepare($yourStatement.'?')){
$stmt->bind_param('i',$data);
$stmt->execute();
  }
varubi

You could just reiterate the query string on the echo line and place your variables in the string manually like such:

if ($stmt = $mysqli->prepare('SELECT `id`,`info` FROM `propertys` WHERE id>?')){
    $stmt->bind_param('i',$data);
    if($stmt->execute()){
        echo 'SELECT `id`,`info` FROM `propertys` WHERE id>'.$data;
    };
}

Much of the comments you posted indicate your question was actually:

How to show the last queries executed on MySQL?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!