Home  >  Q&A  >  body text

Why can't I use $mysqli->query in a custom function?

MCXCI}8`AS6FQ6ZJ7TUW)%H.png

别闹i别闹i2614 days ago1004

reply all(1)I'll reply

  • 天蓬老师

    天蓬老师2017-09-15 14:31:20

    There is something wrong with your usage~~

    The prerequisite for using $mysqli->query() is: you have created the $mysqli object. I wonder if you have created this object in the dbconfigs.php file?

    Also, you used mysqli_fetch_array() below. This is a typical process-oriented statement. I really don’t understand how you want to call the data?

    If you want to use object-oriented, please use it like this:

    $mysqli = new mysqli($host,$userName,$password,$dbName);
    if ($mysqli->connect_errno){
        die('Error Connected'.$mysqli->connect_error;
    }
    $result = $mysqli->query('SELECT * FROM table_name');
    if ($result && $result->num_rows > 0){
    while($row = $result->fetch_array(MYSQLI_ASSOC)){
       //输出数据
     }
     $result->free_result();
    }
    $mysqli->close();

    If it is process-oriented, please modify the above code:

    $conn = mysqli_connect($host,$userName,$password,$dbName);
    if (mysqli_connect_errno($conn)){
        die('Error Connected'.mysqli_connect_error($conn);
    }
    $result = mysqli_query('SELECT * FROM table_name');
    if ($result && mysqli_num_rows($conn,$result) > 0){
    while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
       //输出数据
     }
     mysqli_free($result);
    }
    mysqli_close($conn);

    Please do not mix object-oriented and process-oriented.

    PHP Chinese website has tutorials for these two parts:

    http://www.php.cn/course/653.html (MySQLi object-oriented)

    http://www.php.cn/course/653 .html (MySQLi is process-oriented)

    reply
    1
  • 别闹i

    $mysqli=new mysqli("localhost","root","root","perform_file") or die("Failed to connect to database"); $mysqli->query("set names utf8"); //This is the configuration in dbconfigs.php mysqli_fetch_array //Isn't this looping out the query result set through the array?

    别闹i · 2017-09-18 09:23:35
    别闹i

    Is there any problem with the configuration in dbconfigs.php?

    别闹i · 2017-09-18 09:43:54
    天蓬老师

    mysqli_fetch_array() converts the result set into array output one by one, including index and association

    天蓬老师 · 2017-09-18 09:29:22
  • Cancelreply