1

I want to retrieve some Data from database using custom PHP MVC.

I created a Controller File

semestres.php

class Semestres extends Controller {

    function __construct(){
        parent::__construct();      
    }
    public function index(){
        $this->view->fetchSemestres = $this->model->fetchSemestres();
        $this->view->render('semestres/index');
    }
}

a Model

semestres_model.php

class Semestres_Model extends Model{
    public function __construct(){
        parent::__construct();
    }

    public function fetchSemestres(){
        $stmt = $this->db->prepare("SELECT * FROM semestres");  
        $stmt->setFetchMode(PDO::FETCH_ASSOC);  
        $stmt->execute();
        return $stmt->fetchAll();       
    }   
}

and a View file index inside the folder semestre.

foreach($this->fetchSemestres AS $key=>$value){
    echo $value['intitule_semestre']."<br>";
}

But it gives me nothing !!!

The print_r($this->fetchSemestres) gives me an empty array

Array ( )

// Update:

Database connection:

class Database extends PDO{
    public function __construct(){
        parent::__construct('mysql:host:localhost;dbname:planingexams', 'root', '');
    }
}

Model.php

class Model{

    function __construct(){
        $this->db =  new Database();
    }
}
5
  • I updated my code above and added database connection Commented May 8, 2015 at 21:17
  • That Array() is the result of your echo? if so try a var_dump instead of an echo. The act that you get array() means $value['intitule_semestre'] contains an array and echo cannot print what is inside. Commented May 8, 2015 at 21:19
  • it the result of print_(); Commented May 8, 2015 at 21:23
  • pint_r($this->fetchSemestres); Commented May 8, 2015 at 21:23
  • the foreach loop gives me nothing Commented May 8, 2015 at 21:24

1 Answer 1

3

Try this

class Database extends PDO{
    public function __construct(){
        parent::__construct('mysql:host=localhost;dbname=planingexams', 'root', '');
    }
}

I tested your code locally and added

var_dump($stmt->errorInfo());

This gave me:

array(3) {
  [0] =>
  string(5) "00000"
  [1] =>
  int(1046)
  [2] =>
  string(20) "No database selected"
}

So after taking a good look at the database connection it seems you had to use = and not : to assign the values.

See:

$dbh = new PDO("pgsql:host=$host;port=5432;dbname=$db;user=$user;password=$pass");

From

http://php.net/manual/en/class.pdostatement.php

Sign up to request clarification or add additional context in comments.

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.