我正在我正在建立的网站上进行分页,我在这里找到了一个很好的分页示例:http://www.awcore.com/dev/1/3/Create-Awesome-PHPMYSQL-Pagination_en。我想在我的页面上看到这个,但我使用的是mysqli而不是mysql,需要转换一些。
我是MySQL的新手,我正试图找出转换以下代码的语法:
function pagination($query, $per_page = 10,$page = 1, $url = '?'){
$query = "SELECT COUNT(*) as `num` FROM {$query}";
$row = mysql_fetch_array(mysql_query($query));
$total = $row['num'];
$adjacents = "2";
我知道它并没有给你很多关于整个代码是什么(它大约100行),但我认为这可能是一个简单的语法更改。我最初这样做是这样的:
function pagination($query, $per_page = 10,$page = 1, $url = '?'){
$query = "SELECT COUNT(*) as `num` FROM {$query}";
$row = mysqli_fetch_array(mysqli_query($query));
$total = $row['num'];
$adjacents = "2";
我知道mysqli_query需要采用两个参数,但我也认为它对于mysql_query来说是一样的,所以我想我只是不理解代码。对不起,如果这是一个超级基本的问题,我只想试着围绕其中的一些概念!谢谢你的帮助。
BTW我确实看到了这个问题(Converting from mysql to mysqli (mysql_fetch_array)),但似乎他正在采取一些可能不需要采取的额外步骤。
以下是我用以上代码FYI获得的错误消息:
警告:mysqli_query()需要至少2个参数,1在第9行的linkinformation / functions.php中给出
警告:mysqli_fetch_array()要求参数1为mysqli_result,在第9行的linkinformation / functions.php中给出null
所以我在函数中添加了一个连接(这是正确的方法吗?我尝试在函数外连接,但它抓住了信息):
function pagination($mysqli, $query, $per_page = 10,$page = 1, $url = '?'){
$mysqli = mysqli_connect("localhost","username","password", "db_name");
$query = "SELECT COUNT(*) as `num` FROM {$query}";
$row = mysqli_fetch_array(mysqli_query($mysqli, $query));
$total = $row['num'];
$adjacents = "2";
我收到了这个警告:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in linkstuff/functions.php on line 10
它得到一个布尔值(我假设为TRUE),而它应该是我想的其他东西/实际查询。
答案 0 :(得分:1)
您还需要将连接更改为mysqli
,并将连接对象作为第一个参数传递给mysqli_query
。
function pagination($link, $query, $per_page = 10,$page = 1, $url = '?'){
$query = "SELECT COUNT(*) as `num` FROM {$query}";
$row = mysqli_fetch_array(mysqli_query($link, $query));
$total = $row['num'];
$adjacents = "2";
答案 1 :(得分:0)
这样的事情:
//You need to change thses variables
$conn = new mysqli('localhost','root','',$databasename);
function pagination( $conn,$query, $per_page = 10,$page = 1, $url = '?'){
$query = "SELECT COUNT(*) as `num` FROM {$query}";
$result = $conn->query($query);
$row=$result->fetch_array;
$total = $result->num_rows;
$adjacents = "2";
答案 2 :(得分:0)
//您需要更改变量
global $conn;
$conn = new mysqli('localhost','root','',$databasename);
function pagination($query, $per_page = 10,$page = 1, $url = '?'){
$query = "SELECT COUNT(*) as `num` FROM {$query}";
$result = $GLOBALS['conn']->query($query);
$row=$result->fetch_array;
$total = $result->num_rows;
$adjacents = "2";