MKougiouris
MKougiouris

Reputation: 2861

Retrieve value from database

I am trying to create a login script with PHP. Users are redirected to it by a login form with username and password fields. My problem here is that mysqli fetch_assoc() does not return anything. I tried the same query on the database and it works as expected. I tried using fetch_array with mysql_assoc, or as numeric array but still no luck. I tried accessing with both $row[0] and $row[password] for the returned value, but when running I get the "no rows found, nothing to print", so I guess everything works good until that point.

Any hints as to what I might be missing?

<?php 
$con=mysqli_connect('localhost','root','','site');

if(!$con)
{
die('Could not connect to database : ' . mysql.error());
}

$result=mysqli_query($con,'SELECT Password FROM users WHERE Username="$_POST[iusrname]" LIMIT 1');

if (!$result)
{
    Die("Could not successfully run query from DB: " . mysql_error());
}

$row = mysqli_fetch_assoc($result);

if (mysqli_num_rows($result) == 0)
{
    die("No rows found, nothing to print");
}


if($_POST[ipwd] == '$row[password]')
{
echo "Authentication succeeded.You will be redirected to the main page shortly";
$_SESSION['loged']=true;
$_SESSION['user']=$_POST[iusrname];
}
else
{
die("could not authenticate user");
}

mysqli_close($con);
?>

Upvotes: 1

Views: 219

Answers (2)

Rafael
Rafael

Reputation: 2817

Try changing you query from this:

'SELECT Password FROM users WHERE Username="$_POST[iusrname]" LIMIT 1'

to this:

'SELECT Password FROM users WHERE Username='.$_POST['iusrname'].' LIMIT 1'

also you will have problems here:

if($_POST[ipwd] == '$row[password]')

should be:

if($_POST["ipwd"] == $row["password"])

and most likely here:

$_SESSION['user']=$_POST[iusrname];

that should be:

$_SESSION['user']=$_POST['iusrname'];

Upvotes: 1

11684
11684

Reputation: 7507

I spotted the error, I think.

In single quotes ('') PHP will not automatically replace variable names with variable values. Using double quotes should do the trick:

$username = mysqli_real_escape_string($con, $_POST['iusrname']); // For @cHao
$result=mysqli_query($con,"SELECT Password FROM users WHERE Username='$username' LIMIT 1");

Upvotes: 2

Related Questions