dovlapsy dovlapsy - 9 months ago 32
MySQL Question

MySQLi second query not working

I have a problem with MySQLi and PHP while trying to use query twice inside one php page. The problem is that first query works perfect but second don't work. First query set the session, but second don't. Here is my code (I also have connect to db file, form and other files)..

$connection = new mysqli($server,$username,$password,$database);

$username = $_POST['username'];
$email = $_POST['email'];

if($select1 = $connection->query("SELECT * FROM users WHERE username = '$username'")) {
$counter1 = $select1->num_rows;
if($counter1 != 0) {
$_SESSION["accesserror"] = "Error: <em>That username is already used by other member.</em>";
else if($select2 = $connection->query("SELECT * FROM users WHERE user_email = '$email'")) {
$counter2 = $select2->num_rows;
if($counter2 != 0) {
$_SESSION["accesserror"] = "Eror: <em>That E-Mail is already used by other member.</em>";


Replace the else if

else if($select2 = $connection->query("SELECT * ...

With an if

if($select2 = $connection->query("SELECT * ...

The problem with your code is that execution can never enter the else if so long as the first query was run successfully (even if the 1st query returns no result, it is still run successfully). In order to always check both conditions, you need to separate those two in separate if blocks

PS: It would be even more efficient to run one query, and you should never insert user supplied values such as $username directly in your queries; this is to avoid SQL injection. Your code is very vulnerable. Here is a safer, more efficient version:

$username = mysqli_escape_string($_POST['username']);
$email = mysqli_escape_string($_POST['email']);
$sql = "SELECT * FROM users WHERE username='$username' OR email='$email'";
if($select = $connection->query($sql) && $select->num_rows) {
    $_SESSION["accesserror"] = 
        "Error: <em>That username or email is taken.</em>";
    //Todo: handle server error. probably a badly formed query
    // error details in $connection->error
    // OK to register new username and email