Andor Nagy
Andor Nagy

Reputation: 174

Mysql PHP Query Runs Perfectly, But returns as false

I have some mysql_query()s that work just fine, but if I put them in an if else statement they return false. Any idea?

        public function delete_post() {

        $id = $_GET['post_id'];

        mysql_query("DELETE FROM posts WHERE post_id='$id' LIMIT 1");

        if ( !mysql_query() ) {
            echo ('Could not be Deleted');
        } else { 
            echo 'Deleted Successfully'; 
        }
    }

and when i run it, it deletes the post, but returns "Could not be deleted"

Upvotes: 1

Views: 496

Answers (4)

Jean
Jean

Reputation: 7673

Note: mysql_query() is deprecated. You really should use PDO::query instead.

If you still wish to use it, do:

$result = mysql_query("DELETE FROM posts WHERE post_id='$id' LIMIT 1");
if (!$result) 
{
    echo ('Could not be Deleted');
}

Explanation:

In you original code you call mysql_query() two times. The second time, there is no argument, so it doesn't work, and that's what your code is reporting.

Upvotes: 2

anotherBob
anotherBob

Reputation: 33

I think this is a pretty similar question / answer: What does a successful MySQL DELETE return? How to check if DELETE was successful?

Can you try what it suggests and see if that will work for you?

Upvotes: 1

RelevantUsername
RelevantUsername

Reputation: 1340

You could try :

public function delete_post() {

        $id = $_GET['post_id'];

        $query = mysql_query("DELETE FROM posts WHERE post_id='$id' LIMIT 1");

        if ( !$query ) {
            echo ('Could not be Deleted');
        } else { 
            echo 'Deleted Successfully'; 
        }
    }

Upvotes: 0

mbarlocker
mbarlocker

Reputation: 1386

You're running a query with an empty SQL statement, which is not correct SQL. Try this.

$result = mysql_query("DELETE ...");
if (!$result) {
    echo ('Could not be Deleted');
} else {
    echo 'Deleted Successfully';
}

The difference is on line 2 (of my code).

Upvotes: 3

Related Questions