无法从MySQL数据库中获取行

时间:2016-08-05 04:00:25

标签: php mysql login

我在mysql上有点生疏,特别是现在它是mysql ...在下面的脚本中没有任何反应,变量$ row [username]等是空的。我做错了什么?

<?php

session_start();
include_once('./db_config.php');

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = md5(mysqli_real_escape_string($conn, $_POST['password']));

$query = "SELECT * FROM players WHERE username = '".$username."' AND password = '".$password."'";

if($res = mysqli_query($conn, $query))
{
    $row = mysqli_num_rows($res);
    $_SESSION['Username'] = $row['username'];
    $_SESSION['uID'] = $row['id'];
    $_SESSION['Join_Date'] = $row['join_date'];
    mysqli_free_result($res);

    header('Location: ../index.php');
} else
{
    echo mysqli_error($conn);
}

?>

1 个答案:

答案 0 :(得分:2)

你没有取得记录而是你正在做myql_num_rows(这只会给你一些记录)

用它来获取记录

  

$row = mysqli_fetch_array($res,MYSQLI_ASSOC);

<?php

session_start();
include_once('./db_config.php');

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = md5(mysqli_real_escape_string($conn, $_POST['password']));

$query = "SELECT * FROM players WHERE username = '".$username."' AND password = '".$password."'";

if($res = mysqli_query($conn, $query))
{

    $row = mysqli_fetch_array($res,MYSQLI_NUM);
    $_SESSION['Username'] = $row['username'];
    $_SESSION['uID'] = $row['id'];
    $_SESSION['Join_Date'] = $row['join_date'];
    mysqli_free_result($res);

    header('Location: ../index.php');
} else
{
    echo mysqli_error($conn);
}

?>