Micard Micard - 4 months ago 15
MySQL Question

Can't fetch rows from MySQL database

I'm a bit rusty on mysql, especially now that it's mysqli... Nothing happens in the script below, the variables $row[username] etc are empty. What am I doing wrong?

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

?>

Answer

You are not fetching the records instead you are doing myql_num_rows(this will give only no of record)

use this to fetch records

$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);
}

?>