0

This is my code, the first function. fun.php

function post_exists($post_id){
    global $con;
    $post_id = (int)$post_id;
    return (mysqli_fetch_array(mysqli_query($con, "SELECT COUNT(post_id) FROM home_post WHERE  post_id='$post_id'"), MYSQLI_NUM) != 0) ? true : false;
}

This is the function call in index.php

if(post_exists(23) === true){
    echo "<script>alert('working oo')</script>";
}

function usually return true when the argument is false. what i want is, if the argument is true(which means if the data exist in my database)return true if is false return false .

1 Answer 1

1

What you are doing is checking if the array is not equal to 0 - not the actual result inside the array. Change the true/false ternary to this:

return (mysqli_fetch_array(mysqli_query($con, "SELECT COUNT(post_id) FROM home_post WHERE post_id='$post_id'"), MYSQLI_NUM)[0] != 0) ? true : false;

as you can see, we check the first value in the array (using the [0] key after the array is assigned). This kind of syntax, however, is only available in newer versions of PHP, but should be useable in 5.1 and up.

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

Comments

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.