Shiven Sinha
Shiven Sinha

Reputation: 696

Assign MySQL database value to a PHP variable

I am trying to get the password of a specified username, assign it to a PHP variable, and then print it. Here's the code for it -

$user = $_POST["uname"];
$pass = mysqli_query($con, "SELECT pass FROM users WHERE username = '$user'");                                              
$result = mysqli_fetch_array($pass);

$specific = $result['pass'];

echo $specific;

The problem is that nothing is being printed at all! Even no error. What do I do?

Upvotes: 0

Views: 2432

Answers (2)

Blake A. Nichols
Blake A. Nichols

Reputation: 870

Escape your values and check for errors:

$user = mysqli_escape_string( $con, $_POST["uname"] );
$pass = mysqli_query( $con, "SELECT pass FROM users WHERE username = '$user'");

# Error checking
if( $pass === false ) {
    echo 'Error: ', mysqli_error( $con );
}

# Check for no user with that password
if( mysqli_num_rows( $pass ) == 0 ) {
    echo 'No user with that username.';
}

# Use as associate arary              
$result = mysqli_fetch_assoc($pass);

$specific = $result['pass'];

echo $specific;

edit: Added check for no results.

Upvotes: 1

user5742934
user5742934

Reputation:

$pass = mysqli_query($con, "SELECT pass FROM users WHERE username = '$user'") or die(mysqli_error($con)); 

This will Show you the Correct Error in your query

Upvotes: 1

Related Questions