开发者社区> 问答> 正文

如何使用bind_result与get_result的示例

我想看一个示例,该示例如何使用bind_resultvs. 进行调用,get_result以及一个使用另一个调用的目的。

也是使用每种方法的利弊。

使用两者之一的局限性是什么?

展开
收起
保持可爱mmm 2020-05-10 21:37:08 591 0
1 条回答
写回答
取消 提交回答
  • 对我来说,决定性的因素是我是否使用调用查询列*。

    bind_result()为此,使用会更好: // Use bind_result() with fetch() $query1 = 'SELECT id, first_name, last_name, username FROM table WHERE id = ?'; get_result()为此,使用会更好: // Use get_result() with fetch_assoc() $query2 = 'SELECT * FROM table WHERE id = ?'; 示例1 $query1使用bind_result() $query1 = 'SELECT id, first_name, last_name, username FROM table WHERE id = ?'; $id = 5;

    if($stmt = $mysqli->prepare($query)){ /* Binds variables to prepared statement

        i    corresponding variable has type integer
        d    corresponding variable has type double
        s    corresponding variable has type string
        b    corresponding variable is a blob and will be sent in packets
    

    */ $stmt->bind_param('i',$id);

    /* execute query */ $stmt->execute();

    /* Store the result (to get properties) */ $stmt->store_result();

    /* Get the number of rows */ $num_of_rows = $stmt->num_rows;

    /* Bind the result to variables */ $stmt->bind_result($id, $first_name, $last_name, $username);

    while ($stmt->fetch()) { echo 'ID: '.$id.'
    '; echo 'First Name: '.$first_name.'
    '; echo 'Last Name: '.$last_name.'
    '; echo 'Username: '.$username.'

    '; }

    /* free results */ $stmt->free_result();

    /* close statement */ $stmt->close(); }

    /* close connection */ $mysqli->close(); 实施例2对于$query2使用get_result() $query2 = 'SELECT * FROM table WHERE id = ?'; $id = 5;

    if($stmt = $mysqli->prepare($query)){ /* Binds variables to prepared statement

        i    corresponding variable has type integer
        d    corresponding variable has type double
        s    corresponding variable has type string
        b    corresponding variable is a blob and will be sent in packets
    

    */ $stmt->bind_param('i',$id);

    /* execute query */ $stmt->execute();

    /* Get the result */ $result = $stmt->get_result();

    /* Get the number of rows */ $num_of_rows = $result->num_rows;

    while ($row = $result->fetch_assoc()) { echo 'ID: '.$row['id'].'
    '; echo 'First Name: '.$row['first_name'].'
    '; echo 'Last Name: '.$row['last_name'].'
    '; echo 'Username: '.$row['username'].'

    '; }

    /* free results */ $stmt->free_result();

    /* close statement */ $stmt->close(); }

    /* close connection / $mysqli->close(); 正如你所看到的,你不能使用bind_result带。但是,get_result两者均可使用,但bind_result更简单,并且消除了一些麻烦$row['name']。

    bind_result() 优点:

    更简单 不用惹 $row['name'] 用途 fetch() 缺点:

    不适用于使用 * get_result() 优点:

    适用于所有SQL语句 用途 fetch_assoc() 缺点:

    必须搞乱数组变量 $row[] 不那么整齐 需要MySQL本机驱动程序(mysqlnd)来源:stack overflow

    2020-05-10 21:37:23
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
How to Build a Successful Data 立即下载
AutoAlerts-From Data to Action 立即下载
低代码开发师(初级)实战教程 立即下载