Felix Felix - 7 months ago 91
PHP Question

how to convert mysql_result in mysqli?

This code was previously in mysql and now since it is deprecated, I decided to convert my code in mysqli, but I'm having this problem in my page where there is pagination, before it works with mysql with no error, but now I get an error in this line:


Warning: mysqli_fetch_assoc() expects exactly 1 parameter, 2 given


The error is obvious, I know that, but I don't know how to do it the other way because previously my code in that line is

$pages = ceil(mysql_result($pages_query, 0) / $limit); // total number of pages


I also tried this

$pages = ceil($pages_query / $limit); // total number of pages


but I get this error


Notice: Object of class mysqli_result could not be converted to int


So I'm wondering how will I convert the mysql_* mysql_result to mysqli? or is there other way to do it?

So far my code is this:

<?php
include 'dbcontroller.php';

$limit = 10; // limit the number of post per page
$pages_query = mysqli_query($conn, "SELECT COUNT('id') FROM news");
$pages = ceil($pages_query / $limit); // total number of pages

$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $limit; // set the page to 0
$query = mysqli_query($conn, "SELECT * FROM news ORDER BY date DESC LIMIT $start, $limit");


while($row = mysqli_fetch_array($query)) {
....
}
?>

Answer

Problem is with this line you can't use mysqli_query() directly without fetching data

$pages = ceil($pages_query / $limit); // total number of pages

mysqli_query()

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object .

SO it would be

$pages_query = mysqli_query($conn, "SELECT COUNT('id') FROM news");

You need to fetch data from your query object

     $row = mysqli_fetch_array($pages_query);// fetch fata
     $ic = $row[0];
     $pages = ceil($ic / $limit); // total number of pages