首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用预准备语句动态绑定参数?

如何使用预准备语句动态绑定参数?
EN

Stack Overflow用户
提问于 2018-06-24 21:45:52
回答 1查看 1.7K关注 0票数 4

我正在尝试为用户输入编写准备好的语句。参数数量是可变的,取决于用户输入。我正在尝试这段代码

php代码:

$string          = "my name";
$search_exploded = explode( " ", $string );
$num             = count( $search_exploded );
$cart            = array();
for ( $i = 1; $i <= $num; $i ++ ) {
    $cart[] = 's';
}
$str          = implode( '', $cart );
$inputArray[] = &$str;
$j            = count( $search_exploded );
for ( $i = 0; $i < $j; $i ++ ) {
    $inputArray[] = &$search_exploded[ $i ];
}
print_r( $inputArray );
foreach ( $search_exploded as $search_each ) {
    $x ++;
    if ( $x == 1 ) {
        $construct .= "name LIKE %?%";
    } else {
        $construct .= " or name LIKE %?%";
    }
}
$query = "SELECT * FROM info WHERE $construct";
$stmt  = mysqli_prepare( $conn, $query );
call_user_func_array( array( $stmt, 'bind_param' ), $inputArray );
if ( mysqli_stmt_execute( $stmt ) ) {

    $result = mysqli_stmt_get_result( $stmt );
    if ( mysqli_num_rows( $result ) > 0 ) {
        echo $foundnum = mysqli_num_rows( $result );
        while( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ) ) {

            echo $id = $row['id'];
            echo $name = $row['name'];
        }
    }
}

when I print_r $inputArray output is is:

   Array ( [0] => ss [1] => my [2] => name ) 

错误日志中未显示错误。我在这里做错了什么请告诉我。

EN

回答 1

Stack Overflow用户

发布于 2018-06-25 01:14:38

编写一个通用查询处理程序,并将查询、参数数组和参数类型列表传递给它。返回结果或消息数组。这是我个人的mysqli版本(我主要使用PDO,但也为此设置了一个类似的函数)。对插入、更新和删除执行相同的操作。然后简单地维护您的一个库,并将其用于您所做的一切:)请注意,如果您从这个开始,您可能想要更好地处理连接错误,等等。

<?php

// this is normally in an include() file
function getDBConnection(){

    // your DB credentials

    $hostname="127.0.0.1";
    $username="ausername";
    $password="supersecret";
    $database="some_db_name";

    $con = new mysqli($hostname, $username,$password, $database);
    if($con->connect_error) {
      return false;
    }
    return $con;
}

// generic select function.
// takes a query string, an array of parameters, and a string of
// parameter types
// returns an array - 
//   if $retVal[0] is true, query was successful and returned data
//   and $revVal[1...N] contain the results as an associative array
//   if $retVal[0] is false, then $retVal[1] either contains the 
//   message "no records returned" OR it contains a mysql error message

function selectFromDB($query,$params,$paramtypes){

    // intitial return;
    $retVal[0]=false;

    // establish connection
    $con = getDBConnection();
    if(!$con){
        die("db connection error");
        exit;
    }

    // sets up a prepared statement
    $stmnt=$con->prepare($query);
    $stmnt->bind_param($paramtypes, ...$params);
    $stmnt->execute();

    // get our results
    $result=$stmnt->get_result()->fetch_all(MYSQLI_ASSOC);
    if(!$result){
    $retVal[1]="No records returned";
    }else{
        $retVal[0]=true;
        for($i=0;$i<count($result);$i++){
            $retVal[]=$result[$i];
        }
    }

    // close the connection
    $con->close();

    return $retVal;

}

$myusername=$_POST['username'];
$mypassword=$_POST['password'];

// our query, using ? as positional placeholders for our parameters
$q="SELECT useridnum,username FROM users WHERE username=? and password=?";

// our parameters as an array - 
$p=array($myusername,$mypassword);

// what data types are our params? both strings in this case
$ps="ss";

// run query and get results
$result=selectFromDB($q,$p,$ps);

// no matching record OR a query error
if(!$result[0]){
    if($result[1]=="no records returned"){
        // no records
        // do stuff
    }else{
        // query error
        die($result[1]);
        exit;
    }   
}else{  // we  have matches!
    for($i=1;$i<count($result);$i++){
        foreach($result[$i] as $key->$val){
            print("key:".$key." -> value:".$val);
        }
    }
}

?>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51010509

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档