如何使用php对mysql数据库中检索到的数据进行分页
我在我的网站上有一个搜索页面,用户可以在其中搜索数据库中的所有数据。我在数据库中有一个名为property的表,所有搜索到的数据都是从该表中获取的。 现在我想将分页添加到我的结果页,只想在第一页显示8条记录。 我的网站是wordpress,根据搜索检索数据的代码如下:如何使用php对mysql数据库中检索到的数据进行分页,php,mysql,wordpress,Php,Mysql,Wordpress,我在我的网站上有一个搜索页面,用户可以在其中搜索数据库中的所有数据。我在数据库中有一个名为property的表,所有搜索到的数据都是从该表中获取的。 现在我想将分页添加到我的结果页,只想在第一页显示8条记录。 我的网站是wordpress,根据搜索检索数据的代码如下: <?php if(isset($_REQUEST['submit'])) { $search = $_POST['cs']; $field_array = array('ID',
<?php
if(isset($_REQUEST['submit']))
{
$search = $_POST['cs'];
$field_array = array('ID', 'ManagementCompanyID', 'MarketingName', 'PropertyURL', 'Address', 'City', 'State', 'PostalCode', 'StructureType', 'UnitCount', 'YearBuilt', 'LeaseLength', 'Parking', 'ShortDescription');
foreach($field_array as $value)
{
$query = "SELECT * FROM `wp_property` WHERE `$value` LIKE '%$search%' ";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
echo "<pre>";
print_r($row);
echo "<pre>";
}
}
}
?>
试试这个:
在循环中发送查询是个坏主意。使用或
在一个查询中组合多个条件。@ThiefMaster:不是这样,只是使用事务,而不是mysql\uU*
函数。对于修改数据的查询可能是这样的。但使用事务不会改善循环中的选择。
<?php
if(isset($_POST['submit'])) { // DO NOT USE $_REQUEST unless You are sure You need this... Use $_GET or $_POST accordingly...
$search = mysql_real_escape_string($_POST['cs']); // ALWAYS sanitize user input
$field_array = array('ID', 'ManagementCompanyID', 'MarketingName', 'PropertyURL', 'Address', 'City', 'State', 'PostalCode', 'StructureType', 'UnitCount', 'YearBuilt', 'LeaseLength', 'Parking', 'ShortDescription');
// Pagination
$limit = 15; // change that constant if You want or let it be a value from form...
$offset = isset($_POST['page']) ? mysql_real_escape_string($_POST['page']) : 0;
$offset = $offset * $limit;
$where = ' WHERE (';
$cnt = count($field_array);
$i = 0;
foreach($field_array as $value) {
$where .= " {$value} LIKE '%{$search}%'";
if($i < $cnt) $where .= ' OR ';
$i++;
}
$where .= ')';
$query = "SELECT * FROM `wp_property` {$where} LIMIT {$offset}, {$limit}";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
echo "<pre>";
print_r($row);
echo "<pre>";
}
}