无法从MySQL数据库中检索值

时间:2012-07-01 14:04:12

标签: php mysql database mysqli

我是使用MySql的新手,我在从数据库中检索值时遇到问题。我的印象是我正确的方式,但我的回声声明没有打印任何东西。

我很感激一些帮助。我的代码如下。我知道我必须在以后添加安全性,例如清理用户输入。

<?php
            $email = $_POST['email'];
            $password = $_POST['password'];
            $hashedPass = sha1($password);

            if ((!isset($email)) || (!isset($password))) {
                //Visitor needs to enter a name and password
                echo "Data not provided";
            } else {
                echo "Received details $email and $password <br/>";
                // connect to mysql
                $mysql = mysqli_connect("localhost", "root", "root");
                if(!$mysql) {
                echo "Cannot connect to PHPMyAdmin.";
                exit;
                } else {
                echo "Connected to phpmyadmin <br/>";
                }
            }
            // select the appropriate database
            $selected = mysqli_select_db($mysql, "languageapp");
            if(!$selected) {
                echo "Cannot select database.";
                exit;
            } else {
                echo "DB Selected"; 
            }
            // query the database to see if there is a record which matches
            $query = "select count(*) from user where email = '".$email."' and password = '".$hashedPass."'";
            $result = mysqli_query($mysql, $query);
            if(!$result) {
                echo "Cannot run query.";
                exit;
            }

            $row = mysqli_fetch_row($result);
            $count = $row[0];

            $userdata = mysqli_fetch_array($result, MYSQLI_BOTH);
            echo $userdata[3];
            echo $userdata['firstName'];

            if ($count > 0) {   
                echo "<h1>Login successful!</h1>";
                echo "<p>Welcome.</p>";
                echo "<p>This page is only visible when the correct details are provided.</p>";
            } else {
                // visitor's name and password combination are not correct
                echo "<h1>Login unsuccessful!</h1>";
                echo "<p>You are not authorized to access this system.</p>";
            }
            ?>

1 个答案:

答案 0 :(得分:1)

我认为问题是您调用了两次* fetch *系列函数,这将导致$ userdata为空。

从文档mysql_fetch_row中获取下一行并向前移动内部数据指针。所以当你调用mysqli_fetch_array($ result,MYSQLI_BOTH)时,我认为用户/密码是唯一的,没有什么可以检索的。您所做的另一个错误是您的SELECT不检索实际的用户数据,而只检索用户/密码组合的计数。因此,即使您正确地获取数据,您的用户数据也总是不正确的。

所以将您的查询更改为:

 $query = "select * from user where email = '".$email."' and password = '".$hashedPass."' LIMIT 1";

然后使用mysql_fetch_array检查条目是否存在,然后检索用户数据。