【问题标题】:Loop MySQLi Prepared Statement with PHP OOP使用 PHP OOP 循环 MySQLi 准备好的语句
【发布时间】:2014-05-29 18:04:12
【问题描述】:

您好,每次我在 fetch() 函数上使用 while 循环时,我都在尝试使用用 PHP 编写的准备好的语句来遍历我的数据库表中的所有行 它让我陷入无限循环这是我的代码,请帮助

public function loadIndex() {
    $conn = new Database();
    $db = $conn->Connect();
    $query = "
        SELECT Title,Description,uploadeddate
        FROM article
        ORDER BY article.uploadeddate DESC LIMIT 10";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($title, $desc, $date);
    $num_rows = $stmt->num_rows();
    $fetch = $stmt->fetch();
    $data = array(
    'title' => $title,
    'desc' => $desc,
    'date' => $date,
        'num_rows' => $num_rows,
    'fetch' => $fetch
    );
    return $data;
}

这就是用途

<?php
  art = new Articles();
  $index = $art->loadIndex();
  $num =  $index['num_rows'];
  if($num != 0) {
while() {$index['fetch']} {
    echo $index['title']."<br />";
    echo $index['desc']."<br />";
    echo $index['date']."<br />";
   }
   }?>

谢谢

【问题讨论】:

  • 附注:不要在每个函数中连接。你会杀死你的mysql服务器。你应该只连接一次
  • 看来死循环是因为你的while语句没有条件
  • 就您的代码而言,您需要在函数内部而不是外部运行 while 循环

标签: php while-loop


【解决方案1】:

一团糟!

暂时忘记你的常识是非常有效的观点。

未测试,但可以尝试 10 年的初学者。

文章类

public function loadIndex() {
    $conn = new Database();
    $db = $conn->Connect();

    $title = '';
    $desc = '';
    $date = '';
    $data = array();

    $query = "SELECT Title,Description,uploadeddate
              FROM article
              ORDER BY article.uploadeddate DESC LIMIT 10";

    $stmt = $db->prepare($query);
    $stmt->execute();

    $stmt->bind_result($title, $desc, $date);

    while ( $stmt->fetch() ) {

        $data[] = array(
                   'title'    => $title,
                   'desc'     => $desc,
                   'date'     => $date                      
                  );
    }

    return $data;
}

调用Article->loadIndex()的主代码

<?php
    art = new Articles();
    $index = $art->loadIndex();

    // you dont need to know how big the $index array is here
    // if its empty then the foreach will just not run.

    foreach ($index as $row) {
        echo $row['title'] . '<br />';
        echo $row['desc'] . '<br />';
        echo $row['date'] . '<br />';
   }
?>

【讨论】:

    【解决方案2】:

    在您的索引中:

    While($stmt->fetch())
    {
    $index =count($data);
    $data['title'][$index] = $title;
    ...
    }
    

    【讨论】:

      【解决方案3】:

      首先,您应该只建立一次数据库连接,而不是在每个函数调用中。连接后,您只需在函数内执行查询,因此无需每次都连接。

      其次是无限循环,因为你在while循环中没有条件。

      所以改变这个:

      while() {$index['fetch']}
      

      while($index['fetch'])
      

      谢谢 阿马尔

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-01
        • 2016-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多