PHP MYSQL SET gives error in while loop

2019-07-28 04:33发布

问题:

I have this query:

$result2 = mysql_query("SET @total=0;
SELECT *,
@total:= @total+ `companyearned` AS `total`
FROM `recordedhours` WHERE `group` = '$uid'
ORDER BY `unixdate` DESC, `idnum` DESC
LIMIT $from, $max_results");

while ($rowb = mysql_fetch_array($result2)) {
//DO STUFF
}

But the SET @total=0; makes the while line give me an error: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in The query works fine in phpmyadmin and the while works fine without the SET @total=0;

回答1:

As you can not use more than one queries in mysql_query(), But you can combine both your query into a single one.

Try this query..

SELECT *,
@total:= @total+ `companyearned` AS `total`
FROM `recordedhours`, (SELECT @total:=0) r WHERE `group` = '$uid'
ORDER BY `unixdate` DESC, `idnum` DESC
LIMIT $from, $max_results


回答2:

Use two calls to mysql_query():

mysql_query("SET @total=0");

$result2 = mysql_query("SELECT *,
@total:= @total+ `companyearned` AS `total`
FROM `recordedhours` WHERE `group` = '$uid'
ORDER BY `unixdate` DESC, `idnum` DESC
LIMIT $from, $max_results");

I think the variable should persist since it's the same database connection.