0

I want to use php mysqli function, to query this:

SET @rownum = 0, @rank = 1, @prev_val = NULL;
SELECT @rownum := @rownum + 1 AS row,
    @rank := IF(@prev_val!=score,@rownum,@rank) AS rank,
    userid,
    @prev_val := score AS score
FROM (
    SELECT userid, sum(amount) as score 
    from leads WHERE date(time) >= '2013-08-15'
    group by userid
) exodus_entries 
 ORDER BY rank asc LIMIT 0,100;

I tried using the mysqli_query(link, query); function, but no luck, any help?

4
  • Try using mysqli::multi_query instead because your query is actually multiple statements Commented Sep 18, 2013 at 19:07
  • I am trying this: $query = mysqli_multi_query($cxn,$sqll); $result = mysqli_store_result($cxn); while ($row = mysqli_fetch_row($result)) { echo $row[1] . "<br>"; } But mysqli_fetch_row returns error. Commented Sep 18, 2013 at 19:17
  • mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given Commented Sep 18, 2013 at 19:22
  • in that case, show your (php) code. And you can already try changing mysqli_multi_query(.....); into mysqli_multi_query(.....) or die (mysqli_error());. This should tell you if you have any mysql errors that would otherwise be silently ignored. Commented Sep 18, 2013 at 20:06

1 Answer 1

3

There is no need to use multi-query, and you risk security problems whenever you use multi-query.

The values for you user variables @rownum, @rank, @prev_val will remain in effect for the second query, as long as you run both query in the same connection.

So just run mysqli_query("SET ..."); and then run mysqli_query("SELECT..."); separately. It's much simpler to do this, and avoids at least one security risk.

Regarding your error:

mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given 

Always check the return value of mysqli_query(). It will return false if there's an error. And of course you can't run mysqli_fetch_row(false);

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome. This is documented almost nowhere on any APIs or forums. I don't know if this is an "obvious" solution, but I've been searching for over 2 days for this solution.
@Michael, read the first paragraph of this manual page: dev.mysql.com/doc/refman/5.6/en/user-variables.html It doesn't literally say that setting a user-variable lasts for the rest of the session, but that's what happens, and it's sure easy to test if you are in doubt.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.