mysql_query在sql语法中说错误,但同样的查询在mysql客户端中工作正常

When I try to send the following query:

SET @attempts=0; 
SELECT mt1.TimeStamp, mt1.ReadAttempts - @attempts AS delta, 
       @attempts := mt1.ReadAttempts ReadAttempts 
FROM OneWireStats mt1 
WHERE SensorIndex=1 ORDER BY mt1.TimeStamp;

to fetch delta values between rows in table OneWireStats I receive following error:

Query failed with error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT mt1.TimeStamp, mt1.ReadAttempts - @attempts AS delta, @attempts := mt1.Re' at line 1 Query = SET @attempts=0; SELECT mt1.TimeStamp, mt1.ReadAttempts - @attempts AS delta, @attempts := mt1.ReadAttempts ReadAttempts FROM OneWireStats mt1 WHERE SensorIndex=1 ORDER BY mt1.TimeStamp;, Query no: 0

When I paste the query from the error printout above into mysql client it works fine.

mysql>  SET @attempts=0; SELECT mt1.TimeStamp, mt1.ReadAttempts - @attempts AS delta, @attempts := mt1.ReadAttempts ReadAttempts FROM OneWireStats mt1 WHERE SensorIndex=1 ORDER BY mt1.TimeStamp LIMIT 10; Query OK, 0 rows affected (0.01 sec)

+---------------------+-------+--------------+ 
| TimeStamp           | delta | ReadAttempts |
+---------------------+-------+--------------+ 
| 2013-12-23 07:55:01 |  5532 |         5532 | 
| 2013-12-23 08:00:00 |   302 |         5834 | 
| 2013-12-23 08:05:01 |   302 |         6136 | 
| 2013-12-23 08:10:00 |   302 |         6438 | 
| 2013-12-23 08:15:00 |   302 |         6740 | 
| 2013-12-23 08:20:01 |   302 |         7042 | 
| 2013-12-23 08:25:00 |   302 |         7344 | 
| 2013-12-23 08:30:01 |   302 |         7646 | 
| 2013-12-23 08:35:00 |   302 |         7948 | 
| 2013-12-23 08:40:01 |   302 |         8250 |
+---------------------+-------+--------------+ 
10 rows in set (0.07 sec)

I use the following php code:

$query = mysql_real_escape_string(trim($queryobj[$counter]));

$sqlresult = mysql_query($query) or die("Query failed with error: ".mysql_error() . 
             " Query = " . $query . ", Query no: " . $counter);

I do not use any single or double quotes in my query so I do not yet understand the error printout.

Greatful for hints.

You need to run each query separately, may be like

mysql_query( "SET @attempts=0" );
mysql_query( "SELECT mt1.TimeStamp, mt1.ReadAttempts - @attempts AS delta, @attempts := mt1.ReadAttempts ReadAttempts FROM OneWireStats mt1 WHERE SensorIndex=1 ORDER BY mt1.TimeStamp" );

OR use mysqli's multi_query(), like:

$query  = "SET @attempts=0;";
$query .= "SELECT mt1.TimeStamp, mt1.ReadAttempts - @attempts AS delta, @attempts := mt1.ReadAttempts ReadAttempts FROM OneWireStats mt1 WHERE SensorIndex=1 ORDER BY mt1.TimeStamp";
mysqli_multi_query($connection, $query);
mysqli_next_result($connection);
if ($result = mysqli_store_result($connection)) {
  //while loop here
}