2014-11-01 2 views
1

У меня есть сценарий, написанный в Mysql, который просто перечисляет имена людей. Он отлично работает в mysql, но я пытался его обновить до mysqli, и я получил большую часть его. Однако предполагается, что результаты будут разбиты на страницы. Пагинация работает отлично, потому что должно быть 5 страниц, и там, где она останавливается ... но ВСЕ результаты отображаются только на каждой странице. Не уверен, что я делаю ... любая помощь будет принята с благодарностью .... Я знаю, что он должен делать с «mysql_result»Миграция из MySQL в расширение MySQLi

Вот мой новый код в MySQLi:

<?php 
include ('paginate.php'); //include of paginat page 

$per_page = 10;   // number of results to show per page 
$result = $con->query("SELECT EmployeeID,FirstName,LastName FROM employee;"); 
//If Database Error...Print the error and exit 
if (!$result) { 
printf("Error: %s\n", mysqli_error($con)); 
exit(); 
} 
//If No Database Error.....Continue 
if ($result) 
{ 
// Return the number of rows in result set 
$total_results=mysqli_num_rows($result); 
//printf("Result set has %d rows.\n",$total_results); 
// Free result set 
} 
//total pages we going to have 
$total_pages = ceil($total_results/$per_page); 
//if page is setcheck 
$show_page=''; 
if (isset($_GET['page'])) { 
$show_page = $_GET['page'];//it will telles the current page 
if ($show_page > 0 && $show_page <= $total_pages) { 
$start = ($show_page - 1) * $per_page; 
$end = $start + $per_page; 
} else { 
// error - show first set of results 
$start = 0;    
$end = $per_page; 
} 
} else { 
// if page isn't set, show first set of results 
$start = 0; 
$end = $per_page; 
} 
// display pagination 
$page = intval(isset($_GET['page'])); 
$tpages=$total_pages; 
if ($page <= 0) 
$page = 1; 
?> 
<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<title>View All Employees</title> 
<link rel="stylesheet" type="text/css" href="css/style.css" /> 
</head> 
<body> 
<div class="container"> 
<div class="row"> 
<div class="logo"> 
<a href="#"><img src="../admin/images/logo-thompson-industrial-services.gif" class="text- center"width="259" height="59" /></a> 
</div> 
</div> 
<br /> 
<div class="row"> 
<div class="span6 offset3"> 
<div class="mini-layout"> 
<?php 
$reload = $_SERVER['PHP_SELF'] . "?tpages=" . $tpages; 
echo '<div class="pagination"><ul>'; 
if ($total_pages > 1) { 
echo paginate($reload, $show_page, $total_pages); 
} 
echo "</ul></div>"; 
// display data in table 
echo "<table class='table table-bordered'>"; 
echo "<thead><tr><th>First Name</th> <th>Last Name</th></tr></thead>";      
// loop through results of database query, displaying them in the table 
// loop through results of database query, displaying them in the table 
for ($i = $start; $i < $end; $i++) { 
// make sure that PHP doesn't try to show results that don't exist 
if ($i == $total_results) { 
break; 
} 
while($row = mysqli_fetch_assoc($result)) { 
$id = $row['EmployeeID']; 
$fname = $row['FirstName']; 
$lname = $row['LastName']; 
echo "<tr>"; 
echo '<td class="col-md-4">' .$fname .'</td>'; 
echo '<td class="col-md-4">' .$lname .'</td>'; 
echo "</tr>"; 
} 
} 
// close table> 
echo "</table>";    
?> 
</div> 
</div> 
</div> 
</div> 
</body> 
</html> 

И здесь мой исходный код в MySQL:

<?php 
error_reporting(E_ALL | E_NOTICE); 
ini_set('display_errors', '1'); 
error_reporting(E_ALL^E_DEPRECATED); 
include('config.php'); //include of db config file 
include ('paginate.php'); //include of paginat page 

$per_page = 10;   // number of results to show per page 
$result = mysql_query("SELECT * FROM employee"); 
$total_results = mysql_num_rows($result); 
$total_pages = ceil($total_results/$per_page);//total pages we going to have 

//-------------if page is setcheck------------------// 
$show_page=''; 
if (isset($_GET['page'])) { 
$show_page = $_GET['page'];    //it will telles the current page 
if ($show_page > 0 && $show_page <= $total_pages) { 
$start = ($show_page - 1) * $per_page; 
$end = $start + $per_page; 
} else { 
// error - show first set of results 
$start = 0;    
$end = $per_page; 
} 
} else { 
// if page isn't set, show first set of results 
$start = 0; 
$end = $per_page; 
} 
// display pagination 
$page = intval(isset($_GET['page'])); 

$tpages=$total_pages; 
if ($page <= 0) 
$page = 1; 
?> 


<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<title>View Employees</title> 
<link rel="stylesheet" type="text/css" href="css/style.css" /> 
<style type="text/css"> 

</style> 
</head> 
<body> 
<div class="container"> 
<div class="row"> 
<div class="logo"> 
<a href="#"><img src="../admin/images/logo-thompson-industrial-services.gif" class="text-center"width="259" height="59" /></a> 
</div> 
</div> 
<br /> 
<div class="row"> 
<div class="span6 offset3"> 
<div class="mini-layout"> 
<?php 
$reload = $_SERVER['PHP_SELF'] . "?tpages=" . $tpages; 
echo '<div class="pagination"><ul>'; 
if ($total_pages > 1) { 
echo paginate($reload, $show_page, $total_pages); 
} 
echo "</ul></div>"; 
// display data in table 
echo "<table class='table table-bordered'>"; 
echo "<thead><tr><th>First Name</th> <th>Last Name</th></tr></thead>"; 
// loop through results of database query, displaying them in the table 
for ($i = $start; $i < $end; $i++) { 
// make sure that PHP doesn't try to show results that don't exist 
if ($i == $total_results) { 
break; 
} 

// echo out the contents of each row into a table 
echo "<tr>"; 
echo '<td>' . mysql_result($result, $i, 'FirstName') . '</td>'; 
echo '<td>' . mysql_result($result, $i, 'LastName') . '</td>'; 
echo "</tr>"; 
}  
// close table> 
echo "</table>"; 
// pagination 
?> 
</div> 
</div> 
</div> 
</div> 
</body> 
</html> 

я делаю что-то здесь не так, и я не могу понять это ....

Любая помощь будет принята с благодарностью ...

Большое спасибо.

+0

Пожалуйста, попробуйте сварить код до минимального примера, который по-прежнему проявляет проблему; это не только помогает нам, но и поможет вам найти ответ самостоятельно. См. Http://stackoverflow.com/help/mcve – IMSoP

+0

Я пытаюсь преобразовать myqsl_result в mysqli .... он работает, но результаты все отображаются на одной странице ... вместо paginatd – user3251779

+0

Там много отсутствует: откуда берутся все переменные? Например. '$ Total_results'. – Paul

ответ

0

Я также хотел бы просто удалить заявление пока и использовать mysqli_data_seek в сочетании с mysqli_fetch_accoc. MySQLi_data_seek указывает на результат, который мне нужен. Проверьте это:

// display data in table 
echo "<table class='table table-bordered'>"; 
echo "<thead><tr><th>First 

Name</th> <th>Last Name</th></tr></thead>"; 
// loop through results of database query, displaying them in the table 
// loop through results of database query, displaying them in the table 
for ($i = $start; $i < $end; $i++) { 
// make sure that PHP doesn't try to show results that don't exist 
if ($i == $total_results) { 
break; 
} 

//go to the column you want the results 
mysqli_data_seek($result, $i); 
$row = mysqli_fetch_assoc($result); 
// echo out the contents of the row into a table 
echo "<tr>"; 
echo '<td>' . $row['FirstName'] . '</td>'; 
echo '<td>' . $row['LastName'] . '</td>'; 
echo "</tr>"; 
} 

} 
echo "</table>"; 
+0

Это сработало отлично .... я выберу его как правильный ответ .... Большое спасибо за вашу помощь. – user3251779

+0

Можете ли вы опротестовать мой вопрос? – user3251779

+0

Вы проверили другое решение? Что случилось с этим ответом. Да, я прошу вас голосовать. –

0

Проблема, с которой вы извлекаете запрос, является проблемой. После ввода while statement не уходить, пока все результаты не выполняются, а затем он выполняет

if ($i == $total_results) { 
    break; 
} 

Так что никогда не получает шанс закончить в $ я больше $ total_result. Исправление состоит в том, чтобы включить в запрос LIMIT и OFFSET. Это означает, что вы также должны исправить страницу разбивки на страницы.

Так просто запустите запрос снова нравится:

// display data in table 
echo "<table class='table table-bordered'>"; 
echo "<thead><tr><th>First 

Name</th> <th>Last Name</th></tr></thead>"; 
// loop through results of database query, displaying them in the table 
// loop through results of database query, displaying them in the table 
for ($i = $start; $i < $end; $i++) { 
// run the query again 

    $sql ="SELECT EmployeeID,FirstName,LastName FROM employee LIMIT $per_page OFFSET $end; 
    $result = $con->query($sql); 
    while($row = mysqli_fetch_assoc($result)) { 
     $id = $row['EmployeeID']; 
     $fname = $row['FirstName']; 

     $lname = $row['LastName']; 
     echo "<tr>"; 
     echo '<td class="col-md-4">' .$fname .'</td>'; 
     echo '<td class="col-md-4">' .$lname .'</td>'; 
     echo "</tr>"; 
    } 

} 
echo "</table>";    
+0

Спасибо большое за ответ .... знаете ли вы, как я исправил бы пагинизацию? – user3251779

+0

Мне нужно посмотреть код разбивки на страницы. Но да, я могу помочь –

Смежные вопросы