PDO 将是最好的选择,但如果你没有它。有一些模仿pg_query_params
mysql的方法。它被写成一个类的方法,$this->dbconn
是返回的连接资源mysqli_init
。当然,您可以mysqli
使用适当的mysql
类似物更改方法。
/**
* Returns the single value of the array mysqli_query_params__parameters
*
* @param $at the position of the parameter inside the array mysqli_query_params__parameters
* @return mixed
*/
public function mysqli_query_params__callback( $at )
{
return $this->mysqli_query_params__parameters[ $at[1]-1 ];
}
/**
* Parameterised query implementation for MySQL (similar PostgreSQL's PHP function pg_query_params)
* Example: mysqli_query_params( "SELECT * FROM my_table WHERE col1=$1 AND col2=$2", array( 42, "It's ok" ), $dbconn );
*
* @param $query, $parameters, $datadase
* @return mixed(resorce, false)
* @access public
*/
public function mysqli_query_params( $query, $parameters=array(), $database=false )
{
if( !is_array($parameters) ){
return false;
} else {
if($this->is_assoc($parameters)){
$parameters = array_values($parameters);
}
}
// Escape parameters as required & build parameters for callback function
foreach( $parameters as $k=>$v )
{
$parameters[$k] = ( is_int( $v ) ? $v : ( NULL===$v ? 'NULL' : "'".mysqli_real_escape_string( $this->dbconn, $v )."'" ) );
}
$this->mysqli_query_params__parameters = $parameters;
// Call using mysqli_query
if( false === $database )
{
$query = preg_replace_callback( '/\$([0-9]+)/', array($this, 'mysqli_query_params__callback'), $query );
$result = mysqli_query( $this->dbconn, $query );
if( false === $result )
{
$err_msg = mysqli_error($this->dbconn);
return false;
} else {
return $result;
}
}
else
{
$query = preg_replace_callback( '/\$([0-9]+)/', array($this, 'mysqli_query_params__callback'), $query );
$result = mysqli_query( $this->dbconn, $query, $database );
if( false === $result )
{
$err_msg = mysqli_error($this->dbconn);
return false;
} else {
return $result;
}
}
return false;
}