Lnvz
Lnvz

Reputation: 141

How to get user's name from the database? MYSQLI newbie

After lots of sweat and struggle I managed to get it working ~somehow~. Although I don't know how to program something that will check user's name based on their password that the user entered previously. Any help? I want to set the name as session's name or something, I think that's more 'secure'.

<?php
ob_start();
session_start(); 
$host="localhost";
$user="x";
$pass="x";
$db="x";
$tbl_name="users";

$mysqli = mysqli_connect($host, $user, $pass, $db);

$mypassword=$_POST['code'];

$mypassword = stripslashes($mypassword);
$mypassword = $mysqli->real_escape_string($mypassword);
$encrypt_password=md5($mypassword);

$sql="SELECT * FROM $tbl_name WHERE password='$encrypt_password'";
$result=$mysqli->query($sql);

$count=mysqli_num_rows($result);

if($count==1) {



$_SESSION['mypassword']="$mypassword";
header("index/index.php");

}   
}
?>

Upvotes: 0

Views: 1919

Answers (2)

Barmar
Barmar

Reputation: 781058

Fetch the row returned by the query and get the username from that.

if ($count == 1) {
    $row = $result->fetch_assoc();
    $_SESSION['username'] = $row['username'];
    header("Location: index/index.php");
}

Upvotes: 1

volkinc
volkinc

Reputation: 2128

Hi you need edit your query to something like this:

 $sql="SELECT * FROM $tbl_name WHERE password='$encrypt_password' AND `username`='$myusername'";

    As if you have 
    $count=mysqli_num_rows($result);

    if($count==1) {
    // it means your user is in a db and it could be marked as logged in

     header("Location: index/index.php");
    }

Upvotes: 1

Related Questions