简体   繁体   English

PHP & MySQL:如何使用“SET @rank=0;” 在 $查询=

[英]PHP & MySQL: How can I use "SET @rank=0;" in $query=

In my PHP file, I use this line to pull data from my mySQL database:在我的 PHP 文件中,我使用此行从我的 mySQL 数据库中提取数据:

$query = "SET @rank=0; SELECT @rank:=@rank +1 as rank, Blah Blah...";

If I check the SELECT statement in phpMyAdmin's SQL window (without $query= ) it works fine.如果我在 phpMyAdmin 的 SQL window(没有 $query= )中检查 SELECT 语句,它工作正常。

But, if I use it in PHP, then I get an error.但是,如果我在 PHP 中使用它,则会出现错误。 It doesn't like the "SET @rank=0;"它不喜欢“SET @rank=0;” bit.少量。 Is there a way to use "SET @rank=0;"有没有办法使用“SET @rank=0;” when it's in "$query="?当它在“$query=”中时? Is there a workaround?有解决方法吗?

The rest of the code is standard stuff for pulling data from a db:代码的 rest 是从数据库中提取数据的标准内容:

public function getmyData() {


 $mysql = mysql_connect(connection stuff);

 $query = "SELECT @rank:=@rank +1 as rank, formatted_school_name,  blah blah";

 $result = mysql_query($query);

            $ret = array();
                 while ($row = mysql_fetch_object($result)) {
                    $tmp = new VOmyData1();
                    $tmp->stuff1 = $row-> stuff1;
                    $tmp->stuff2 = $row->stuff2;

                    $ret[] = $tmp; 
                        }
                 mysql_free_result($result);

                 return $ret;

    }   

Update: I'm trying to use Amerb's suggestion of using multi-query.更新:我正在尝试使用 Amerb 关于使用多查询的建议。 I concatenated the query like so:我像这样连接查询:

$query = "SET @rank = 0";

$query .= "SELECT @rank:=@rank +1 as rank...

I changed the result to:我将结果更改为:

$result = $mysqli_multi_query($query);

But, it's failing for some reason.但是,由于某种原因它失败了。 I'm on a machine running PHP 5.2.我在运行 PHP 5.2 的机器上。 Any suggestions?有什么建议么?

This guy here seems to have a way of setting the variable in the same query to zero. 这个人似乎有办法将同一个查询中的变量设置为零。 I don't have MySQL set on up on this machine to try it, though. 不过,我没有在这台机器上设置MySQL来尝试它。

Here's the query he suggests in his blog post: 以下是他在博客文章中建议的查询:

select @rownum:=@rownum+1 ‘rank’, p.* from player p, (SELECT @rownum:=0) r order by score desc limit 10;

(Is there some homework assignment coming due somewhere having to do with computing ranks? This is the third question I've seen on this in two days.) (是否有一些与计算等级有关的家庭作业?这是我在两天内看到的第三个问题。)

Are you checking for duplicate scores? 你在检查重复的分数吗?

You have to enable the use of multiple queries in one, but i forgot how do do this at the moment. 您必须在一个中启用多个查询,但我忘记了目前是如何做到这一点的。 It's a security feature. 这是一个安全功能。

尝试将其作为2个单独的连续查询执行。

Use mysql_multi_query() or rather mysqli_multi_query() instead of mysql_query()使用 mysql_multi_query() 或 mysqli_multi_query() 而不是 mysql_query()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM