How do I produce a PHP error if an entry is NOT in the DB?

I’ve had the execute(); statement in my code since the beginning. Anyway, Itried this after examining yours and @phdr’s example. It doesn’t work and says “username not found” even if it does. I’m not sure what I did wrong, unless I misunderstood you.

$db->prepare('SELECT * FROM xf_user WHERE username = ?');
$stmt->bind_param('s', $referral);
$stmt->execute();
if ($stmt->num_rows==0) {
     $user_error2 = "<br><span class='error_msg'>Referring username doesn't exist!</span>";	     
}       
$stmt->close();

Well, you did have the execute command, but, AFTER you tested the results which is not available until AFTER the execute command is processed.

Now, are you using PDO or MySQLi? That is the first thing. You did not show how you set up the $db connection. Next, you can not use the code you just posted exactly. You MUST do a fetch inside the routine. Meaning that you check for number of rows, but, do not check for NO number of rows… Also, you do not fetch any data in your last posted version… So, change it like this:

As you see, this version checks the same way for a row and if so echo’s the username.
If no rows found, it sets up the error message…
It does appear you did not read the posts we both did for you… (It is like you deleted some lines…)

For a prepared query, you MUST use the mysqli stmt store_result() method for the num_rows property to get the value from the database.

I recommend that you switch to use the much simpler and more consistent PDO extension.

1 Like

My bad. I was trying to simplify the code for my needs. I will try your new example. Thanks!

Here’s my DB setup:

$db = mysqli_connect('localhost', 'xf', xxxxxxxxxxx', xxxxxxxx');

I’m lost. Now the HTML loads, but when I try to submit the form, I’m told the page isn’t working. Hence, here is the complete script. I seem unable to debug it. :frowning:

  $db = mysqli_connect('localhost', 'xxxx15', 'xxxxxxxxxxxxD)_', 'xxxxxx015');

  if (isset($_POST['register'])) {	
	$username = $_POST['username'];
	$password = $_POST['password'];
	$password2 = $_POST['password2'];
	$referral = $_POST['referral'];
	$ip = $_POST['ip'];      
      $mail = $_GET['email2'];      

	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
	    $ip = $_SERVER['HTTP_CLIENT_IP'];
	} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
	    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	} else {
	    $ip = $_SERVER['REMOTE_ADDR'];
	}

 	if ($stmt = $db->prepare('SELECT * FROM xf_user WHERE username = ?')) {
	  $stmt->bind_param('s', $username);
        $stmt->execute();
	  $stmt->store_result();
  	  if($stmt->num_rows>0) {
           $user_error = "<br><span class='error_msg'>Username already taken!</span>";	     
        }       
	}
	$stmt->close();		

	if ($stmt = $db->prepare('SELECT * FROM xf_user WHERE username = ?')) {
		$stmt->bind_param('s', $referral);
		$stmt->execute();		
		if ($stmt->num_rows==0) {
			$row = $stmt->fetch_assoc();
		} else {
		     $user_error2 = "<br><span class='error_msg'>Referring username doesn't exist!</span>";	     
		}       
	}	
	$stmt->close();

	if (empty($username)) {
    	  $name_error = "<br><span class='error_msg'>Username cannot be blank!</span>";
	  $who3 = $_GET['user'];
     	}else if(strlen($password) < 8) {
	  $pass_error1 = "<br><span class='error_msg'>Password needs to be at least 8 characters!</span>";
	}else if($password != $password2) {
        $pass_error2 = "<br><span class='error_msg'>Passwords do not match!</span>";
	}else if (empty($referral)) {
	  $refer2 = "<span class='error_msg'><br>Who referred you?</span>";
	}else if (empty($mail)) {
	  $refer = "<span class='error_msg'><br>Where is your e-mail, did you follow the correct link?</span>";
	}else if (empty($user_error2)) {	

	$date = date('m/d/Y');
      
      $headers = "From: xxxx <xxxxxxxxxxxxx.net>";

	$subject = "Access Request";

	$message = "Submitted E-mail: $mail
Choosen Username: $username
Password: $password
IP: $ip	
Referred By: $referral
Date requested: $date\n
Simply reply to this message being sure to quote the above info.  Once received, I'll setup your account!\n
~z";

	mail($mail, $subject, $message, $headers);
	header('location: done.html');
	}  	

 }

You are getting a fatal run time error. If you set php’s error_reporting and display_errors settings as I have posted a number of times in your threads, php will help you find the problem.

Short-answer: you cannot fetch data from a mysqli prepared query the way that you have been shown in this thread. You also must call the store_result() method before num_rows will work. You have it in one place but not the other.

You are also validating the inputs after you have tried to use them. This is nonsense, since the inputs could be empty and the sql queries wouldn’t produce expected results in this case.

1 Like

Zoldos, are you JOKING with us??? LOL

You can NOT do an IF() clause on a PREPARE clause! ! !
Also, you check to see if the $username is empty AFTER you run a query based on it. Your code is all messed up. Lastly, you have no protection from code being placed into your forms. You need to add some code to filter out hacker crap out of the input fields. Here is a version of yours with some changes which should get you started. Not tested, just rewritten off the top of my tired mind…

//  USING MySQLi...

//  Check if form was posted ( Using the preferred way not using ISSET...
if ($_SERVER['REQUEST_METHOD'] == 'POST') {	
	$username = filter_input(INPUT_POST, "username");
	$password = filter_input(INPUT_POST, "password");
	$password2 = filter_input(INPUT_POST, "password2");
	$referral = filter_input(INPUT_POST, "referral");
	$ip = filter_input(INPUT_POST, "ip");
        $mail = filter_input(INPUT_POST, "'email2");

        //  Form is posted, fields are retrieved from form...
        //  This next section is okay but, may not work 100%  (For another post...)
	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
	    $ip = $_SERVER['HTTP_CLIENT_IP'];
	} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
	    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	} else {
	    $ip = $_SERVER['REMOTE_ADDR'];
	}

       //  Validate some of the user's inputs.  You are not checking most of them...  (Should add more!)
      $error_message = "";
       if ( empty($username) OR trim($username)=="") {
    	    $error_message .= "<br>Username cannot be blank!";
       }
       if ( strlen($password) < 8 ) {
	  $error_message .= "<br>Password needs to be at least 8 characters!";
	}
       if ( $password != $password2 ) {
          $error_message .= "<br>Passwords do not match!";
	}
       if ( empty($referral) ) {
	   $error_message .= "<br>Who referred you?";
	}
       if ( empty($mail) ) {
	  $error_message .= "<br>Where is your e-mail, did you follow the correct link?";
        }

       //  If all these validations pass, then run queries to check usernames
       if ( $error_message=="" ) {
            $db->prepare('SELECT * FROM xf_user WHERE username = ?')) {
	    $stmt->bind_param('s', $username);
            $stmt->execute();
	    $number_of_rows = $stmt->num_rows;   // here if will fetch the count
            if ( $number_of_rows > 0 ) {
                 $error_message .= "<br>Username already taken!";	     
            }
	    $stmt->close();		

	    $stmt = $db->prepare('SELECT * FROM xf_user WHERE username = ?')) {
	    $stmt->bind_param('s', $referral);
	    $stmt->execute();		
	    $number_of_rows = $stmt->num_rows;   // here if will fetch the count
            if( $number_of_rows!=0)  {
	        $error_message .= "<br>Referring username doesn't exist!";	     
	     }
	    $stmt->close();

            //  All validation is complete, check results.  If errors, display them, if not send email...
           if ( $error_message!="" ) {
              //  Display error(s)  NOTE:  error message will show ALL errors, not just the last one!
              echo "<br><span class='error_msg'>" . $error_message . "</span><br>";
           } else {
              //  All okay, send the email...	
              $date = date('m/d/Y');
              $headers = "From: xxxx <xxxxxxxxxxxxx.net>";
              $subject = "Access Request";
              $message = "Submitted E-mail: $mail
Chosen Username: $username
Password: $password
IP: $ip	
Referred By: $referral
Date requested: $date\n
Simply reply to this message being sure to quote the above info.  Once received, I'll setup your account!\n
~z";

	    mail($mail, $subject, $message, $headers);
	    header('location: done.html');
	}
     }
}

This example is TOTALLY not tested. I just rewrote your logic and added a little of my own into it for you. The version will “concatenate” the error messages and place them when displayed into one error list. This means, if you leave out the email address or miss-match the passwords,etc, it will show you ALL of the errors, not just the last one. You can test that buy submitting the form with nothing entered into it.
It also is more in order better than your previous tries. Hope this helps! Good luck!

EDIT: Not sure if your email section where you create the message will work as-is. You might need to redo that section so it is better formatted.

1 Like

hehe My code seemed to work (before this latest change). :smile: But anyway, I’m putting it on the shelf for good this time. I clearly have not grasped PHP like I thought I was. :frowning:

Well, okay with me, but, I think you are close to finishing up that quest. The code I gave you should work for you. You might just want to test the email part further. But either way, see you in your next post…

1 Like

Nothing is actually being inserted into the DB. I’m only checking to see if the selected username already exists, and return an error if it does. Everything seems to work as is (before this last request), so I’m going to go ahead and keep the original code. This last change has proved more difficult than I realized.

Thank you so much for your help and to everyone else!! :smiley:

Well, working with bad code will just make your application worst in the future, but, okay.
When you run into another problem, just post a new thread… Good luck

1 Like

I’m going to just keep it as is since it works for my purposes. Thanks!! :smiley:

Sponsor our Newsletter | Privacy Policy | Terms of Service