HerrimanCoder
HerrimanCoder

Reputation: 7228

PHP - function for mysql_fetch_assoc

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"]);
}

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();
}

}

This function works great in 2 out of 3 scenarios:

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

$rs = ExecuteQuery($sql);

$foo = $rs["UserID"];

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

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"]);
}

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.

Upvotes: 1

Views: 2505

Answers (3)

Teena Thomas
Teena Thomas

Reputation: 5239

try foreach($rs as $row){ instead of while ($row = $rs){

Upvotes: 1

bobwienholt
bobwienholt

Reputation: 17610

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;

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

Upvotes: 0

Zathrus Writer
Zathrus Writer

Reputation: 4331

Don't use while, use foreach:

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

Upvotes: 0

Related Questions