如何使用php连续获取所有数据?

时间:2018-11-05 06:35:02

标签: php mysqli

我关注了这个youtube视频教程here。它教会了我如何获取用户名并将其发布到index.php页面。我想知道如何获取行中的所有数据,而不仅仅是username(注意:我使用email_address作为用户名)。表格中有firstname, lastname, email_address, password

if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM user_info WHERE email_address='$username' AND password='$password'";
    $result = mysqli_query($db, $query);
    if (mysqli_num_rows($result) == 1) {
        $_SESSION['email_address'] = $username;
        $_SESSION['success'] = "You are now logged in";
        header('location: dashboard.php');
    } else {
        array_push($errors, "Wrong username/password");
    }
}

3 个答案:

答案 0 :(得分:0)

实际上,您不是从查询中获取用户名,而是从POST中获取用户名。您将查询结果存储到$result变量中,然后可以使用它访问行。

if (count($errors) == 0) {
    $password = md5($password);
    $query = "SELECT * FROM user_info WHERE email_address='$username' AND password='$password'";

    $result = mysqli_query($db, $query);

    while ($row = $result->fetch_assoc()) {
        $_SESSION['email_address'] = $row['username'];

        //here goes other rows from your DB
        //$row['email'];
        //$row['other_rows'];

        $_SESSION['success'] = "You are now logged in";
        header('location: dashboard.php');
    } else {
        array_push($errors, "Wrong username/password");
    }
}

答案 1 :(得分:0)

这应该做到。您已经从数据库中选择了所有列,因此只需要使用它即可。

LIMIT 1确保您只退回一行,而且无论如何都回退不超过一排。

if (count($errors) == 0) {

     $password = md5($password);
     $query = "SELECT * FROM user_info WHERE email_address='$username' AND password='$password' LIMIT 1";

     $result = mysqli_query($db, $query);

     if(mysqli_num_rows($result) == 1) {
         $_SESSION['email_address'] = $result['username'];
         $_SESSION['firstname'] = $result['firstname'];
         $_SESSION['lastname'] = $result['lastname'];        
         $_SESSION['success'] = "You are now logged in";
        header('location: dashboard.php');
     } else {
        array_push($errors, "Wrong username/password");
     }
}

答案 2 :(得分:0)

从php.net关于mysqli_query

  

失败时返回FALSE。对于成功的SELECT,SHOW,DESCRIBE或EXPLAIN查询,mysqli_query()将返回mysqli_result对象。对于其他成功的查询,mysqli_query()将返回TRUE。

您仍然需要将结果作为关联数组来获取以使用它(例如,使用mysqli_fetch_assoc)。数组将以列名作为键,以列值作为值。

if (count($errors) == 0) {
    $password = md5($password);
    $query = "SELECT * FROM user_info WHERE email_address='$username' AND password='$password'";
    $sqlQuery = mysqli_query($db, $query);
    // fetch the result as an associative array here
    $result = mysqli_fetch_assoc($sqlQuery);
    if (mysqli_num_rows($sqlQuery) == 1) {
       // if you are using the email_address as username
       $_SESSION['email_address'] = $result['email_address'];
       $_SESSION['first_name'] = $result['firstname'];
       $_SESSION['last_name'] = $result['lastname'];

       $_SESSION['success'] = "You are now logged in";
       header('location: dashboard.php');
    } else {
        array_push($errors, "Wrong username/password");
    }
}