用于事件列表的PHP PDO查询

时间:2012-09-14 01:26:52

标签: php mysql list pdo fetch

我正在开展一个活动项目,我想展示他们在个人资料页面中托管的用户活动,但我坚持列出活动。

其他事情都运作良好。

以下是代码:

if(isset($_GET["id"])) {
$id = intval($_GET["id"]);
if(!empty($id)) {

try {
$pq = "SELECT * FROM `users` WHERE `id` = :id";
$pq_check = $db->prepare($pq);
$pq_check->bindParam(':id', $id, PDO::PARAM_INT);
$pq_check->execute();
$ac = $db->query("SELECT FOUND_ROWS()")->fetchColumn();
} 
catch(PDOException $e) { $log->logError($e." - ".basename(__FILE__));
}


// i'm fetching the user info and showing them name age gender exc. , no problem with here


echo "Events That User Hosted :\n";

// here is the place i have problem

$eq = "SELECT * FROM `events` WHERE `host_id` = :id";
$eq_check = $db->prepare($eq);
$eq_check->bindParam(':id', $id, PDO::PARAM_INT);
$eq_check->execute();
$foo = $db->query("SELECT FOUND_ROWS()")->fetchColumn();
if(!empty($foo)) {
$_loader = true;
$fetch = $eq_check->fetch (PDO::FETCH_ASSOC);
}

while($fetch = $eq_check->fetch (PDO::FETCH_ASSOC) ){ 
if ($fetch == NULL ) {
break;
}

$event_id = $fetch['event_id'];
$event_name = $fetch['event_name'];
$link = "https://www.mywebsite.com/e/$event_id";

echo "<a target=\"_blank\" href=\"$link\"><li>$event_name</li></a>";

} 

}
}

谢谢

1 个答案:

答案 0 :(得分:1)

一个问题是您获取结果集的第一行然后将其丢弃:

if(!empty($foo)) {
  $_loader = true;
  $fetch = $eq_check->fetch (PDO::FETCH_ASSOC);
}

/* above you have fetched the first row but that value gets overwritten
   directly after that: */

while ($fetch = $eq_check->fetch (PDO::FETCH_ASSOC) ) { 

/* $fetch now contains the second row of the result set, if it exists... */

编辑:我会清理代码,添加错误处理并查看会发生什么:

try
{
  $eq = "SELECT * FROM `events` WHERE `host_id` = :id";
  $eq_check = $db->prepare($eq);
  $eq_check->bindParam(':id', $id, PDO::PARAM_INT);
  $eq_check->execute();

  while($fetch = $eq_check->fetch (PDO::FETCH_ASSOC) )
  { 
    $_loader = true;

    $event_id = $fetch['event_id'];
    $event_name = $fetch['event_name'];
    $link = "https://www.mywebsite.com/e/$event_id";

    echo "<a target=\"_blank\" href=\"$link\"><li>$event_name</li></a>";
  }
} 
catch(PDOException $e)
{
  $log->logError($e." - ".basename(__FILE__));
}