PHP - mysql_fetch_assoc 函数 [英] PHP - function for mysql_fetch_assoc

查看:58
本文介绍了PHP - mysql_fetch_assoc 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在 PHP 中执行此操作,它可以正常工作并按预期循环:

If I do this in PHP, it works fine and loops as expected:

$rs = mysql_query($sql);
while ($row = mysql_fetch_assoc($rs)){
    writeme("UserID: " . $row["UserID"]);
}

但我一直想把它抽象成一个我称之为 ExecuteQuery 的函数:

But I keep wanting to abstract this out into a function I have called ExecuteQuery:

function ExecuteQuery($sql){
$result = mysql_query($sql);

if ($result) {
    if($result != 1){
        return mysql_fetch_assoc($result); // return recordset
    }
}else{
    $message  = 'Invalid query: ' . mysql_error() . "<br>";
    $message .= 'Whole query: ' . $sql;
    echo $message;
    die();
}

}

此功能在 3 种情况中的 2 种情况下效果很好:

This function works great in 2 out of 3 scenarios:

1- 非常适合返回 1 行的查询,我可以这样访问:

1- Works great for a query that returns 1 row, and I can access like this:

$rs = ExecuteQuery($sql);

$rs = ExecuteQuery($sql);

$foo = $rs["UserID"];

$foo = $rs["UserID"];

2- 适用于不返回任何记录的 sql 语句,例如 UPDATE 或 DELETE.

2- Works great for a sql statement that returns no records, like an UPDATE or DELETE.

3- 但是当我尝试取回返回多条记录的记录集,然后循环遍历它时,我得到了一个无限循环,我的浏览器崩溃了.像这样:

3- But when I try to get back a recordset that returns multiple records, and then loop through it, I get an infinite loop and my browser crashes. Like this:

$rs = ExecuteQuery($sql);
while ($row = $rs){
    writeme("UserID: " . $row["UserID"]);
}

如何修改我的 while 循环,使其前进到记录集中的每条新记录并在最后一条记录后停止?我敢肯定这是一件愚蠢的小事,但我还不是 PHP 专家.我真的很希望我的 ExecuteQuery 函数能够处理所有 3 种情况,它非常方便.

How can I modify my while loop so it advances to each new record in the recordset and stops after the last record? I'm sure it's a dumb little thing, but I'm not expert with PHP yet. I'd really like my ExecuteQuery function to be able to handle all 3 scenarios, it's very handy.

推荐答案

mysql_fetch_assoc() 只返回结果的一行.要获取下一行,您需要再次调用 mysql_fetch_assoc().您可以做的一件事是让您的 ExecuteQuery 函数返回一个数组数组:

mysql_fetch_assoc() only returns one row of the result. To get the next row, you need to call mysql_fetch_assoc() again. One thing you could do is have your ExecuteQuery function return an array of arrays:

$rows = array();
while ($row = mysql_fetch_assoc($result) !== false) {
   $rows[] = $row;
}
return $rows;

此外,您不应使用 mysql_* 函数,因为它们已被弃用.尝试改用 PDO 或 mysqli_*.

Also, you should not use the mysql_* functions as they are deprecated. Try using PDO or mysqli_* instead.

这篇关于PHP - mysql_fetch_assoc 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆