2014-07-16 61 views
1

在下面的代码中,如果我尝试使用不同的参数集执行两次连续执行后获取结果,它将显示相同的结果集(第一个两次),而不是使用不同的参数显示两个结果。我该怎么办?另外,在PHP手册中,$ sqli-> bind_results()放在$ sqli-> execute()之后,是否始终是强制的,还是在$ sqli-> execute()之前放置$ sqli-> bind_results() ?MySQLi中的绑定结果

<?php 
    $mysqli = new mysqli("localhost","root","","test"); 

    /*check connection*/ 
    if(mysqli_connect_errno()) 
    { 
    printf("connection failed: %s\n",mysqli_connect_error()); 
    exit(); 
    } 

    /*create prapared statement*/ 

    $sqli = $mysqli->prepare("select post_id from posts where id=?"); 

    /*bind params*/ 
    $sqli->bind_param('i',$id); 


    /*set params*/ 
    $id =1; 

    /*execute prapared statement*/ 
    $sqli->execute(); 

    /*bind results*/ 
    $sqli->bind_result($post_id); 

    while($sqli->fetch()) 
    { 
    echo ' '.$post_id; 

    } 

    echo '<br/>fetch new record<br/>'; 

    /*set params*/ 
    $id =2; 

    /*execute prapared statement*/ 
    $sqli->execute(); 


    while($sqli->fetch()) 
    { 
    echo ' '.$post_id; 

    } 

执行的循环:*

场景1:调用bind_result($ POST_ID)反复

<?php 
    $mysqli = new mysqli("localhost","root","","test"); 

    /*check connection*/ 
    if(mysqli_connect_errno()) 
    { 
    printf("connection failed: %s\n",mysqli_connect_error()); 
    exit(); 
    } 

    /*create prapared statement*/ 

    $sqli = $mysqli->prepare("select post_id from posts where id=?"); 

    /*bind params*/ 
    $sqli->bind_param('i',$id); 

    for($x=0;$x<1000;$x++) 
    { 

    $id =$x; 


    $sqli->execute(); 

    /*****bind results*****/ 

    $sqli->bind_result($post_id); 

    while($sqli->fetch()) 
    { 
     echo ' '.$post_id; 

    } 
    } 
?> 

第二幕::调用bind_result($ POST_ID)一旦

<?php 
    $mysqli = new mysqli("localhost","root","","test"); 

    /*check connection*/ 
    if(mysqli_connect_errno()) 
    { 
    printf("connection failed: %s\n",mysqli_connect_error()); 
    exit(); 
    } 

    /*create prapared statement*/ 

    $sqli = $mysqli->prepare("select post_id from posts where id=?"); 

    /*bind params*/ 
    $sqli->bind_param('i',$id); 

    /*****bind results*****/ 

    $sqli->bind_result($post_id); 

    for($x=0;$x<1000;$x++) 
    { 

    $id =$x; 


    $sqli->execute(); 


    while($sqli->fetch()) 
    { 
     echo ' '.$post_id; 

    } 
    } 
?> 

现在,在execute()之后应该使用PHP手册bind_result(),但是如上面的scene1所示,这将重复调用“bind_result()”,而在scene2中它只调用一次,并且仍然很好。哪种方法更好? scen2有效吗?

回答

0

是的,您需要在每个execute之后运行bind_result

the manual ...

注意,所有列必须mysqli_stmt_execute()之后和调用mysqli_stmt_fetch()之前约束。

所以,你只缺少第二(必填)调用bind_result ...

$id = 2; 
$sqli->execute(); 
$sqli->bind_result($post_id); 
+0

谢谢@phil,但我有一个问题:不过它是确定绑定它的第二次如你在答案中提到的那样。但是如果我在一个循环内执行它,并且需要将循环连续多次进行绑定,那么它是否意味着一次又一次地调用bind_result()函数..除此之外,还有什么替代方法? –

+0

@ParveezAhmed每次你调用execute时,都会在内部加载一个新的结果对象。因此,你需要重新绑定你的结果变量。 – Phil

+0

我编辑了我的问题@phil –