MYSQLi记录不存在检查 [英] MYSQLi record doesnt exists check

查看:58
本文介绍了MYSQLi记录不存在检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果mysqli连接到数据库,并且之后 if(!mysqli_stmt_execute($check)){ 如果找不到记录,是否应该返回NULL或false?

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?

执行此行并检查用户是否存在于数据库中后,如果用户或记录不存在,它是否不应该返回NULL并退出程序?

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
      }
    ?>

推荐答案

这实际上不是答案,但我受不了这条漫长而多风的传统PHP风格的意大利面.看起来,有几个代码屏幕,就像从数据库中获取一个单一值一样简单!那太奇怪了.

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.

至少必须这样

<?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 ...

这篇关于MYSQLi记录不存在检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆