-2

I have a query that works in phpMyAdmin but not when being run through php

This is the query:

DELETE FROM 'table' WHERE 'id' NOT IN ( SELECT DISTINCT id FROM ( SELECT * FROM 'table' ORDER BY scoreDESC LIMIT 10 ) foo)

Basically, it sorts the table to score descending and then keeps the top 10 and deletes the rest. I can run this fine trough phpmyadmin but my php code says no

This is the php script:

function add_highscore()
{

    mysql_query("DELETE FROM highscores WHERE id NOT IN ( SELECT DISTINCT id FROM ( SELECT * FROM highscores ORDER BY score DESC LIMIT 10 ) foo)")
    or die('0');

    echo "1";

    mysql_close($table_id);
}

There is no problems with the connection, I have more functions in the script that works.

Any ideas? Help is greatly appreciated!

Cheers, Jon

4 Answers4

0

May be function is not being called or connection not established.You should try mysql_error for catching error or use try catch to catch error

Bhaskar Bhatt
  • 1,265
  • 12
  • 19
  • Sory, the php-code isn't correct up in my post. It should say "mysql_query" not "mysqli_multi_query". The mysqli was one of my tries to get it working. – Jon Nyström Feb 08 '13 at 20:32
0

Try this:

<?PHP
function add_highscore()
{
    $link = mysqli_connect($host, $user, $password, $database);
    $query = "DELETE FROM highscores WHERE id NOT IN ( SELECT DISTINCT (id) FROM ( SELECT * FROM highscores ORDER BY score DESC LIMIT 10 ) foo)";
    mysqli_query($link, $query)    or die('0');

    echo "1";

    mysqli_close($table_id);
}
?>

The MYSQL version

<?PHP
function add_highscore()
{

    $link = mysql_connect($server, $username, $password);
    mysql_select_db($database_name, $link);

    $query = "DELETE FROM highscores WHERE id NOT IN ( SELECT DISTINCT(id) FROM ( SELECT * FROM highscores ORDER BY score DESC LIMIT 10 ) foo)";
    return mysql_query($query)   or die('0');

    echo "1";

    mysql_close($link);
}

?>
Mr. Radical
  • 1,833
  • 1
  • 17
  • 27
0

I recommend you to use an ORM library, it's more easy to work with queries and it's more safety

For example: RedBean

or Search on this site

Community
  • 1
  • 1
ursuleacv
  • 1,011
  • 12
  • 16
0

Add this to the top of your script:

error_reporting(E_ALL);

And replace:

die('0');

with:

die(mysql_error());

and that should help indicate just what variety of 'not working' the script is.

Sammitch
  • 25,490
  • 6
  • 42
  • 70
  • Thank you!!! Oh god i've been wtrying to fix this one for a long time. With error reporting (dont know how I could not priorities that) it became very clear that my mysql user didnt have permission to do delete. :) Thanks again! – Jon Nyström Feb 08 '13 at 20:54
  • 1
    @JonNyström is you question solved by sammitch answer? Please accept it then. – Mr. Radical Feb 08 '13 at 20:57