duanao4729 2013-06-24 10:54
浏览 28
已采纳

是否可以嵌套mysqli命令[关闭]

Using the php mysql functions, if I have a query that I know will only return one row from the data table I nest the functions like this:

$myVariable = mysql_fetch_assoc(mysql_query("SOME QUERY"));

Using the mysqli functions I have to have to use two lines of code:

$query = $db->query("SOME QUERY");
$myVariable = $query->fetch_assoc();

Is it possible to condense the two lines into one as I do using the older mysql functions?

  • 写回答

3条回答 默认 最新

  • dou91808 2013-06-24 11:00
    关注

    Yes you can do it but I wouldn't recommend it:

    $myVariable = $db->query("SOME QUERY")->fetch_assoc();
    

    It's a bad idea because you don't get the opportunity to do any error handling. For example:

    $myVariable = array();
    
    $result = $db->query("SOME QUERY");
    if($result && $result->num_rows == 1)
    {
        $myVariable = $result->fetch_assoc();
    }
    

    If you nest or chain the calls, you might run into unhandled fatal errors because query() will return false if there was a MySQL error.

    If you're looking to tidy up your code or reduce it, you could extend the MySQLi class and add your own method to fetch a single row.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算