-3

If mysqli connects to the database and after the if(!mysqli_stmt_execute($check)){ shouldnt this return NULL or false if there is no record found?

After execution of this line and checking the user exists in the database it shouldn't it return NULL and exit the program if the user or record doens't exists?

How to solve this problem without fetching the whole result set and looping over it?

<?php
     ////////////// ADDED CODE ////////////
     $user_exists = FALSE;
     ///////////////////////////////////////
     $user = null;
     $pass = null;
     /* Connects to your Database */
$mysqli = mysqli_connect("localhost", "dbUser", "dbPassword","dbName");
        if (!$mysqli) {
            echo "Failed to connect to MySQL: (" . $mysqli->errno . ") " . mysqli_connect_error();
            exit();
            }

     /* create a prepared statement */
     $check = mysqli_prepare($mysqli, "SELECT username, password FROM users WHERE username = ?");

     /* bind parameters for markers */
     mysqli_stmt_bind_param($check, "s", $user);
     echo $mysqli->host_info . "Mysql connected: Succes.\n";

     /* Checks if there is a login cookie */
     if (isset($_SESSION['refer'])){$location = $_SESSION['refer'];}
     if(isset($_COOKIE['ID_my_site'])){
        /*if there is, it logs you in and directes you to the members page */
        echo "Yes there is a cookie";
        $user = $_COOKIE['ID_my_site'];
        $pass = $_COOKIE['Key_my_site'];
        }
    /* if the login form is submitted */
       if (isset($_POST['submit'])) {
             echo " Form submitted.";
                 /* if form has been submitted */
                 /* makes sure they filled it in */
      if(!$_POST['username'] | !$_POST['pass']) {
                  die('You did not fill in a required field.');
                        /* close statement */
                        mysqli_stmt_close($check);
                        /* close connection */
                        mysqli_close($mysqli);
                       }
      $user = stripslashes($_POST['username']);
      $pass = stripslashes($_POST['pass']);
      $pass = md5($pass); 
    /* checks it against the database */

    /* execute query */
    if(!mysqli_stmt_execute($check)){
    die('That user does not exist in our database. <a href=Registration.php> Click Here to Register</a>');} 

    /* bind result variables */
    mysqli_stmt_bind_result($check, $user_column, $pass_column);
    /* fetch value */
    /* Gives error if user dosen't exist */
         while(mysqli_stmt_fetch($check)!= NULL){
            /* gives error if the password is wrong */
            $user_exists = TRUE;
            echo " fetch = NOT null --->> ".$user_column;
            if ($pass != $pass_column){
                 /* statement close */
                 mysqli_stmt_close($check);
                 /* close connection */
                 mysqli_close($mysqli);
                 die('Incorrect password, please try again.');
                 }
                }
    if(!$user_exists){
    die('That user does not exist in our database. <a href=Registration.php> Click Here to Register</a>');}

      /* if login is ok then we add a cookie */
      $hour = time() + 3600;
      setcookie(ID_my_site, $user, $hour);
      setcookie(Key_my_site, $pass, $hour);
      /* then redirect them to the members area */
        header("Location: Members.php");
}
  else
    {


    /* if they are not logged in */
    /* added rest of code for convenience */
    ?>
    /* if they are not logged in */
?>
<!DOCTYPE HTML>
<HTML>
<HEAD>
<meta http-equiv="Content-type" content="text/html" charset=utf-8>
<TITLE>Login</TITLE>
<style>
label,section{display:block;margin-top:20px;letter-spacing:2px;}
form {margin:0 auto;width:60%;}
input,textarea{width:55%;height:27px;padding:10px;margin-top:3px;background:#efefef;border:1px solid #dedede;font-size:0.9em;color:#3a3a3a;border-radius:5px;-web-border-radius:5px;-webkit-border-radius:5px;}
textarea{height:213px;}
input:focus,textarea:focus{border:1px solid #97d6eb;}
.body {display:block;margin:0 auto;width:70%;}
#submit {display:block;align:right;width:127px;height:38px;border:1px solid #dedede;margin-top:20px;cursor:pointer;}
#submit:hover {opacity:0.9;border:1px solid #97d6eb;}
</style>
</head>
<body>
<header class="body"><label>Login page.</label></header>
<section class ="body">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
       <label>Username:</label>
       <input name="username" type="text" placeholder="Type your name here." autofocus required>
        <label>Password</label>
        <input name="pass" type="password" placeholder="*******************" autofocus required>
        <input id="submit" name="submit" type="submit" value="Login">
  </form>
</section>
 <footer class="body"><label>Write your footer code here.</label></footer>
</body>
</html>
    <?php
      }
    ?>
Andre
  • 172
  • 2
  • 8
  • To me it looks like a couple operators thrown together at a quite random order. – Your Common Sense Jul 06 '13 at 09:34
  • funny enough it does work lol I could edit it to look "Professional" ... – Andre Jul 06 '13 at 09:36
  • 2
    "Works" is a subjective thing... – Your Common Sense Jul 06 '13 at 09:46
  • As is "I find your coding crap and mine is good ..." Thats why low-level coding is much more fun not all those diffrent syntaxes to learn. I just shuffeld around some mysql code to get it work and then finelyzing it making it fluent and crisp. – Andre Jul 06 '13 at 09:53
  • Oh, no. I don't find your code crap. Looking at all these comments scattered around I would say this code is just adopted by you - so, I have no objections on your code at all. – Your Common Sense Jul 06 '13 at 10:12
  • ah ok, at several points in life we all adopted somebodies knowledge, its called learning. My webspace supplier doesnt let me code in lower-level so i have to learn some php and mysql to get it working lol copy and past some here and there and getting into binary flow is the challenge for a smooth stable running program even though it is a high programming language ... – Andre Jul 06 '13 at 11:27
  • The bad thing with PHP, whatever code one can adopt written in this language, most certainly would be a complete crap. – Your Common Sense Jul 06 '13 at 11:45
  • true, as with any language. I'am not a top coder not even professional but i learned allot especially about basic computer behavior and then you see 95% of the coders know there syntax very well but have know clue of whats going on under the bonnet. The basics and menace of programming. – Andre Jul 06 '13 at 12:10

2 Answers2

2

It is not actually an answer but I just can't stand this long and windy traditional PHP-style spaghetti. Look, there are several screens of code for as simple task as getting one single value from database! That's just weird to my taste.

This is how it have to be at least

<?php
/* have all the common routines included */
include 'bootstrap.php';

/* if the login form is submitted */
if (isset($_POST['submit']))
{
    $sql = "SELECT id, password FROM users WHERE username = ?";
    /* let's use some *intelligent* way to deal with database */
    $row = $dbal->getRow($sql, $_POST['username']);

    /* if we got something and password is correct*/
    if ( $row && password_verify($_POST['pass'],$row['password']) )
    {
        /* set user into session and redirect */
        $_SESSION['user'] = $row['id'];
        header("Location: Members.php");
        exit;
    }
}
?>
<!DOCTYPE HTML>
here goes HTML ...
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
-1

mysqli_stmt_execute returns FALSE on broken query i.e. no connection to db, syntax error, or so. If you want to check if the query does not return any rows, you shouldn't use TRUE/FALSE operators, nor the execute function itself. You should use mysqli_num_rows which returns how many rows the SELECT statement returns. Basicly if the returned rows are 0 (not false), you should exit.

Royal Bg
  • 6,988
  • 1
  • 18
  • 24
  • But dont you need to first use store_result() wich copies the records in a array and then loop over them to see if the record exists? doesnt this create alot of memory allocation and extra handelings for the cpu? – Andre Jul 06 '13 at 10:01
  • Returns the number of rows in the result set. The behaviour of mysqli_num_rows() depends on whether buffered or unbuffered result sets are being used. For unbuffered result sets, mysqli_num_rows() will not return the correct number of rows until all the rows in the result have been retrieved. http://php.net/manual/en/mysqli-result.num-rows.php – Andre Jul 06 '13 at 10:07
  • The official doc says (http://www.php.net/manual/en/mysqli-result.num-rows.php): Parameters: `Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().`. So you don't need to. You can check out the examples there, right after the query, the num_rows is used – Royal Bg Jul 06 '13 at 10:07
  • In your case you expect 1 or 0 rows, it should not have any problems – Royal Bg Jul 06 '13 at 10:10
  • I found a work around: At the top set $user_exsist = FALSE; in the while loop: $user_exists = TRUE; and below the while loop: if(!$user_exists){ die('That user does not exist in our database. Click Here to Register');} – Andre Jul 06 '13 at 10:51
  • I thought you don't want to iterate through the results, while you are searching for 0 rows :) – Royal Bg Jul 06 '13 at 10:56
  • No i dont want to copy and then itterate over the results. You have to itterate to see if its there. The database is returning NULL if it isnt there ... :-) – Andre Jul 06 '13 at 11:02
  • Got your point :) So, yes, once your are looping through them is easy to check whether the loop exits :) Glad to see you have solved your problem – Royal Bg Jul 06 '13 at 11:03
  • @Andre there is no use for loops at all. – Your Common Sense Jul 06 '13 at 11:46
  • Hmm how do you mean? because if you have a couple of vars in a array you can only loop through the arr to find out whats in there, unless you know an elements position or index you could retrieve it right away. – Andre Jul 06 '13 at 12:06
  • The loop is in the execute statement and the while loop loops the variable found by the dbase-engine – Andre Jul 06 '13 at 15:48