Maison >développement back-end >tutoriel php > php mysqli 预处理 如何绑定参数
php mysqli 预处理 怎么绑定参数
<br /> /**<br /> * php中预处理执行sql<br /> * $sql[String] sql语句<br /> * $args[array] 参数<br /> */<br /> public function exeSql($sql,$args){<br /> $mysqli_stmt=$mysqli->prepare($sql);<br /> //由于$sql由调用者传入,所以sql语句和参数个数都不确定<br /> //疑问1:怎么获取参数类型呢?php中有没有相应的函数呢?<br /> //如果没有我用如下方法:getParamTypeStr($arr)是否可行呢?有什么好的建议吗?<br /> //疑问2:怎么绑定参数呢?如下为参数个数确定时的绑定方法。<br /> //$mysqli_stmt->bind_param("ssi","xx","xx",20);<br /> $mysqli_stmt->execute();<br /> $mysqli->close();<br /> }<br /> <br /> private function getParamTypeStr($arr){<br /> $count = count($arr);<br /> $typestr = "";<br /> for($i = 0; $i<$count; $i++){<br /> $type = gettype($arr[$i]);<br /> switch($type){<br /> case "integer":<br /> $typestr.= "i";<br /> break;<br /> case "float":<br /> case "double":<br /> $typestr.= "d";<br /> break;<br /> case "string":<br /> $typestr.= "s";<br /> break;<br /> }<br /> }<br /> return $typestr;<br /> }<br />
<br /> //java中预处理执行sql<br /> public void exeSql(String sql,Object[] args){<br /> PreparedStatement preparedStatement = connection.prepareStatement(sql);<br /> for(int i =0;i<args.length;i++){<br /> preparedStatement.setObject(i+1, args[i]);<br /> }<br /> preparedStatement.executeUpdate();<br /> connection.close();<br /> }<br />
$callback = array($mysqli_stmt, 'bind_param');<br /> // 将参数类型描述加入数组<br /> array_unshift($args, getParamTypeStr($args)); <br /> call_user_func_array($callback, $args);<br /> // 它的调用类似:<br /> $mysqli_stmt->bind_param(getParamTypeStr($args), $args[0], $args[1], $args[2] ...);
<br> <?php <br /> <br> /* 连接数据库类 MysqlConnect */<br> <br> class MysqlConnect{<br> private $dbhost=null;<br> private $dbuser=null;<br> private $dbpwd=null;<br> private $dbname=null;<br> private $dbport=null;<br> private $ifpdo=null;<br> private $dburi=null;<br> private $handler=null;<br> <br> <br> function __construct($dbhost,$dbuser,$dbpwd,$dbname,$dbport,$ifpdo,$dburi){<br> $this->dbhost=$dbhost;<br> $this->dbuser=$dbuser;<br> $this->dbpwd=$dbpwd;<br> $this->dbname=$dbname;<br> $this->dbport=$dbport;<br> $this->ifpdo=$ifpdo;<br> $this->dburi=$dburi;//PDO的URI参数,可以查手册<br> if($this->ifpdo==1){//表示调用PDO来操作数据库<br> $this->handler=$this->CreatePdo();<br> }elseif($this->ifpdo==0){//这里可以写MYSQLI的方法<br> $this->handler=null;<br> }<br> }<br> /* ----------------这里是入口--------------------- */<br> //@param sql:外部调用时传递的完整SQL语句<br> //@param bindArray:绑定的参数数组,与sql语句有关,如果没有PDO占位符此处为空<br> //@param action:传递操作参数,"select"/"update"/"delete"/"insert"<br> public function exeSql($sql,$bindArray=array(),$action=""){ <div class="clear"> </div>