PHP OOP: How to get database rows as objects? - php

I can do this when selecting a single row fine but cant quite get my head around doing this for multiple rows of data.
For the single row I simply instantiate a new object that does a number of operations behind the scenes that bascially produces a row from the database as our object.
Example:
$object = new Classname($param);
foreach($object->row as $key=>$value) {
echo $key.":".$value."\n";
}
//output
id:1
firstname:steve
lastname:took
etc...
Any clever people here able to point me in the right direction please?
NOTE: just want to be able to create an object for each row rather than the one object with nested arrays
EDIT: sorry $object->row is a member of the class that stores selected row from the database

If I got you the answer is pretty simple mysql_fetch_object
Example:
while ($row = mysql_fetch_object($result)) {
echo $row->user_id;
echo $row->fullname;
}

Why don't you consider to use an ORM (Object Relational Mapper), like Doctrine or Propel?
I prefer Doctrine: http://www.doctrine-project.org/
Enjoy! :)

Here is an example
class users extends db {
public $users_id = 0;
public $users_group = 0;
public $users_firstname = 0;
public $users_lastname = 0;
public function open($id) {
if (is_numeric($id)) {
$sql = "SELECT * FROM users WHERE users_id = '$id'";
$res = parent::DB_SELECT($sql);
if (mysql_num_rows($res) <> 1) {
return 0;
}
} else {
$sql = "SELECT * FROM users " . $id;
$res = parent::DB_SELECT($sql);
if (mysql_num_rows($res) <= 0) {
return 0;
}
}
$data = array();
while ($row = mysql_fetch_array($res)) {
$this->users_id = $row['users_id'];
$this->users_group = $row['users_group'];
$this->users_firstname = $row['users_firstname'];
$this->users_lastname = $row['users_lastname'];
$data[] = (array) $this;
}
return $data;
}
public function setUsersId($users_id) { $this->users_id = addslashes($users_id); }
public function getUsersId() { return stripslashes($this->users_id); }
public function setUsersGroup($users_group) { $this->users_group = addslashes($users_group); }
public function getUsersGroup() { return stripslashes($this->users_group); }
public function setUsersFirstname($users_firstname) { $this->users_firstname = addslashes($users_firstname); }
public function getUsersFirstname() { return stripslashes($this->users_firstname); }
public function setUsersLastname($users_lastname) { $this->users_lastname = addslashes($users_lastname); }
public function getUsersLastname() { return stripslashes($this->users_lastname); }
}

You could use MySQLi.
// Connect
$db = new mysqli('host', 'user', 'password', 'db');
// Query
$users = $db->query('SELECT * from users');
// Loop
while($user = $users->fetch_object()) {
echo $users->field;
}
// Close
$users->close();
$db->close();
More info here: http://php.net/manual/en/book.mysqli.php

Related

Accessing class properties in PHP OOP

I am new in PHP OOP and was wondering if someone could help me with this.
I have a basic class with one method which returns data from database. Currently I am calling the method which displays everything inside the function.
Here is my class Definition:
class Products{
//properties
public $familyName = "";
public $familyProduct = "";
//Methods
public function getFamily($catId){
global $conn;
$sql = "SELECT * FROM product_family WHERE catID = '$catId'";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo "<li>".$row['familyName']."</li>";
echo "<li>".$row['familyProduct']."</li>";
}
}
}
}
Here is how I call the method:
$Products = new Products;
$Products->getFamily( 4 );
This works however, how can I assign each data coming from database ( ex familyName, familyProduct ) into variables inside class implementation and then access them individually where ever I need to. Something like this:
$Products = new Products;
$Products->familyName;
$Products->familyProduct;
I have empty properties but I am not sure how can I assign values to them coming from the loop and then return them each.
Thanks,
There are view things I would change in your Code.
Don't make Properties public use use Getters and Setters.
This will protect you Object from being used the wrong way e.g. now you can't change the familyName from outside: $products->familyName = "some value" because this would make the data of the object corrupt.
global $conn; is a no go in OOP use the construct of the Object,
in your case $products = new Products($conn);
Now you can set a Cat ID $products->setCatId(4); and read the result
$familyName = $products->getFamilyName(); or $familyProduct = $products->getFamilyProduct();
If you have more than one result you will get an array, if catId will always result one row you can delete this part. If you learn more about OOP you will find out that the hole SQL stuff can be done with a separate Object, but this is off Topic.
class Products
{
// Properties
protected $conn;
protected $catId;
protected $familyName;
protected $familyProduct;
public function __construct($conn)
{
$this->conn = $conn;
}
// set Cat ID and get date
public function setCatId($catId)
{
$this->catId = (int) $catId;
$this->getDate();
}
public function getCatId()
{
return $this->catId;
}
// get Family Name
public function getFamilyName()
{
return $this->familyName;
}
// get Family Product
public function getFamilyProduct()
{
return $this->familyProduct;
}
// get date
protected function getDate()
{
$sql = "SELECT * FROM product_family WHERE catID = '$this->catId'";
$result = $this->conn->query($sql);
// Default if no result
$this->familyName = null;
$this->familyProduct = null;
// if one Result
if ($result->num_rows == 1)
{
$row = $result->fetch_assoc();
$this->familyName = $row['familyName'];
$this->familyProduct = $row['familyProduct'];
}
if ($result->num_rows > 1)
{
$this->familyName = [];
$this->familyProduct = [];
while ($row = $result->fetch_assoc())
{
$this->familyName[] = $row['familyName'];
$this->familyProduct[] = $row['familyProduct'];
}
}
}
}

Load specific data from array

So i have this class for loading data from my MySQL database :
class Db {
protected static $connection;
public function connect() {
if(!isset(static::$connection)) {
$config = parse_ini_file('config.ini');
static::$connection = new mysqli('localhost',$config['username'],$config['password'],$config['dbname']);
}
if(static::$connection === false) {
return false;
}
return static::$connection;
}
public function query($query) {
return $this->connect()->query($query);
}
public function select($query) {
$rows = array();
$result = $this->query($query);
if($result === false) {
return false;
}
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function error() {
return $this->connect()->error;
}
public function quote($value) {
return "'" . $this->connect()->real_escape_string($value) . "'";
}
}
I use that class like this :
$db = new Db();
$rows = $db -> select("SELECT name, shortlink FROM `test` WHERE id=3");
It gives me an array with the data.
The problem is that i want to pull out specific data, for example the shortlink field.
How do i do that? I have tried echo $rows['shortlink'], but that gives me the following error :
Undefined index: shortlink
So how do I print specific data?
Your returned $rows columns is an array of associative arrays, to pull out shortlink data returned from the query you have to do something like this:
foreach($rows as $row) {
echo $row['shortlink'];
}

PHP OOP query is not executing

I am using PHP with OOP to select rows from the database (MySQL).
When I execute the query, it returns an empty row.
Here is the classe I am using:
<?php
class EmploiManager
{
private $_db;
public function __construct($db)
{
$this->setDb($db);
}
public function category($category)
{
$q = $this->_db->prepare('SELECT * FROM DemandeEmploi WHERE category = :category');
$q->execute(array('category' =>$category));
$donnees = $q->fetch(PDO::FETCH_ASSOC);
return new Emploi($donnees);
}
public function setDb(PDO $db)
{
$this->_db = $db;
}
}
$type = $_GET['category'];
$manager = new EmploiManager($db);
$row = $manager->category($type);
foreach ($row as $demandeE)
{
?>
<div class="list"><h4><? echo $demandeE->title();?></h4> </div>
<?php
}
?>
Can any one tell me what's wrong with that code?
Thanks!
It's my bad, I didn't use a loop to select all the rows.
I corrected the code and it works fine now, here is what it looks like:
public function category($category)
{
$datas = array();
$q = $this->_db->prepare('SELECT * FROM DemandeEmploi WHERE category = :category');
$q->execute(array('category' =>$category));
while ($donnees = $q->fetch(PDO::FETCH_ASSOC))
{
$datas[] = new Emploi($donnees);
}
return $datas;
}
$q->fetch() just returns one row of the results. If you want all the results, you must use $q->fetchAll().
Since you specified PDO::FETCH_ASSOC, the elements of $row will be associative arrays, not objects; aren't you getting errors saying that you're trying to call a method on a non-object? So $demandeE->id() should be $demandeE['id'], and $demandeE->title() should be $demandeE['title'].
Alternatively, you could specify PDO::FETCH_OBJ. Then, the values will be properties, not methods, so it should be $demandeE->id and $demandeE->title (no parentheses).

Fetching rows using PHP OO Class

I have made a class function which will get rows from a table in my database along with an optional argument. This works when getting a single row however I cant get this to work when multiple rows are returned.
Here is what is in the Users class
public function getUsers($filter="") {
$Database = new Database();
if($filter == 'male')
$extra = "WHERE gender = 'm'";
$sql = "SELECT *
FROM users
$extra";
if ($Database->query($sql))
return $Database->result->fetch_assoc();
else
return false;
}
Database Class
class Database {
private $db = array();
private $connection;
private $result;
public function __construct() {
$this->connect();
}
public function connect() {
$this->connection = mysqli_connect('mysql.com', 'username', 'pass');
mysqli_select_db($this->connection, 'database');
}
public function query($sql) {
$this->result = mysqli_query($this->connection, $sql);
return $this->result;
}
This is the code used to try and display the rows
if ($student = $User->getUsers($filter)) {
echo "<table>\n";
echo "<tr><td>Col 1</td><td>Col 2</td><td>Col 3</td><td>Col 4</td><td></td><td></td></tr>";
foreach($student as $row) {
echo "<tr>";
echo "<td>$row[col1]</td>";
echo "<td>$row[col2]</td>";
echo "<td>$row[col3]</td>";
echo "<td>$row[col4]</td>";
echo "<td>$row[col5]</td>";
echo "<td>$row[col6]</td>";
echo "</tr>\n";
}
echo "</table>";
}
(I'm learning OO PHP, bear with me)
I'm still learning OOP but I have used this:
protected $connection, $result, $_numRows;
public function query($sql)
{
$this->result = mysql_query($sql, $this->connection);
$this->_numRows = mysql_num_rows($this->result);
}
/*
* #desc get result af query
*
* #returns string $result
*/
public function getResult()
{
return $this->result;
}
/*
* #desc Return rows in table
* #returns int $_numRows
*/
public function numRows()
{
return $this->_numRows;
}
/*
* #desc Count rows and add to array
* #return string $rows array
*/
public function rows()
{
$rows =array();
for ($x=0; $x < $this->numRows(); $x++) {
$rows[] = mysql_fetch_assoc($this->result);
}
return $rows;
}
Then you could use something like this to get the rows:
public function getUsers($filter="") {
$Database = new Database();
if($filter == 'male')
$extra = "WHERE gender = 'm'";
$sql = "SELECT *
FROM users
$extra";
if ($this->numRows() == 0) {
echo "No rows found";
} else {
foreach ($this->rows() as $b) {
$c = array('something' => $b['col']);
}
return $c;
}
Modify the last part to suit your needs.
It's not clear in your code where $result comes from...
You should call the fetch_assoc() method of an object returned by:
$mysqli->query($query)
Why are you using $result->fetch_assoc() twice? you are returning an array.. you should deal with $student.

How to convert Mysqli results into an array in OO Php

I want to retrieve data from a table in database and display the result in an array in the form below.
array("1"=>"Value 1", "2"=>"value2")
Here is the function I tried using but I get error when I try to display the array. Please I need help on this. I'm new to OO Php.
<?php
class query {
public function listfields (){
$result = $this->mysqli->query("SELECT id, name FROM fields", MYSQLI_USE_RESULT);
while($row=$result->fetch_assoc()){
$this->fields[$row["id"]] = $row["name"];
}
$result->free();
}
public function fields(){
return $this->fields;
}
}
$list = new query;
$list->listfields();
$field1 = $list->fields();
echo $field1;
?>
Instead of your function fields, you will need a property fields, which you can access.
Furthermore i suggest using getters and setters instead of a public property, im sure you will find out how.
This will return the Data in form array("1"=>"Value 1", "2"=>"value2").
class query {
public $fields;
public function fillfields ()
{
$result = $this->mysqli->query("SELECT id, name FROM fields", MYSQLI_USE_RESULT);
while($row=$result->fetch_assoc()){
$this->fields[] = $row["name"];
}
$result->free();
}
$list = new query;
$list->fillfields();
$field1 = $list->fields[1];
echo $field1;
Try This.
<?php
class query {
public function listfields (){
$fields = array();
$rowcnt =1;
$result = $this->mysqli->query("SELECT id, name FROM fields", MYSQLI_USE_RESULT);
while($row=$result->fetch_assoc()){
$this->fields[$row["id"]] = $row["name"];
//$this->fields[$rowcnt] = $row["name"]; // if you want different indexing.
$rowcnt++;
}
$result->free();
}
public function fields(){
return $this->fields;
}
}
$list = new query();
$list->listfields();
$field1 = $list->fields();
var_dump($field1);
?>

Categories