dongpankao6133 2015-06-07 10:47
浏览 25
已采纳

将mysql查询转换为预准备语句

I'm trying to turn the below query into a prepared statement, but I'm having no luck so far. I've attached one of my attempts. The idea is I'm using this to check how many rows are returned using mysqli_num_rows afterward.

 $sql2=mysqli_query($bd, "SELECT address FROM member WHERE address='".$address."'");

This is my attempt at creating a prepared statement.

$ustmt = $bd->prepare("SELECT username FROM member WHERE username = ?");
$ustmt->bind_param("s", $username);
$sql2 = $ustmt->execute();

Is this correct? And if so, how do I then check the number of rows returned into $sql2 ?

  • 写回答

1条回答 默认 最新

  • doutandusegang2961 2015-06-07 10:58
    关注

    Yes, your preparation and execution is correct.

    The execute call returns a boolean value, which will be true if successful else false (if false, the $stmt->error property will be set with error message).
    This is worth checking before continuing, cause if its false, there will be no result.
    Same with the preparation, if the $mysqli->prepare(...) call returns false, the $mysqli->error will be set with the error message.

    After execution, you can fetch the number of affected rows by either the $num_rows property, in case its a SELECT statement, or the $affected_rows property in other cases.

    echo $stmt->num_rows;
    

    Or, you can fetch the mysqli_result object from the statement with the get_result() method.
    The mysqli_result object contains the public field $num_rows, so you can check row count by:

    $res = $stmt->get_result();
    echo $res->num_rows;
    

    For other methods in the mysqli_result object, i recommend checking the docs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊