Search code examples
phpmysqliprepared-statement

Statement to tell me the username already exists


The below query is not telling me the username already exists in the database even though it does.

I am trying to learn how to bind parameters etc. but have confused myself somewhere I think.

<?php
    // Include config.php
    require_once("".$_SERVER['DOCUMENT_ROOT']."/admin/config.php");

    // top.inc.php
    require_once($top_inc);
?>

<!-- Meta start -->
<title></title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<!-- Meta end -->

<!-- CONTENT START -->

<?php
    // sidebar.inc.php
    require_once($sidebar_inc);

    // main.inc.php
    require_once($main_inc);

    // check if form has been submitted
    if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit'])){

        // initialize form errors array
        $error    = array();

        // fetch form data
        $username = $_POST['username'];
        $email    = $_POST['email'];
        $password = $_POST['password'];

        // validate form data
        if(!preg_match(constant("USERNAME_REGEX"), $username)){
            $error[] = "Please enter a username. Use 3 to 15 digits and letters";
        }
        if(!preg_match(constant('PASSWORD_REGEX'), $password)){
            $error[] = "Please enter a password. Minimum of 6 characters required";
        }
        if(!empty($password) && $password == $username){
            $error[] = "Your pasword cannot be you username for security reasons";
        }
        if(empty($email)){
            $error[] = "Please enter your email address";
        }
        if(!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)){
            $error[] = "Your email address is not valid";
        }

        // connect to database
        sql_con();

        // Get instance of statement
        $stmt = mysqli_stmt_init($connect);

        // sql statement
        $UserExists = "
                    SELECT
                        `user_login`
                    FROM
                        `users`
                    WHERE
                        `user_login` = ? ";

        // prepare sql statement for execution
        if (mysqli_stmt_prepare($stmt, $UserExists)) {

            // bind parameters [s for string]
            mysqli_stmt_bind_param($stmt, "s", $username) or die(mysqli_stmt_error());
            // execute statement
            mysqli_stmt_execute($stmt) or die(mysqli_stmt_error());
            // check if username is found
            if(mysqli_stmt_num_rows($stmt) > 0 ){
                $error[] = 'The username you have choose has already been taken';
            }
        }

        // If errors found display errors
        if(!empty($error)){
            foreach($error as $msg){
                echo "$msg <br />";
            }
    } else {
            echo 'My Query Worked!';
        }
    }
    // signup.tpl template location
    $tpl = 'inc/tpl/signup.tpl';
    // load signup form template
    PageContentTemplate($tpl);
?>

<!-- CONTENT FINISH -->

<?php
    // footer.inc.php
    require_once($footer_inc);
?>

Basically it just echos out 'My Query Worked' even though it should say the username is already taken which it is, I enter details on the form and a username I know that has been taken and submit the form, I know I am doing something probably really silly but being new to mysqli and binding parameters etc. I don't know where I am going wrong even though I have looked at some examples.

To be honest, I am not sure if this is the best way to do it in procedural style, I don't know PDO/OOP, my main reason to change is to avoid SQL injection by using placeholders etc. in my queries.


Solution

  • I see it now. You have not called mysqli_stmt_store_result() before which mysqli_stmt_num_rows() won't report the correct value.

        // prepare sql statement for execution
        if (mysqli_stmt_prepare($stmt, $UserExists)) {
    
            // bind parameters [s for string]
            mysqli_stmt_bind_param($stmt, "s", $username) or die(mysqli_stmt_error());
            // execute statement
            mysqli_stmt_execute($stmt) or die(mysqli_stmt_error());
    
            // check if username is found
            // FIRST : store the store the result set so num_rows gets the right value
            mysqli_stmt_store_result($stmt);
    
            // Now this should be 1 instead of 0
            if(mysqli_stmt_num_rows($stmt) > 0 ){
                $error[] = 'The username you have choose has already been taken';
            }
        }
    

    From the docs:

    Returns the number of rows in the result set. The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle.

    If you use mysqli_stmt_store_result(), mysqli_stmt_num_rows() may be called immediately.