php - 如何在php中使用sql变量传递sql查询

标签 php mysql

我想在 php 中传递以下 sql 查询

SET @rank=0; SELECT @rank:=@rank+1 AS rank, `percentage_obtained`  FROM `result`  ORDER BY percentage_obtained DESC

如这里

mysql_query('SET @rank=0; SELECT @rank:=@rank+1 AS rank, `percentage_obtained`  FROM `result`  ORDER BY percentage_obtained DESC') or die(mysql_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 @rank:=@rank+1 AS rank, percentage_obtained FROM result ' at line 1

但是,当我直接在数据库内运行查询时,它会起作用。请帮忙。

最佳答案

mysql_query()不支持多个查询,因此需要将它们分开。 您也可以使用 mysqli_multi_query - 但请注意,您需要 mysqli 而不是 mysql

所以

mysql_query('SET @rank=0') or die(mysql_error());
mysql_query('SELECT @rank:=@rank+1 AS rank, `percentage_obtained`  FROM `result`  ORDER BY percentage_obtained DESC') or die(mysql_error());

应该处理这个问题

关于php - 如何在php中使用sql变量传递sql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42600938/

相关文章:

c# - 找不到 sendNotifications 选项 Google Calendar api v3 .NET

php - 使用 PHP 的 SAML 2.0 身份验证

MySQL 默认值错误与 ON DUPLICATE KEY UPDATE with sql mode ON

php - 基于对象的父=>子关系构建访问矩阵?

php - 为 Mac 安装 ext-zip

php - 在没有类依赖的自定义类/子系统中使用 Laravel 4 模型

php - 将下拉列表中的多个选择放入sql查询中

PHP如何将代码页950转换为utf8

mysql - 即使使用 Alias,MySQL 中的列也不明确

php - 设置多个类来表示真实世界的对象