How to convert Mysqli results into an array in OO Php - 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);
?>

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'];
}
}
}
}

return an array of objects

want from a method return an array of objects, what is the best way
retrieving data from the db and then populate a list of objects to be returned.
<?php
class DataObject{
public function GetObjetList(){
// Connect to the database server
$dbh = new PDO("mysql:host=localhost;dbname=bookdb", "webuser", "secret");
// Execute the query return 1200 register
$stmt = $dbh->query('SELECT sku, title FROM products ORDER BY title');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$sku = $row['sku'];
$title = $row['title'];
return something?? --> how to??
}
}
?>
regards!
PDO already has a fetch mode that returns objects.
Change your code to this:
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
class DataObject
{
public function __construct($pdo)
{
$this->db = $pdo;
}
public function GetObjetList()
{
$sql = 'SELECT sku, title FROM products ORDER BY title';
return $this->db->query($sql)->fetchAll(PDO::FETCH_OBJ);
}
}
Put the return after the while, not inside, use FETCH_OBJ and an array:
$rows = array();
$rows = $stmt->fetchAll(PDO::FETCH_OBJ);
return $rows;

Assigning SQL Statement to Class Variable

I stated to build up my Database Class.
Here is a part of my database class.
public function query($sql)
{
return $this->getPdo()->query($sql);
}
My Class is working but i want to improve it.
This is external part of class:
$db = new Database();
$q = $db->query('SELECT * FROM table');
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$results[] = $r;
}
echo "<pre>";
print_r($results);
echo "</pre>";
I want to get while part inside database class like
public function query($sql)
{
return $this->getPdo()->query($sql);
}
public function getAll() {
while($r = $this->query($sql)->fetch(PDO::FETCH_ASSOC)){
$results[] = $r;
}
return $results;
}
But i know this part is wrong : $this->query($sql)->fetch(PDO::FETCH_ASSOC); How can i fix it ? I have to declare a class varible like $sql, and i have to assign sql statement to $sql varible.
But i couldn't. How can i do that ?
$q = $db->query('SELECT * FROM table');
$results = $q->fetchAll();
echo "<pre>";
print_r($results);
echo "</pre>";
One of your biggest problems is that when you write
public function getAll() {
while($r = $this->query($sql)->fetch(PDO::FETCH_ASSOC)){
$results[] = $r;
}
return $results;
}
you are causing the database to run the query with each iteration of the loop.
To correct the code as it is defined simply run the query outside of the loop then use fetch as the loop condition:
public function getAll() {
$stmt = $this->query($sql);
while($r = $stmt->fetch(PDO::FETCH_ASSOC)){
$results[] = $r;
}
return $results;
}
Another problem that is probably probably causing you grief is that the $sql value appears to be coming from out of thin air. You should pass it into your getAll function to have access to it.
To avoid all this noise you might want to just follow #YourCommonSense's suggestion and use the available PDO getAll method.
public function getAll($sql){
return $this->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}
You need to pass the $sql parameter to your getAll() method, and then use return to get the result back out. So this method becomes:
public function getAll($sql) {
while($r = $this->query($sql)->fetch(PDO::FETCH_ASSOC)){
$results[] = $r;
}
return $results;
}
Then you use it externally like:
$db = new Database();
$results = $db->getAll('SELECT * FROM table');
echo "<pre>";
print_r($results);
echo "</pre>";

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).

PHP OOP: How to get database rows as objects?

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

Categories