Ruth
Ruth

Reputation: 13

How to echo an item from a database

I am still in the process of learning PHP so forgive me for the poor code. I am attempting to get the users first name to output once they have logged in, however nothing is returning, please may I have some help.

   <?php

session_start();

$DATABASE_HOST="localhost";
$DATABASE_USER="root";
$DATABASE_PWORD="";
$DATABASE_NAME="registration";

$connection=mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PWORD, $DATABASE_NAME);
if (mysqli_connect_errno()){
    //if there is an issue with connecting to the database, ends code and displays the error
    die("failed to connect to server: " .mysqli_connect_error()); //kills program
}

if (!isset($_POST['email'], $_POST['pswd'])){ //checking if both fields were inputted into on the form, isset()checks if data exists
    //unable to get data
    die("please fill in both email and password"); //kills program
}

$email = mysqli_real_escape_string($connection, $_POST['email']); //saves input as string, preventing misinterpretation
$password = mysqli_real_escape_string($connection, $_POST['pswd']);//saves input as string, preventing misinterpretation

$SQLstatement = "SELECT * FROM users WHERE email='$email' and password='$password'"; //querys the database for match

$Queryresult = mysqli_query($connection, $SQLstatement) or die(mysqli_error($connection)); //runs the query 

$rowsQueryResult = mysqli_num_rows($Queryresult);//number of 'emails' in database where the emails match
$dbFirstName=$rowsQueryResult ['firstName'];
    if ($rowsQueryResult==1){//if the number of emails where a match is made, is 1 
        echo "Welcome $dbFirstName <br/> ";
        echo "successful login. <a href='accountPage.php'>Click</a> here to access the accounts page";      //successful login, links to accounts page
        $_SESSION['firstName']=$dbFirstName;

    }else{ //if matches are 0 or >=2 
        die ('unsuccessful login'); //kills program
    }

?>

Thank you for your time and help

Upvotes: 1

Views: 104

Answers (2)

Hayk Melkonyan
Hayk Melkonyan

Reputation: 77

The mysqli_num_rows() function returns the number of rows in a result set.

$rowsQueryResult = mysqli_num_rows($Queryresult);`

will give number of 'emails' in database where the emails match.

You need to use mysqli_fetch_assoc() as

$row = mysqli_fetch_assoc($Queryresult);
$dbFirstName=$row['firstName'];

Upvotes: 1

Sagun Raj Lage
Sagun Raj Lage

Reputation: 2504

This problem can be solved by using the mysqli_fetch_assoc() function in place of mysqli_num_rows(). However, I would recommend you to use PDO since it's easier to implement and more readable.

Upvotes: 1

Related Questions