Ok, I have Googled this problem as well as looked at previous entries here on phpbuilder....

I'm going through the tutorial below, around the 2 minute mark, he talks about about adding query line:

http://www.youtube.com/watch?v=Til3oVNlho4&list=ECE134D877783367C7&index=7

..which is the line I'm getting the error on...

function user_exists($username) {
	$username = sanitize($username);
	//$query  = mysql_query("SELECT * FROM `users` WHERE user_id = "adrian"");
	// $query  = mysql_query("SELECT COUNT(`user_id`) * FROM users WHERE `username` = '$username'");
	// return (mysql_result($query, 0) == 1) ? true : false;
	return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'"), 0) == 1) ? true : false;
}

I know, I know - I'm using the outdated mysql function instead of mysqli ...but I'm a beginner and I want want to follow the tutorial and get it working before I make a around and update the code...

Is there a better way to write this with error handling built in? I've read about this elsewhere...

and....is there a text editor that supports the new mysqli functions? whenever I change it from mysql to mysqli in Notepad++, its greys out from being blue...

Thanks,

A

    It means the query is failing for some reason, so the mysql_query() call is returning Boolean false instead of a query result resource.

    I prefer to not chain the functions together like that, but instead assign the result of mysql_query() to a variable, which you can then test to see if it's false, and if so output/log debug info, etc. If it passes, then you pass that new variable to the mysql_result() function.

      Thanks for the reply...

      When I take out the line....

      return (mysql_result($query, 0) == 1) ? true : false;

      , and hit the Submit button on the form, I get a blank page.

      The code then looks like this:

      function user_exists($username) {
      	$username = sanitize($username);
      	$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'"); 
      	//return (mysql_result($query, 0) == 1) ? true : false;

      I went back to the code that is in the login.php (the above code is in file called general.php) , which looks like this - I added the "doesn't exist" inside the die brackets.

      It looks like:

      if (user_exists('adrian') === true) {
      	echo 'exists';
      }
      die("doesn't exist");

      ...and it of course returns "doesn't exist" because it can't read from the return line I commented out....when I hit the Submit button...

      So I tried something else....put in mysql_num_rows function...to tell me if it is returning any rows...so how can I call a function just to see if its returning the stuff in it...if it has a query inside? ...and bypass or remove the echo from the code above...?

      function user_exists($username) {
      	$username = sanitize($username);
      	$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'"); 
      	$num_rows = mysql_num_rows($query);
      	echo "$num_rows Rows\n";

      It seems like the return line is causing the issue with the error I am getting...

        php_adrian;11024035 wrote:

        I know, I know - I'm using the outdated mysql function instead of mysqli ...but I'm a beginner and I want want to follow the tutorial and get it working before I make a around and update the code...

        You're making it harder on yourself. Why learn something the wrong way to start with and plan on un-learning it later?

        You're also picking up other bad habits (as NogDog pointed out, nesting functions inside each other, effectively blocking any sort of error handling) by deciding to blindly "follow the tutorial."

        php_adrian wrote:

        and....is there a text editor that supports the new mysqli functions? whenever I change it from mysql to mysqli in Notepad++, its greys out from being blue...

        I would suspect that notepad++ (or, at least, your installed version) simply doesn't have an up-to-date function list. It doesn't really "support" or "not support" it.

        If you want to try something else, Komodo is a fantastic editor.

        php_adrian wrote:

        ...so how can I call a function just to see if its returning the stuff in it...if it has a query inside? ...and bypass or remove the echo from the code above...?

        [man]return[/man] a value from your function, like you did in your original post.

        If you only want to know if a username exists, you might use a query like so:

        "SELECT 1 FROM `users` WHERE `username`='$username'"

        ...and then, return TRUE or FALSE based on whether there were any rows returned.

          Another approach is to simply(?) ensure there is a unique index on that DB table for the user_id field. Then instead of doing a separate query to see if it exists, just go ahead and do your insert. If the result of that mysql_query() is false and its mysql_errno() is 1022, then you could branch at that point to outputting the "already used" message and ask them to try another. Not only does this avoid having to do 2 separate queries all the time, but it avoids a possible race condition when two users request the same ID at virtually the same time, and both pass the is-it-available test before the first request then does its insert.

            NogDog;11024049 wrote:

            Another approach is to simply(?) ensure there is a unique index on that DB table for the user_id field. Then instead of doing a separate query to see if it exists, just go ahead and do your insert. If the result of that mysql_query() is false and its mysql_errno() is 1022, then you could branch at that point to outputting the "already used" message and ask them to try another. Not only does this avoid having to do 2 separate queries all the time, but it avoids a possible race condition when two users request the same ID at virtually the same time, and both pass the is-it-available test before the first request then does its insert.

            absolutely - this is a good idea even if you still intend to check availability before your insert, since it eliminates the possible race condition.

              thanks a lot guys. I'm going to come back to this in a few days - I'll rewrite it in mysqli....and try and figure it out myself. I have a few question in the mean time:

              1. I'm worried that it may not be able to read/connect to the database? Should place my database $connect variable in there first somewhere to do a check to make sure it can connect?

              2. When we call the function user_exists - there is nothing in there for $username variable to store - so then how can the SQL query out $username if nothing is put inputted into that variable? All we're checking for is 'adrian'....does that make sense? ...when we are outputting $username...??

              3. I hope this makes sense....I have a folder with all my php scripts in it - so if I declare a variable - $car - for example - and then in another script, I declare another variable and name it $car - what happens? does one get overwritten?

              4. I'm wondering about my #2 question above - how does php know to locate a function in a file that's called in another? do they all have to be in the same folder in your www directory? what If I call a function when its located located in another folder? will it be able to locate it and execute it?

              Thanks,

              Adrian

                php_adrian;11024055 wrote:

                thanks a lot guys. I'm going to come back to this in a few days - I'll rewrite it in mysqli....and try and figure it out myself. I have a few question in the mean time:

                1. I'm worried that it may not be able to read/connect to the database? Should place my database $connect variable in there first somewhere to do a check to make sure it can connect?

                With MySQLi, if you use the procedural functions (versus the object-oriented approach), you will need to pass the connection variable as an argument into any function that needs to use it (including the mysqli_*() functions), e.g.:

                function user_exists($username, $dbConnx) { ... }
                
                // code that calls it:
                $exists = user_exists($_POST['user_name'], $dbConnx);
                

                2. When we call the function user_exists - there is nothing in there for $username variable to store - so then how can the SQL query out $username if nothing is put inputted into that variable? All we're checking for is 'adrian'....does that make sense? ...when we are outputting $username...??

                The variables in the function declaration ($username and $dbConnx in my preceding example) are available locally within that function, and have the value of whatever you called the function with in those same positions (in most cases right now for you, they are copies of what you pass in, but when you get into passing objects around they'll likely be references to them...but that's for later).

                3. I hope this makes sense....I have a folder with all my php scripts in it - so if I declare a variable - $car - for example - and then in another script, I declare another variable and name it $car - what happens? does one get overwritten?

                Yes, it will get overwritten by the last reference to it in the global scope. Note, however, that variables defined/assigned within functions are only in the local scope of that function (well, not always, but probably for the most part for now 😉 ), so they will not be overwriting variables in the global scope nor in the local scope of other functions.

                4. I'm wondering about my #2 question above - how does php know to locate a function in a file that's called in another? do they all have to be in the same folder in your www directory? what If I call a function when its located located in another folder? will it be able to locate it and execute it?

                The files can be anywhere that you can access them via the file system (and with read permission for the web server, which typically will actually be executing your PHP scripts); but you will need to [man]include/man, [man]include_once/man, [man]require/man, or [man]require_once/man them.

                  php_adrian;11024055 wrote:

                  thanks a lot guys. I'm going to come back to this in a few days - I'll rewrite it in mysqli....and try and figure it out myself.

                  Your function might be rewritten for MySQLi like so:

                  <?php
                  
                  /**
                   * checks if given $username already exists in `users` table.
                   * 
                   * @param string $username    the username to check.
                   * @param object $DB          database handle
                   *                            (this *must* be an instance of the mysqli class. more on this later).
                   * @return bool               true if username exists; false otherwise.
                   */
                  function check_username( $username,mysqli $DB ){
                  
                  # sanitize $username (to avoid SQL injection attacks/errors)
                  $username = $DB->real_escape_string( $username );
                  
                  # this is the SQL query we'll use.
                  $sql = "SELECT 1 FROM `users` WHERE `username`='$username'";
                  
                  # execute the query.
                  $result = $DB->query( $sql );
                  
                  # check if there were any rows in the result (if there were no rows, the username does not exist).
                  return (bool)$result->num_rows;
                  }

                  In the function parameters, $DB is your database handle. It has to be an instance of the mysqli class, or the function won't work. You create the handle somewhere in your script, and pass it to the function when you call it. Example usage:

                  <?php
                  
                  # database connection
                  $DB = new mysqli( 'DBhost','DBusername','DBpassword','DBname' );
                  
                  # username to check
                  $username = 'adrian';
                  
                  if( check_username( $username,$DB ) ){
                  
                  # check_username() returned TRUE.
                  print "The username '$username' already exists.";
                  }else{
                  
                  # check_username() returned FALSE.
                  print "The username '$username' is available.";
                  }

                    Your function might be rewritten for MySQLi like so:

                    Ok, thanks, your code worked for me - but I want to understand it. I think the reason it wasn't working was b/c I am using mysqli in my database connection.....and in the tutorial on Youtube, its wasn't...is that why all this wasn't working from the get go? Below are my files that all played a role in this working.

                    Login.php

                    <?php
                    // this file processes the username and password, and calls different functions, is the user active.
                    // to handle error handling (i.e - wrong password) we create an array called $errors in init.php
                    include 'core/init.php';
                    // include 'core/database/connect.php';
                    ini_set('error_reporting',-1);
                    ini_set('display_errors','On'); 
                    
                    # database connection 
                    $DB = new mysqli( 'localhost','root','', 'lr' ); 
                    
                    # username to check 
                    $username = 'adrian'; 
                    
                    if( check_username( $username,$DB ) ){ 
                    
                    # check_username() returned TRUE. 
                    print "The username '$username' already exists."; 
                    }else{ 
                    
                    # check_username() returned FALSE. 
                    print "The username '$username' is available."; 
                    } 
                    
                    if (empty($_POST) === false) { // === checks for type
                    	$username = $_POST['username']; //define the $username variable and point it back to the other login.php file where it says - <input type="text" name="username">
                    	$password = $_POST['password']; //define the $password variable and point it back to the other login.php file where it says - <input type="password" value="password">
                    
                    if(empty($username) == true || empty($password) === true) {
                    	$errors[] = 'You need to enter a username and password';  //if the username or password is empty, display the code
                    } else if(user_exists($username) === false) { //WORKFLOW:  we are checking if the user exists, which is calling the user_exists fucntion user_exists in users.php, which then passes in the username, sanitizing it by calling the sanitize function in the general.php, and then we run our query.
                    	$errors[] = "We can't find the username.  Have your registered?";
                    }
                    }
                    ?>
                    

                    Connect.php

                    <?php  //// This is what the code looks like after Database Connection
                    $link = mysqli_connect('localhost','root','', 'lr');
                    if (!$link) {
                        die('Connect Error (' . mysqli_connect_errno() . ') '
                                . mysqli_connect_error());
                    }
                    
                    // echo 'Success... ' . mysqli_get_host_info($link) . "\n";
                    
                    mysqli_close($link); // ended here
                    ?> 

                    Users.php

                    function check_username( $username,mysqli $DB ){ 
                    
                    # sanitize $username (to avoid SQL injection attacks/errors) 
                    $username = $DB->real_escape_string( $username ); 
                    
                    # this is the SQL query we'll use. 
                    $sql = "SELECT 1 FROM `users` WHERE `username`='$username'"; 
                    
                    # execute the query. 
                    $result = $DB->query( $sql ); 
                    
                    # check if there were any rows in the result (if there were no rows, the username does not exist).
                     return (bool)$result->num_rows; 

                    Question #1:

                    function check_username( $username,mysqli $DB ){ 

                    What are we saying above in english? We are going create a function called "check_username".....we want the $username variable to be used by this fuction?, right ....and ???? what does having mysqli and a variable called $DB there for? Can someone explain that to me when we have a mysql and a variable beside eachother? What is getting stored in $DB??

                    Question #2:

                     # sanitize $username (to avoid SQL injection attacks/errors)  
                    $username = $DB->real_escape_string( $username );

                    This question is partly because I don't know what's happening on with $DB and what its storing....but is the sequence like this? Take the data stored in $username and pass it through $DB, then pass that data through the real_escape_function, and pipe it back out into the $username variable? ....almost like an assembly line of sorts?

                    Thanks for all the help,

                    Adrian

                      Ok, after reading it more closely, I realize that the database connection details are kept in $DB...duh.....but I'm also wondering the syntax about this:

                      if( check_username( $username,$DB ) ){

                      What are we saying in english in the brackets? - ($username,$D😎 ...

                      Thanks.

                        php_adrian;11024133 wrote:
                        function check_username( $username,mysqli $DB ){ 

                        What are we saying above in english? We are going create a function called "check_username".....we want the $username variable to be used by this fuction?, right ....and ???? what does having mysqli and a variable called $DB there for? Can someone explain that to me when we have a mysql and a variable beside eachother? What is getting stored in $DB??

                        In english: yes, we're going to create a function called "check_username".

                        It accepts two arguments, and, within the function scope, will call them $username and $DB (this is unrelated to what they're called outside the function scope).

                        "mysqli" specifies that the $DB argument must be a mysqli object (the function will throw a fatal error otherwise). Doing this lets us skip explicitly checking that $DB really is the $DB that we need.

                        php_adrian;11024133 wrote:
                         # sanitize $username (to avoid SQL injection attacks/errors)  
                        $username = $DB->real_escape_string( $username );

                        This question is partly because I don't know what's happening on with $DB and what its storing....but is the sequence like this? Take the data stored in $username and pass it through $DB, then pass that data through the real_escape_function, and pipe it back out into the $username variable? ....almost like an assembly line of sorts?

                        Kinda. $DB (as you figured out on your own) is, basically, the database connection. It is a [man]mysqli[/man] object, and has a bunch of functions (which are called "methods") contained inside it, one of which is real_escape_string(). It escapes certain characters in $username so they can't be confused with SQL commands or keywords (which would create a security weakness and opportunity for completely avoidable errors).

                        php_adrian wrote:
                        if( check_username( $username,$DB ) ){  

                        What are we saying in english in the brackets [sic]?

                        This is where we're calling the function. the two variables inside the parenthesis - $username and $DB - are the username and database connection, respectively, that we're passing into the function's scope for use.

                          4 days later

                          Thanks, I'm going to read up more on functions...thanks for all your help...

                          Adrian

                            no problem. please ask if you need anything else!

                              Write a Reply...