MrDrewskii
MrDrewskii

Reputation: 91

How can I echo an array of values from a php mySQL query?

Basically I am attempting to make a login. I understand a very small amount of php, but everytime I try to log in it works. So it is not following my if statement below. So I would like to see if anyone can help me print the $results as not a string. Everytime I echo it, it says error can not print as string. Which makes me think its an array, can someone help ? =(

<?php
include('include/dbConnection.php');

if (isset($_REQUEST['attempt']))
{
    //variables
    $user = $_POST['user'];
    $password = sha1($_POST['password']);

    //SQL statement
    $query = "SELECT COUNT(user) 
              FROM users
              WHERE user = '$user'
              AND password = '$password'";

    //Execute prepared MySQL statement
    $results = mysqli_query($dbc,$query) or die('Error querying database');
        /* Here is where I want to print $results

    if ($results = 1)
    {
        session_start();
        $_SESSION['$user'];
        header('location: home.php');
    }
    else
    {
        echo $results + 'Incorrect Username or Password';
    }

*/
    //Close dbConnect
    mysqli_close($dbc);
}

?>

Upvotes: 0

Views: 84

Answers (4)

erencan
erencan

Reputation: 3763

mysqli_query function returns false for unsuccessful queries. it returns a MySQLi_Result object for select or show queries and true for insert and update queries.

if your query fails for some reason your script will die because of or die statement and never returns false.

if ($results = 1) 

statement assigns 1 to your result variable. when your script runs, your code enters this if block. because you control the assignment statement whether it is done or not.

your query is a select, mysqli_query function returns MySQLi_Result object.

Upvotes: 0

Friend of Kim
Friend of Kim

Reputation: 860

You have to use this:

echo "<pre>";
print_r($results);
echo "</pre>";

It first echoes so that the print of the array is formatted properly. If you don't do this it will all be on one line.

Hope this helped! :D

Upvotes: 1

Marc B
Marc B

Reputation: 360762

mysql_query() returns a statement result handle, NOT the data you've requested in the query. You first have to fetch a row of data to get access to the actual query data:

$result = mysqli_query(...);

$row = mysqli_fetch_row($result);
$count = $row[0];

Upvotes: 0

djdy
djdy

Reputation: 6919

Use var_dump($output) or print_r($output) to display contents of an array.

Upvotes: 1

Related Questions