PHP_Newbie
PHP_Newbie

Reputation: 1

My SQL Select Query and IF statement will not return any results

I'm hoping someone could help me.

I am completely new to PHP and I am finding that my SELECT query and/or IF statement are not retrieving any result from my database.

The aim of this code is to retrieve a css skin from the database that can be applied to every page of my website.

Here is the code:

$dbc - mysqli_connect($servername, $username, $password, $databasename) or die ('Error connecting to MYSQL server');

$skin = $_POST['skin'];

$query = "SELECT skin FROM skins WHERE id = '".$_SESSION['userid']."'";

$result = mysqli_query($dbc, $query) or die ('Error quering database');

if ($result) {     
    if ($skin=='blue') {     
        echo "<link rel='stylesheet' type='text/css' href='blue.css' />";
    }    
    else if ($skin == "pink1") {                
        echo "<link rel='stylesheet' type='text/css' href='pink1.css'  />";             
    }
    else {     
        echo 'You do not have a skin preference';
    }    
}

When the code runs, it comes back echoing You do not have a skin preference.

My thinking is that it has not connected to the database/table correctly; so, it is not retrieving any result.

I know for a fact that it should pick up $skin=='blue' from the database.

Any help or suggestion would be much appreciated.

Thanks.

Upvotes: 0

Views: 217

Answers (1)

Marc B
Marc B

Reputation: 360702

mysqli_query() will only return false in case of an error, which would then trigger your or die() clause.

A query which returns no data is NOT an error. It's still a valid result set, which just happens to be empty. You need to check mysqli_num_rows() to see if 0 or non-zero rows were returned instead.

eg.

if (mysqli_num_rows($result) == 0) {
   ... there is no preference set
} else {
   ... there's at least one skin preference
}

Upvotes: 1

Related Questions