0

What I want is to return MYSQL query in a array however my code returns a bool(true).
Here is the code from code.php

require('model.php');

$id = $_POST['id'];
$password = $_POST['password'];

$user = new user();

$row = $user->check_user($id, $password);
var_dump($row);

Here is the code from model.php

class config {

    public $dbhost = "localhost";
    public $dbuser = "root";
    public $dbpass = "";
    public $dbused = "dbname";

    function dbconn() {

        $conn = mysqli_connect($this->dbhost,$this->dbuser,$this->dbpass,$this->dbused);

        if(mysqli_connect_errno()) {

            printf("Connection failed: " . mysqli_connect_error());
            exit();

        }

        return $conn;

    }

}

class user {

    function check_user($id, $pass) {

        $config = new config();

        $conn = $config->dbconn();

        $query = $conn->prepare("SELECT id, password, status FROM e_users WHERE id = ? AND password = ?");

            $query->bind_param('is', $id, $pass);

            try {

                $query->execute();

                return $query->fetch();

            } catch(PDOException $e) {

                die($e->getMessage());

            }

    }

}

I think the problem is in the $query->fetch(); because I tried return 'test'; and it works fine. Even return an array works fine.

Can anyone help me?

3
  • 1
    return $query->fetch(); will simply return true if the fetch operation was successful and false if it wasn't. It doesn't return the data you requested. Commented Aug 15, 2014 at 15:35
  • @TheBlueDog if it is then, how should i return it in array? Commented Aug 15, 2014 at 15:39
  • return $query->fetch_assoc(); as per the answer posted by @peter_the_oak below. Commented Aug 15, 2014 at 15:51

1 Answer 1

1

As The Blue Dog pointed out, fetch() returns a status flag, not the row itself. But fetch_assoc() will return a row.

Have a look here:

http://php.net/manual/en/mysqli-stmt.fetch.php

If you work with fetch, you need to bind the variables:

$stmt->bind_result($mySelectedValue_1, $mySelectedValue_2);

Here are examples with fetch_assoc():

http://php.net/manual/de/mysqli.quickstart.prepared-statements.php

So this should work fine:

$row = $res->fetch_assoc();
Sign up to request clarification or add additional context in comments.

2 Comments

peter_the_oak and @The Blue Dog thanks for the info guys, it is now working like what i wanted.If i could i would you all a big hug :))
Glad to help. So it's a distributed, or virtual hug ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.