简体   繁体   中英

How to check if a specific value exists in table column

I have 2 tables in a database and they have a foreign key relation thru the column called id. So I have the id (representing a user and is the primary key in the user table) from one table and want to check weather that user has existing data in the other table.

So I wish to run the id against the column called id in the other table and if the id exists in that column return value true. I´m not getting any error at the moment but the method does not return any value. So I must be doing something wrong... Any help appreciated!

This is the class and method I have in one file:

class test {

    public function dataExists ()
        {
            $db = Database::getInstance();
            $classUser = new user();
            $userId = $classUser->getUserData($_SESSION['id']);
            $user = $userId['id'];

            $query = $db->prepare("`id` SELECT * FROM `data`");

            if ($user == $query)
            {
                return true;
            } else {
                return false;
            }
        }
}

And the in my view file I have this:

$classTest = new test();
$exists = $classTest->dataExists();

if ($exists == true) {

echo '';

}

Currently you are checking if a mysqli_stmt object (returned from prepare() ) equals a number. How do you think this comparison should work?

You can do this via num_rows , this is taken pretty straight forward from the manual

public function dataExists () {
    //...
    if ($statement = $db->prepare("SELECT * FROM `data` WHERE `id`=?")) {
        $statement->bind_param("i", $user);
        $statement->execute();
        //...
        return ($statement->num_rows > 0);
    }
}

Since you are working with classes, you might want to store the results of the query somewhere - asking for their existence implies that you might want to use them.

I shortened the return statement as

if ($a==$b) {
    return true;
} else {
    return false;
}

is equal to

return ($a==$b);

Why not just use the query statement

SELECT count(*) FROM `data` where `id` = ?

and then just test for the value returned.

This has the benefit of only returning the number of records that match your query rather than matching and returning all the records that do. While that may be okay for a small number of records if your second table has 50,000 records that match you probably don't want to pull all of them just to find out that there are 50,000 of them!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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