【问题标题】:PHP PDO Query for Event Listing事件列表的 PHP PDO 查询
【发布时间】:2012-09-14 01:26:52
【问题描述】:

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

其他方面都很好。

代码如下:

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>";

} 

}
}

谢谢

【问题讨论】:

  • 您遇到的实际问题是什么? SQL 错误,不是您预期的数据?
  • 没有给出任何错误但也没有打印出来

标签: php mysql list pdo fetch


【解决方案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__));
}

【讨论】:

  • 另外:while($fetch = $eq_check-&gt;fetch (PDO::FETCH_ASSOC) ){ if ($fetch == NULL ) { break; } - if 毫无意义。
  • 是的,我知道,因此我为第一个事件导入了一个虚拟内容,但之后还有其他事件,但我也无法列出它们..
  • @mrmryb 完全正确,我还要说第二个查询$foo = $db-&gt;query("SELECT FOUND_ROWS()")-&gt;fetchColumn(); 是不必要的,您可以在execute 语句之后立即开始获取行。
  • 我不认为它没有意义,因为我认为没有它会进入无限循环
  • @CastielMartin 您正在使用的 while 循环将在不再从数据库中获取行后停止,因为条件将评估为 false。将永远不会调用 break,因为一旦 $fetch 为空,while 循环将不会执行。
猜你喜欢
  • 2012-08-14
  • 1970-01-01
  • 2015-09-01
  • 2011-06-04
  • 2013-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多