0

So I'm trying to call an array which is generated from a database, here is the function in the class file:

public function select($array) 
{
   try 
   {
       $result ="SELECT id,make,model FROM cars";

       $stmt = $this->db->query($result);
       $array = $stmt->fetchAll();
   } 
   catch (PDOException $e) 
   {
       echo $e->getMessage();
   }
}

and here i'm trying to call the array, at least I am, quite new to this.

    include ('CarsDb.class.php');
    $db = new CarsDb();
    $db->connect();
    $carArray = $db->select($array);
    var_dump($carArray);

Now the var_dump just shows NULL, however if I put a var_dump in the function it'll show the array on my page, so can anyone help me?

1
  • return statement is missing in select function ... Commented Apr 28, 2014 at 8:49

2 Answers 2

3

You need to return a value from your function. Do this.

public function select($array) {
    try {
        $result ="SELECT id,make,model FROM cars";
        $stmt = $this->db->query($result);
        return $stmt->fetchAll(); //Return value here
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
}

And now this should work.

include ('CarsDb.class.php');
$db = new CarsDb();
$db->connect();
$carArray = $db->select($array);
Sign up to request clarification or add additional context in comments.

3 Comments

That's got it working, thank you very much, saved me a lot of hair pulling.
@JayBhatt please consider the case when try block fails.
@RajeevRanjan The array returned by the function is initialized only if the query succeeds. If an exception is thrown the array will be empty. Rather then returning empty values the code should handle exceptions.
0

Return array from the select function

public function select($array=array()) {
try {

    $result ="SELECT id,make,model FROM cars";

    $stmt = $this->db->query($result);
    $array = $stmt->fetchAll();



} catch (PDOException $e) {
    echo $e->getMessage();
}
return $array;

}

Comments

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.