如何在mysqli查询中使用while循环

时间:2012-09-30 16:55:15

标签: php mysqli

对这个非常愚蠢的问题感到抱歉。我有一个像这样的代码,我希望结果在while循环中完成。我正在使用mysql befor,查询很简单,执行得很好。 示例

$sql_query = mysql_query($query);
while($row = mysql_fetch_array($sql_query)
 {
   $data_a = $row['a']; $data_b = $row['b'];
 }

现在我使用oop,我有一个数据库类和一个连接处理程序,它被注入到从数据库类扩展的新类中。我的问题是在代码执行后,我得到这个错误方法* mysqli_stmt :: fetch_assoc()*这里是我的代码

<?php
class recentWorks extends DatabaseModelBase
{

public function show($tbl, $num_to_show, $site_url="") 
{

    $statement = $this->prepare('SELECT * FROM '.$tbl.' WHERE RAND()<(SELECT (( '.$num_to_show.' /COUNT(*))*10) FROM '.$tbl.' ) ORDER BY RAND() LIMIT  '.$num_to_show.'  ');
    $statement->execute();
    while ($recent_results = $statement->fetch_assoc())
    {
        $featured_work_name=$recent_results['name']; $featured_work_url=$recent_results['url']; $featured_work_thumb=$recent_results['img_thumb'];
        $featured_work_id=$recent_results['id'];$featured_work_desc=$recent_results['desc'];$featured_work_img=$recent_results['img_url'];
        ?>
  <li> 
  <a href="<?php echo $featured_work_img; ?>" class="fancybox thumb poshytip" title="Click To View Enlarged Image">
  <img src="<?php echo $featured_work_thumb; ?>" width="282px" height="150px" alt="<?php echo $featured_work_name; ?>' Image" />
  </a>
 <div class="excerpt">

 <span class="main_header"><a href="<?php echo $featured_work_url; ?>" target="_blank" class="poshytip recent-link" title="Click To Visit Website"><?php echo ucwords($featured_work_name); ?></a>
 </span>
<?php echo substr($featured_work_desc,0,300); ?>
</div>
</li>
        <?php
    }
    $statement->close();
    }

  }
 ?>

请有人为我调试这个

1 个答案:

答案 0 :(得分:1)

让我们看看之前

$sql_query = mysql_query($query);
   `----- missing error checking and handling
while ($row = mysql_fetch_array($sql_query))
         `---- missing error handline
{
    $data_a = $row['a']; $data_b = $row['b'];
           `----- complicated way of setting variables as arrays
}

现在让我们看看你现在拥有的(选定的行)

$statement = $this->prepare('SELECT * FROM '.$tbl.' WHERE RAND()<(SELECT (( '.$num_to_show.' /COUNT(*))*10) FROM '.$tbl.' ) ORDER BY RAND() LIMIT  '.$num_to_show.'  ');
                       `---- using prepare as if it would have been mysql_query()
$statement->execute();
            `----- same here

这是错误的。只是告诉你。我建议您首先搜索一些运行良好的mysqli_*教程。一个要么解释你如何构建SQL查询并解雇它们,它们解释了prepared statements是什么以及如何使用它们。

我的建议:从PHP手册开始,它会比较不同的库并显示所有mysql,mysqli和PDO的示例。

您甚至可以将mysql和mysqli并排比较,以便更轻松地进行迁移:Dual procedural and object-oriented interface