How to do mysql_fetch_assoc in mysqli?

后端 未结 2 1173
一向
一向 2020-12-20 18:43

How can I do the following in mysqli prepare statement?

$result = mysql_query($sql);
$data = mysql_fetch_assoc($result);
return $data:
相关标签:
2条回答
  • 2020-12-20 19:07

    You need to use the MySQLi version of the functions:

    $result = mysqli_query($sql);
    $data = mysqli_fetch_assoc($result);
    return $data;
    

    That should do it, you also might want to take a look at:

    • http://php.net/mysqli
    • http://www.php.net/manual/en/class.mysqli-result.php
    0 讨论(0)
  • 2020-12-20 19:09

    That's pretty simple after you've created the connection to mysql somewhere:

    <?php
    // create the connection to mysql.
    $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
    ?>
    

    The refer to the mysqli object when you need to do a query or do something else.

    <?php
    // get the result object.
    $result = $mysqli->query($sql);
    // fetch the result row.
    $data = $result->fetch_assoc();
    
    return $data;
    ?>
    

    Then at some point (if you have a class, you can write a destructor) you should close the connection to mysql if you won't need it anymore.

    <?php
    $mysqli->kill($mysqli->thread_id);
    $mysqli->close();
    ?>
    

    You can do much more with the result object you have. So read more about the MySQLi_Result here:

    • http://www.php.net/manual/en/class.mysqli-result.php
    0 讨论(0)
提交回复
热议问题