不输出数据PDO

时间:2014-09-29 06:42:06

标签: php mysql pdo pagination prepared-statement


我还是PDO的新手 我正在写一个pdo分页但我的问题是,它没有输出数据 它只输出空白页

PHP代码

include "config.php";
if(isset($_POST['checkin'])){

$country = $_POST['country'];
$city = $_POST['city'];
$checkin = $_POST['checkin'];
$checkout = $_POST['checkout'];


$sql = $dbo->prepare("SELECT COUNT(id) FROM hotels");
if(!$sql->execute()){
    echo "No Count";
}else {
    $fetchrows = $sql->fetch();
    $rows = $fetchrows[0];
    $page_rows = 5;
    $last = ceil($rows/$page_rows);

    if($last < 1){
        $last = 1;
    }

    $page_num = 1;

    if(isset($_GET['pn'])){
       $page_num = preg_replace('#[^0-9]#', '', $_GET['pn']);
    }

    $limit = ($page_num - 1) * $page_rows;


$sql = $dbo->prepare("SELECT * FROM hotels DESC WHERE h_country='$country' LIMIT $limit");
    echo "<h3>Total hotels found: $rows</h3>";
    echo "Page <b>$page_num</b> of <b>$last</b>";
    $hotels = $sql->fetchAll(PDO::FETCH_OBJ);
    foreach($hotels as $hotel){
        echo $hotel->h_title;
    }
  }

 }

我通常在正常查询中进行分页声明,所以我尝试在PDO中做同样的事情,但它没有工作。
我不知道问题是什么。
如果你能指出我的错误,那就太好了。 感谢

这是我的PDO连接&amp; Mysql,我从网站上复制了PDO连接代码。

$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "test";

$dbserver = mysql_connect($dbhost,$dbuser,$dbpass);
if(!$dbserver) die ("Failed to Connect:" . mysql_error());

mysql_select_db($dbname) or die ("Unable to select the database");

try {
$dbo = new PDO('mysql:host=localhost;dbname='.$dbname, $dbuser, $dbpass);    
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}

我不确定错误是如何运作的

2 个答案:

答案 0 :(得分:1)

您在第二个查询中缺少execute()

$sql = $dbo->prepare("SELECT * FROM hotels DESC WHERE h_country='$country' LIMI$limit");

// add this
$sql->execute();

echo "<h3>Total hotels found: $rows</h3>";
echo "Page <b>$page_num</b> of <b>$last</b>";
$hotels = $sql->fetchAll(PDO::FETCH_OBJ);

答案 1 :(得分:0)

我仍然不知道问题是什么。 我去写了一个输出所有数据的代码,字面上都是NO LIMITS。 它工作,所以我复制代码并将其粘贴到上面的代码,看它是否有效,它确实

工作代码:

$stmt = $dbo->prepare("SELECT * FROM hotels WHERE h_country='Malaysia' LIMIT 5");
$stmt->bindParam(':country', $country);
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);

if(!$stmt->execute()){
       echo "\nPDO::errorInfo():\n";
      print_r($dbo->errorInfo());
}else {
    echo "<h3>Total hotels found: $rows</h3>";
echo "Page <b>$page_num</b> of <b>$last</b>";            
$hotels = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach($hotels as $hotel){

    echo "<h3>$hotel->h_title</h3>";
}
}

我想也许(只是可能)它的错(DESC)
我终于知道如何在PDO中使用while语句(非常简单,但我不知道:P)
感谢您的提示

原始代码:

    $sql = $dbo->prepare("SELECT * FROM hotels DESC WHERE h_country='$country' LIMIT $limit");
    echo "<h3>Total hotels found: $rows</h3>";
    echo "Page <b>$page_num</b> of <b>$last</b>";
    $hotels = $sql->fetchAll(PDO::FETCH_OBJ);
    foreach($hotels as $hotel){
        echo $hotel->h_title;
    }
  }