Mujtaba Ali Mujtaba Ali - 7 months ago 11
SQL Question

Check value in MySQL from PHP

Hi guys,

I am fairly new to PHP, what i want is not much,

i just want to place a check on my page which goes to database and check for value 1 or 0, 1=enable so page continues and 0=disable page dies.

someone suggested but didn't work

$sql = mysql_query("SELECT * FROM members WHERE access= '1'");
$user = mysql_query($sql);
echo $user;
if ($user !=="1") {
echo "You are not the proper user type to view this page";
die();
}


Thank you so much for your time.

Answer

Firstly, you're using mysql_query() twice and that alone will cause a syntax error.

You're also not looping over results, so use the following to achieve what you want to do.

$sql = "SELECT * FROM members WHERE access= '1'"; 
$user = mysql_query($sql) or die(mysql_error()); 

    while($row = mysql_fetch_array($user)){

        if ($row['access'] !=="1") { 
            echo "You are not the proper user type to view this page"; 
            die(); 
        }
        else {
                echo "You are the right type.";
            }

}

If your query requires a db connection to the query, you will need to do:

$user = mysql_query($sql, $connection); 

This assuming a mysql_ successful connection. However, that API is deprecated as of PHP 5.5 and deleted as of PHP 7.0 and note that different MySQL APIs do not intermix.

It's time to step into the 21st century and use either the MySQLi_ or PDO API.

You may also have to select an actual row (or rows) instead of SELECT * FROM members

I.e.:

SELECT column_1, column_2 FROM members

Consult these following links http://php.net/manual/en/function.mysql-error.php and http://php.net/manual/en/function.error-reporting.php and apply that to your code.


You can also achieve this with mysql_num_rows():

$result = mysql_query("SELECT * FROM members WHERE access= '1'");
$num_rows = mysql_num_rows($result);

if ($num_rows > 0) {
  // do something
}
else {
  // do something else
}

You might also want to add to the WHERE clause:

$result = mysql_query("SELECT * FROM members WHERE access= '1' AND column='x' ");