php - PDO query class -


i'm tinkering class 'should' allow me execute fetchall query , display results within foreach statement. assume working correctly have no errors. foreach - must problem? how foreach results gained $connect->query()? i'm new using database oop framework in functions along wrong lines completely.

 <?  error_reporting(1);  class dbconnect {  private $host; private $database; private $username; private $password;  private $pdo; private $error;      public function __construct() {          $this->host     = "localhost";              // host         $this->database = "images";                 // database name         $this->username = "*";              // username         $this->password = "*";  // password         $options  = array(             pdo::mysql_attr_init_command => 'set names utf8'         );          try {             $this->pdo = new pdo("mysql:host={$this->host};dbname={$this->dbname};charset=utf8", $this->username, $this->password, $options);         }         catch(pdoexception $e) {             $this->error = $e->getmessage();         }      }      public function query($query) {          try {             $stmt = $this->pdo->prepare($query);             $stmt->execute();          } catch(pdoexception $ex) {              die("failed run query: " . $ex->getmessage());          }           $rows = $stmt->fetchall();         return $rows;      }  }  $connect = new dbconnect; $rows = $connect->query("select * photos"); foreach($rows $row):     print $row['id']; endforeach;    ?> 

the $rows variable you're declaring inside query not accessible outside, local function. likely, want return results caller:

$rows = $stmt->fetchall(); return $rows; // return value function... 

and have caller capture return value in own variable:

$rows = $connect->query("select * images"); // ... received caller foreach($rows $row): 

also check out dougjore's answer, you're mixing $this->stmt , $stmt inside query method.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -