I'm using singleton design pattern for connect to database.In below I run a query on my database and I want to fetch data from this query :
$db = Db::connect();
$query = $db->query("SELECT * FROM myTable");
while ($row = ???) {
// echo 'myTable' fields here. like = echo $row['someField']
}
my Db class:
class Db
{
private $connection;
private static $instance;
private function __construct()
{
$host = "localhost";
$user = "root";
$pass = "";
$name = "dictionary";
$this->connection = new mysqli($host, $user, $pass, $name);
}
public static function connect()
{
if (self::$instance == null) {
self::$instance = new Db();
}
return self::$instance;
}
public function query($sql)
{
$result = $this->connection->query($sql);
$records = array();
while ($row = $result->fetch_assoc()) {
$records[] = $row;
}
return $records;
}
}
What should I write instead of ??? in my code ?
Replace
while ($row = ???) {
// echo 'myTable' fields here. like = echo $row['someField']
}
with
foreach($query as $row)
echo $row['someField'];
Note : You may want to rename $query to $rows, for example, since this is a more appropriate name.
In each iteration of while loop, use array_shift() function to get the current row from the result set, like this:
while ($row = array_shift($query)) {
echo $row['someField'] . "<br />";
}
Here's the reference:
array_shift()
Your call to your Database class's ->query() method returns an array of result rows. So all you need to do is process that array like any other
$db = Db::connect();
$rows = $db->query("SELECT * FROM myTable");
foreach ($rows as $row ) {
echo $row['someField'];
}
Related
I have a Class in that I want to create a dynamic property (or a dynamic variable) to collect Tables list form the database. here is the code
include_once($base_dir.'./config/index.php');
class TableList{
private $con;
public $Tables_in_sample;
public function __construct($con){
$this->conn = $conn;
}
public function ListTables(){
$query ="SHOW TABLES";
$stmt = $this->connection->prepare($query);
$stmt->execute();
return $stmt;
}
I called it
include_once($base_dir.'./config/index.php');
include_once('./tablelist.php');
$dbclass = new DBClass();
$conn = $dbclass->getConnection();
$post = new TableList($conn);
$stmt = $post->ListTables();
$count = $stmt->rowCount();
if($count > 0){
echo "<html><body><ul>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo = "<li>".$post->Tables_in_jsonapi."</li>";
}
echo "</ul></body></html>";
}
Here I got the list of the tables for the DB sample. But I need to get a property dynamically something like this
public $Tables_in_sample;
to
public $Tables_in_.$this->dbname;
and collect in
echo "<html><body><ul>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo = "<li>".$post->Tables_in_sample."</li>"; //here
}
You don't need dynamic properties, you don't need extract(), you don't need the class TableList.
$result = $pdo->query('SHOW TABLES')->fetchAll(\PDO::FETCH_COLUMN);
echo "<html><body><ul>";
foreach ($result as $table) {
echo '<li>' . $table . '</li>';
}
echo "</ul></body></html>";
I tried to get followers from MySQL usingy this class
class get_followers {
public $followers_arr = array();
public function __construct($user_id) {
$query = "select * from followsystem where following ='$user_id'";
$q = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($q);
if ($count > 0) {
while ($row = mysql_fetch_assoc($q)) {
array_push($this->followers_arr, $row['userid']);
}
}
return $this->followers_arr;
}
}
Then I initialize this class
$fol = new get_followers($userid);
$fol_arr = json_encode($fol);
echo $fol_arr;
Then I get
{"followers_arr":["1234","456"]}
but what i want want just to get this
["1234","456"]
How is that works?
I don't think you understand how constructors work. You can't return a value from a constructor because it's just used to instantiate the object. When you're doing $fol_arr = json_encode($fol); you're actually encoding the entire object, not it's return value.
If you really want to use a class to do this, you should add a method to the class and use that, like this:
class Followers {
public $followers_arr = array();
public $user_id = null;
public function __construct($user_id) {
$this->user_id = $user_id;
}
public function get()
{
$query = "select * from followsystem where following ='{$this->user_id}'";
$q = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($q);
if ($count > 0) {
while ($row = mysql_fetch_assoc($q)) {
array_push($this->followers_arr, $row['userid']);
}
}
return $this->followers_arr;
}
}
And use it like this:
$fol = new Followers($userid);
$fol_arr = json_encode($fol->get());
echo $fol_arr;
The solution to your problem is to do $fol_arr = json_encode($fol->followers_arr);
Nonetheless, making a class in this case is completely obsolete, since you only make it as a wrapper for a single function you want to execute (called get_followers) Instead of making a class, you could simply make the following:
function get_followers($user_id) {
$followers_arr = [];
$query = "select * from followsystem where following ='$user_id'";
$q = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($q);
if ($count > 0) {
while ($row = mysql_fetch_assoc($q)) {
array_push($followers_arr, $row['userid']);
}
}
return $followers_arr;
}
$fol = get_followers($userid);
$fol_arr = json_encode($fol);
echo $fol_arr;
There is no need to put it in a class unless the class serves the purpose of combining a few functions and variables to create a behaviour.
I'm a little bit stumped. I've never messed around with objects and classes too much in PHP, but someone recommended that I re-did some code with it.
What I'm trying to do is make $auctions an object property, while saving all of the row data to it.
Right now, I do echo $auctions[1]['title']; to echo out the listing where id=1 title.
And I wish to re-create it so that it would be an object.
Here's my current code,
$sqlquery = "SELECT * FROM auctions";
if ($result = $db->query($sqlquery)) {
while ($row = $result->fetch_assoc()) {
$auctions[$row['id']]['id'] = $row['id'];
$auctions[$row['id']]['title'] = $row['title'];
$auctions[$row['id']]['featured_image'] = $row['featured_image'];
$auctions[$row['id']]['description'] = $row['description'];
$auctions[$row['id']]['date'] = $row['date'];
$auctions[$row['id']]['location'] = $row['location'];
$auctions[$row['id']]['highlights'] = $row['highlights'];
$auctions[$row['id']]['catagories'] = $row['catagories'];
$auctions[$row['id']]['notes'] = $row['notes'];
$auctions[$row['id']]['terms'] = $row['terms'];
$auctions[$row['id']]['contact'] = $row['contact'];
}
}
I don't have any idea on how to accomplish this, but if someone could give me a little hint to point me in the direction, it would be very appreciated! :)
Create a class auctions with all the needed member variables that you listed above (e.g. id, title, feature_image etc.). Next create a setter method (e.g. setValues()) inside the class that can accept the $row.
$sqlquery = "SELECT * FROM auctions";
$auction = new Auctions();
if ($result = $db->query($sqlquery)) {
while ($row = $result->fetch_assoc()) {
$auction->setValues( $row );
// do something with $auction...
}
}
Instead of a explicit setter method, You may also use magic method __set().
I'll write a minimal snippet here now:
First let create a base class for all our models:
abstract class Model() {
public $fields = array();
private $data = array();
public function setValues(array $vals) {
foreach($vals as $key=>$value) {
if (in_array($key, static::$fields)) {
$this->data[$key] = $value;
}
}
}
public function get($key) {
if (in_array($key, static::$fields) && isset($this->data[$key])) {
return $this->data[$key];
}
return null; // or throw Exception)
}
}
Next, create some concrete model:
class Users extends Model {
public static $fields = array('id', 'name');
}
And we can use it now:
$users = array();
$sqlquery = "SELECT * FROM Users";
if ($result = $db->query($sqlquery)) {
while ($row = $result->fetch_assoc()) {
$user = new User();
$user->setValues($row);
$users[] = $user;
}
}
You can to add some user-specific methods (aka login) to User model directly..
Also you should to implement other Model methods, like getById, getByQuery, save and other, and no use direct sql queries, because models can do this itself
You can store the values in a object like
$obj = new stdClass; //create new standard class object
$obj->id = $row['id']; //assign property value
$obj->title = $row['title'];
//further properties
... and so on
You really are trying to create an array of objects (instances of a type containing info for one auction. Something like this:
class Auction
{
var $id = null;
var $title = null;
var $featured_image = null;
var $description = null;
var $date = null;
var $location = null;
var $highlights = null;
var $catagories = null;
var $notes = null;
var $terms = null;
var $contact = null;
}
$sqlquery = "SELECT * FROM auctions";
if ($result = $db->query($sqlquery)) {
while ($row = $result->fetch_assoc()) {
$newAuction = new Auction();
$newAuction->id = $row['id'];
$newAuction->title = $row['title'];
$newAuction->featured_image = $row['featured_image'];
$newAuction->description = $row['description'];
$newAuction->date = $row['date'];
$newAuction->location = $row['location'];
$newAuction->highlights = $row['highlights'];
$newAuction->catagories = $row['catagories'];
$newAuction->notes = $row['notes'];
$newAuction->terms = $row['terms'];
$newAuction->contact = $row['contact'];
$auctions[$row['id']] = $newAuction;
}
}
Please note that you have misspelled "categories" (you have "catagories").
I advice you to use PDO
class Auction
{
public $id;
public $title;
public $featured_image;
public $description;
public $date;
public $location;
public $highlights;
public $catagories;
public $notes;
public $terms;
public $contact;
// This will return $all being an array of objects of class Auction
public static function getAll() {
$query = "SELECT * FROM auctions";
$statement = $db->prepare($query);
if (!$statement->execute())
return false;
$all = $statement->fetchAll(PDO::FETCH_CLASS, "Auction");
return $all;
}
}
I got below class to fetch records in database, how can use foreach to loop all data in page?
class User{
public function get_user_listing($user_id, $mysqli){
$sql = $mysqli->query("SELECT * FROM `listing` WHERE user_id='".$user_id."'");
if($sql->num_rows > 0){
return $query->result();
}else{
return false;
}
}
}
in my page, if I call:
$user = new User;
$listing = $user->get_user_listing($user_id, $mysqli);
foreach(listing as $value){
echo $value->table_field;
}
But I think that is not a correct way.
You need to return the actual result $sql:
if($sql->num_rows > 0){
return $sql;
} else {
return false;
}
Since you are returning a result set you need to fetch rows:
$user = new User;
$listing = $user->get_user_listing($user_id, $mysqli);
while($row = $listing->fetch_object()){
echo $row->table_field;
}
Or you could add the fetch loop to the class function and return an array of $row[] objects.
Also, I would make some changes here:
private $mysqli;
public function __construct($mysqli) {
$this->mysqli = $mysqli;
}
public function get_user_listing($user_id) {
$mysqli = $this->mysqli;
//or just use $sql = $this->mysqli->query("SELECT * FROM `listing` WHERE `user_id` = '$user_id'");
//etc...
}
Then:
$user = new User($mysqli);
$listing = $user->get_user_listing($user_id);
Better use a prepared statement to protect from SQL injection. And check the returned value from get_user_listing for false or undef.
public function get_user_listing($user_id, $mysqli){
$sql = "SELECT * FROM `listing` WHERE user_id=?";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
return $result;
}
}
$user = new User;
$result = $user->get_user_listing($user_id, $mysqli);
if(isset($result))
{
while ($row = $result->fetch_assoc()) {
print $row['table_field'];
}
/* free result set */
$result->free();
}
I have 3 files:
DB.class.php - which handles all the databases.
Site.class.php - contains a function to return the latest entries in a database.
index.php - trying to print the array passed.
I am trying to pass an array into index.php from Site.class.php which is using a function from DB.class.php to put the mysql results into an associative array.
index.php:
<?php
// index.php
include 'classes/Site.class.php';
$site = new Site();
print_r($site->latestBookmarks());
?>
Site.class.php:
<?php
// Site.class.php
require_once 'DB.class.php';
class Site {
function latestBookmarks() {
$result = mysql_query("SELECT url, title FROM site ORDER BY id DESC");
$db = new DB();
return $db->processRowSet($result);
}
}
?>
DB.class.php:
<?php
// DB.class.php
class DB {
protected $db_name = "project";
protected $db_user = "root";
protected $db_pass = "root";
protected $db_host = "localhost";
// Open up a connection to the database.
public function connect() {
$connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
mysql_select_db($this->db_name);
return true;
}
// Takes a MySQL row and returns an associative array where the keys in the array are the column names in the row set.
public function processRowSet($rowSet, $singleRow=false) {
$resultArray = array();
while ($row = mysql_fetch_assoc($rowSet)) {
array_push($resultArray, $row);
}
if ($singleRow === true)
return $resultArray[0];
return $resultArray;
}
// Select rows from the database.
public function select($table, $where) {
$sql = "SELECT * FROM $table WHERE $where";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1)
return $this->processRowSet($result, true);
return $this->processRowSet($result);
}
// Update a current row in the database.
public function update($data, $table, $where) {
foreach ($data as $column => $value) {
$sql = "UPDATE $table SET $column = $value WHERE $where";
mysql_query($sql) or die(mysql_error());
}
return true;
}
// Insert a new row into the database.
public function insert($data, $table) {
$columns = "";
$values = "";
foreach ($data as $column => $value) {
$columns .= ($columns == "") ? "" : ", ";
$columns .= $column;
$values .= ($values == "") ? "" : ", ";
$values .= $value;
}
$sql = "INSERT INTO $table ($columns) VALUES ($values)";
mysql_query($sql) or die(mysql_error());
return mysql_insert_id();
}
}
?>
A few problems I noticed:
You run a query in function latestBookmarks before you connect to the db;
In your function connect you connect to a database, but the result is discarded immediately, $connection is lost as soon as the function finishes.
You have no connection to the database when you run this line:
$result = mysql_query("SELECT url, title FROM site ORDER BY id DESC");
You will need to adjust your code to send the query string to the DB instance for processing. You can add a method to DB to execute mysql_query, and pass the query in like from Site:: latestBookmarks() like this:
$db = new DB();
$db->executeQuery("SELECT url, title FROM site ORDER BY id DESC");
return $db->processRowSet();