简体   繁体   English

如何使用foreach循环生成mysql_query的结果

[英]how to use foreach loop in generating the result of mysql_query

Im always using while loop in generating all record in my database, and some of my friend told me that it is better to use foreach in generating record from a database, but i dont know how. 我一直在使用while循环在数据库中生成所有记录,而我的一些朋友告诉我,最好使用foreach从数据库中生成记录,但是我不知道如何。

<?php
    $query =  mysql_query("select * from sampleTABLE");
    while($i =  mysql_fetch_array){
    echo $i['samplefieldName'];
    }
?>

My question is, how to display records from my database using foreach? 我的问题是,如何使用foreach显示数据库中的记录? and can some one compare it in the while loop in terms in syntax and generating its result, thank you. 可以在while循环中比较一下它的语法并生成结果,谢谢。

There is no need to use foreach instead of while here as @Zerkms says 就像@Zerkms说的那样,这里不需要使用foreach而不是在这里

 while($i =  mysql_fetch_array( $query)){

however ou can do this by below code but i am sure its not good approach 但是你可以通过下面的代码做到这一点,但我确信它不是一个好方法

$result_list = array();
while($row = mysql_fetch_array($query)) {
   result_list[] = $row;
}

foreach($result_list as $item) {
   //you can now echo $item ; or whatever you want
}

Note 注意

  1. The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, is officially deprecated as of PHP v5.5.0 and will be removed in the future. 整个ext/mysql PHP扩展(提供所有带有前缀mysql_的功能)已从PHP v5.5.0开始正式弃用,以后将被删除。 So use either PDO or MySQLi 因此,请使用PDOMySQLi

Good read 好读

  1. The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead mysql扩展名已弃用,以后将被删除:改用mysqli或PDO
  2. PDO Tutorial for MySQL Developers MySQL开发人员的PDO教程
  3. Pdo Tutorial For Beginners Pdo初学者教程

Firstly, the mysql_xxx() functions are deprecated. 首先,不建议使用mysql_xxx()函数。 They are not recommended for use. 不建议使用它们。 There are two alternatives in PHP that are recommended instead -- mysqli() and PDO . 建议在PHP中使用两种替代方法mysqli()PDO

The older mysql_xxx() functions do not allow you to use foreach to loop through a recordset. 年长mysql_xxx()函数不允许你使用foreach通过记录循环。

However, both the newer alternative APIs do allow this, as they implement the Iterator interface. 但是,两个较新的替代API 允许这样 ,因为它们实现了Iterator接口。

So yes, it is possible to use foreach to loop through a recordset in PHP, but not with the old mysql_xxx() functions. 所以是的,可以使用foreach PHP中的记录集,但不能使用旧的mysql_xxx()函数。

You could write code like this: 您可以这样编写代码:

$conn = new mysqli(....);
foreach ( $conn->query('SELECT ....') as $row ) {
    print_r($row);
}

or like this: 或像这样:

$db = new PDO('mysql:....', $user, $pass);
foreach ($db->query('SELECT ....') as $row) {
    print_r($row);
}

Having said that, please note that it's only been possible to do this with mysqli since PHP v5.4, so you'll need to be up-to-date with your PHP version for that. 话虽如此,请注意,自PHP v5.4起,只能使用mysqli进行此操作,因此,您需要与此有关的PHP版本是最新的。 PDO on the other hand has supported this feature for ages. 另一方面, PDO支持此功能已有很长时间了。

They can, of course, both also use a while loop as well, and this is where your friend isn't quite right, because really there isn't any difference between while and foreach here. 当然,他们也可以同时使用while循环,而这正是您的朋友不太正确的地方,因为在这里, whileforeach之间确实没有任何区别。 Switching from while to foreach won't make any difference to the performance of your code. while切换到foreach不会对代码的性能产生任何影响。 They do the same thing under the hood. 他们在幕后做同样的事情。 foreach in this case is really just "syntactic sugar". 在这种情况下, foreach实际上只是“语法糖”。

I would strongly recommend switching to one of these newer APIs, even if you don't plan to use foreach to do your looping, because as I say, the old mysql functions are deprecated, which means that they are likely to be removed entirely from future PHP versions. 即使您不打算使用foreach进行循环,我也强烈建议切换到这些较新的API之一,因为正如我所说,旧的mysql函数已被弃用,这意味着它们很可能会从中完全删除。未来的PHP版本。 So if you want your code to keep running into the future, you should switch now. 因此,如果您希望代码在将来继续运行,则应立即切换。

It's not possible to iterate over a result set using foreach . 不可能使用foreach遍历结果集。

foreach only works for cases when you already have the data fetched. foreach仅适用于已经获取数据的情况。

So your friend was just wrong and his advice doesn't make any sense. 因此,您的朋友只是错了,他的建议没有任何意义。

@zerkms @zerkms

I also thought like that.. But following works... 我也是这样想的。

My 'tbl_login' table structure also attached as a 我的“ tbl_login”表结构也附加为

<?php
    include '../common/dbConnection.php';

     class foreachtest{
        function foreachtesting(){
            $sql="SELECT * FROM tbl_login";
            $query_result=$GLOBALS['con']->query($sql);
            return $query_result;
        }
    }

    $myobject = new foreachtest();
    $result=$myobject->foreachtesting();


    foreach ($result as $a){
        echo $a['username'];
    }

?>

tbl_login MYSQL table screenshot tbl_login MYSQL表屏幕截图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM