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;
}
}
Related
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'];
}
I am wondering my class property $friend_username does not returning its value either it is public.
update
class Feed {
public static $friend_username;
// ONLINE FRIENDS LOGIC
public function online_friends(){
$friendsHTML = '';
$countOnlineFriends = '';
if(GetFriends($GLOBALS['log_username']) != false) {
$all_friends = GetFriends($GLOBALS['log_username']);
$orLogic = '';
foreach($all_friends as $key => $user){
if(IsBlocked($GLOBALS['log_username'],$user,true) == false){
$orLogic .= "username='$user' OR ";
}
}
$orLogic = chop($orLogic, "OR ");
$sql = "SELECT username, avatar, logged_in FROM users WHERE ($orLogic) AND logged_in = 1";
$query = mysqli_query($GLOBALS['db_conx'], $sql);
$friend_loggedIn = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$this->friend_username = $row["username"];
$friend_avatar = $row["avatar"];
$friend_loggedIn[] = $row["logged_in"];
$friend_pic = userImage($this->friend_username,$friend_avatar,'42','42',$link = false,$up = true);
$friendsHTML .= '<li><a href="#" onClick="chatbox(\''.$this->friend_username.'\',\''.getName($this->friend_username,true).'\');return false;">'.$friend_pic.' '.getName($this->friend_username,true).'</li>';
$countFriends = count($friend_loggedIn);
$countOnlineFriends = ($countFriends > 0) ? '<span class="online_friends animated">'.$countFriends.'</span>' : '';
}
}else{
$friendsHTML = 'No friends';
}
return "$countOnlineFriends|$friendsHTML";
}
public function update_chat() {
$id = '';
$messages = '';
$randUser = '';
$user = sanitize($this->friend_username);
$sql = "SELECT * FROM pm_chat WHERE (sender='$GLOBALS[log_username]' AND receiver='$user') OR (sender='$user' AND receiver='$GLOBALS[log_username]') ORDER BY datetime DESC";
$result = mysqli_query($GLOBALS['db_conx'],$sql) or die(mysqli_error($GLOBALS['db_conx']));
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$user1 = $row['sender'];
$user2 = $row['receiver'];
$message = parseData($row['message']);
$did_read = $row['did_read'];
$datetime = $row['datetime'];
if ($user1 != $GLOBALS['log_username']) {
$randUser = $user1;
}elseif ($user2 != $GLOBALS['log_username']) {
$randUser = $user2;
}
if ($user1 == $GLOBALS['log_username'] && $user2 != $GLOBALS['log_username']) {
$messages .= '<li class="row" id="pm_row_'.$id.'"><div class="me">'.$message.'</div></li>';
}else{
$messages .= '<li class="row" id="pm_row_'.$id.'">'.userImage($randUser,getAvatar($randUser),28,28,$link = true,$up = true).'<div class="userfrnd">'.$message.'</div></li>';
}
}
return $this->friend_username."$id|$messages|$randUser";
// this is for ^^^^^^^ testing purpose
}
}
here is the other file where I am calling the other class method. And its content-type is text/event-stream
class update_chat extends SSEEvent {
public function update(){
//Here's the place to send data
$feed = new Feed();
return $feed->update_chat();
}
public function check(){
//Here's the place to check when the data needs update
return true;
}
}
Any idea or suggestion why this problem persist ?
thanks in advance.
If you are calling bar() in another file and then creating a new Foo in otherClass, you are not referencing the same instance of Foo. Either make $friend_username static and call it statically
public static $friend_username;
public function update(){
//Here's the place to send data
return Foo::$friend_username;
}
or at least make the function static
public static function bar() {}
public function update(){
//Here's the place to send data
return Foo::bar();
}
or pass in the instance of Foo to the function
public function update(Foo $Foo){
//Here's the place to send data
return $Foo->bar();
}
If you want to call a static method from within the same class, you have to use the self identifier (self::$var)
class Feed {
public static $friend_username = array();
// ONLINE FRIENDS LOGIC
public function online_friends(){
$friendsHTML = '';
$countOnlineFriends = '';
if(GetFriends($GLOBALS['log_username']) != false) {
$all_friends = GetFriends($GLOBALS['log_username']);
$orLogic = '';
foreach($all_friends as $key => $user){
if(IsBlocked($GLOBALS['log_username'],$user,true) == false){
$orLogic .= "username='$user' OR ";
}
}
$orLogic = chop($orLogic, "OR ");
$sql = "SELECT username, avatar, logged_in FROM users WHERE ($orLogic) AND logged_in = 1";
$query = mysqli_query($GLOBALS['db_conx'], $sql);
$friend_loggedIn = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
array_push(self::$friend_username, $row["username"]);
$friend_avatar = $row["avatar"];
$friend_loggedIn[] = $row["logged_in"];
$friend_pic = userImage(self::$friend_username,$friend_avatar,'42','42',$link = false,$up = true);
$friendsHTML .= '<li><a href="#" onClick="chatbox(\''.self::$friend_username.'\',\''.getName(self::$friend_username,true).'\');return false;">'.$friend_pic.' '.getName(self::$friend_username,true).'</li>';
$countFriends = count($friend_loggedIn);
$countOnlineFriends = ($countFriends > 0) ? '<span class="online_friends animated">'.$countFriends.'</span>' : '';
}
}else{
$friendsHTML = 'No friends';
}
return "$countOnlineFriends|$friendsHTML";
}
public function update_chat() {
$id = '';
$messages = '';
$randUser = '';
$user = Feed::$friend_username;
foreach ($user as $key => $value) {
$user[$key] = sanitize($value);
}
//I leave it up to you to figure out how you want to deal with the array of users in this next line
$sql = "SELECT * FROM pm_chat WHERE (sender='$GLOBALS[log_username]' AND receiver='$user') OR (sender='$user' AND receiver='$GLOBALS[log_username]') ORDER BY datetime DESC";
$result = mysqli_query($GLOBALS['db_conx'],$sql) or die(mysqli_error($GLOBALS['db_conx']));
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$user1 = $row['sender'];
$user2 = $row['receiver'];
$message = parseData($row['message']);
$did_read = $row['did_read'];
$datetime = $row['datetime'];
if ($user1 != $GLOBALS['log_username']) {
$randUser = $user1;
}elseif ($user2 != $GLOBALS['log_username']) {
$randUser = $user2;
}
if ($user1 == $GLOBALS['log_username'] && $user2 != $GLOBALS['log_username']) {
$messages .= '<li class="row" id="pm_row_'.$id.'"><div class="me">'.$message.'</div></li>';
}else{
$messages .= '<li class="row" id="pm_row_'.$id.'">'.userImage($randUser,getAvatar($randUser),28,28,$link = true,$up = true).'<div class="userfrnd">'.$message.'</div></li>';
}
}
return Feed::$friend_username."$id|$messages|$randUser";
// this is for ^^^^^^^ testing purpose
}
}
Well, since your are using the method mysqli_fetch_array, could it be that more than one element is returned and that the last one is empty?
BTW, I don't understand why you are making a single variable attribution inside a while statement. Supposedly, the last running (if some) will overwrite the variable's value.
Another observation, on the second code. If you are calling the bar() method right off the bat, shoudn't the variable be empty anyway? I understand that $friend_username is only assigned inside the foo() method.
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 working on an advanced search but got error
Fatal error: Cannot access empty property *$this->$Personnummer*
Here is my controller:
<?php
include 'c:/wamp/www/mvc/model/SearchProcessor.php';
// if the user clicks the submit button, it sends its name values here and if not empty, binds them to $data.
if(isset($_POST['button'])) {
if($_POST['name'] !='');
{
$data['name'] = $_POST['name'];
}
if($_POST['lastname'] !='');
{
$data['lastname'] = $_POST['lastname'];
}
if($_POST['Personnummer_search'] !='');
{
$data['Personnummer'] = $_POST['Personnummer_search'];
}
if($_POST['Kon_search'] !='');
{
$data['Kon_search'] = $_POST['Kon_search'];
}
if($_POST['Anvands_search'] !='');
{
$data['Anvands_search'] = $_POST['Anvands_search'];
}
if($_POST['Lan_search'] !='');
{
$data['Lan_search'] = $_POST['Lan_search'];
}
if($_POST['Processormodell_search'] !='');
{
$data['Processormodell_search'] = $_POST['Processormodell_search'];
}
if($_POST['Sida_search'] !='');
{
$data['Sida_search'] = $_POST['Sida_search'];
}
if($_POST['utlamnat_search'] !='');
{
$data['utlamnat_search'] = $_POST['utlamnat_search'];
}
if($_POST['ProcessorSerie_search'] !='');
{
$data['ProcessorSerie_search'] = $_POST['ProcessorSerie_search'];
}
if($_POST['Tillverkare_search'] !='');
{
$data['Tillverkare_search'] = $_POST['Tillverkare_search'];
}
$displayResults = new SearchProcessor($db,$data);
$Results = $displayResults->getSearchResult();
Here is the model:
<?php
require_once 'Database.php';
//This class is for searching for patient and their processors
class SearchProcessor extends Database {
private $Personnummer;
private $TheKon;
private $TheLan;
private $name;
private $TheLastname;
private $TheProcessor;
private $TheAnvands;
private $TheSida;
private $TheUtlamnat;
private $TheSerienummer;
private $TheTillverkare;
//The constructor of both the parent and child class
function __construct(mysqli $db, $data)
{
parent::__construct($db);
//set data
$this->setData($data);
// get search result
$this->getSearchResult();
}
//Sets the data
function setData($data)
{
$this->name = $data['name'];
$this->TheLastname = $data['lastname'];
$this->Personnummer = $data['Personnummer'];
$this->TheKon = $data['Kon_search'];
$this->TheAnvands = $data['Anvands_search'];
$this->TheLan = $data['Lan_search'];
$this->TheProcessor = $data['Processormodell_search'];
$this->TheSida =$data['Sida_search'];
$this->TheUtlamnat =$data['utlamnat_search'];
$this->TheSerienummer = $data['ProcessorSerie_search'];
$this->TheTillverkare = $data['Tillverkare_search'];
}
//This function searches each column regarding patient and its processors.
function getSearchResult() {
$where = array();
$where[] = "Patient.Patient LIKE '%".$this->$Personnummer."%'"; //<--- ERROR Cannot access empty property
$where[] = "person.Namn LIKE '%".$this->name."%'";
$where[] = "person.Efternamn LIKE '%".$this->TheLastname."%'";
$where[] = "person.Kon LIKE '%".$this->TheKon."%'";
$where[] = "processorpatient.Sida LIKE '%".$this->TheSida."%'";
$where[] = "person.Lan LIKE '%".$this->TheLan."%'";
$where[] = "processorpatient.Tillverkare LIKE '%".$this->TheTillverkare."%'";
$where[] = "processorpatient.Processor LIKE '%".$this->TheProcessor."%'";
$where[] = "processorpatient.Utlamnat LIKE '%".$this->TheUtlamnat."%'";
$where[] = "processorpatient.Anvands LIKE '%".$this->TheAnvands."%'";
$where[] = "processorpatient.Serienummer LIKE '%".$this->TheSerienummer."%'";
if(count($where)) // here it counts the amount of $where and a extends the query to search deeper into the database.
{
$Data = array();
$sql = "Select * from patient left join person on person.Personnummer = patient.Patient left join processorpatient on processorpatient.patientv = patient.Patient
WHERE ".implode(" AND ",$where);
if(!$result = $this->mysqli->query($sql)) {
throw new exception("Error: Can not execute the query.");
} else {
$Count = $result->num_rows;
if($Count>0)
{
for($i=0; $i<$Count; $i++)
{
$Data[$i] = $result->fetch_assoc();
}
}
}
return $Data;
}
}
}
What I want to be doing is assign user input $_POST[''] to variables $data[''] in the controller. And then pass it the model class that is supposed to bind it with their own private variables in which is giving value to the query. But I'm getting error Cannot access empty property $this->$Personnummer at the model
access variable without $ as like same as you defined above
$this->Personnummer = $data['Personnummer'];
so access this like
$where[] = "Patient.Patient LIKE '%".$this->Personnummer."%'";
the code is as follow:
Class userinfo {
function fetchdatabyemail($email) {
$result=mysql_query(" SELECT * FROM users WHERE email='$email'");
while($row = mysql_fetch_array($result)) {
$name = $row['name'];
$num = $row['num'];
$city = $row['city'];
}
$numrows= mysql_num_rows($result);
}
}
now to get the info I do this :
$info = new userinfo();
$info->fetchdatabyemail('email#email.com');
echo $info->city;
and it doesnt return the info. I think Im doing something wrong any ideas please
do it
public $numrows;
public function fetchDataByEmail($email) {
$result=mysql_query(" SELECT * FROM users WHERE email='$email'");
while($row = mysql_fetch_assoc($result)) {
$fetch[] = $row;
}
$this->numrows = mysql_num_rows($result);
return $fetch;
}
then
$info = new userinfo();
$detail = $info->fetchDataByEmail('email#email.com');
print_r($detail); // return all result array
$info->numrows; // will return number of rows.
Your variable working locally. You need to assign it in class level.
Your code should be:
Class userinfo {
public $name,$city,$num,$numrows;
function fetchdatabyemail($email) {
$result=mysql_query(" SELECT * FROM users WHERE email='$email'");
while($row = mysql_fetch_array($result)) {
$this->name = $row['name'];
$this->num = $row['num'];
$this->city = $row['city'];
}
$this->numrows= mysql_num_rows($result);
}
Then get to the info using this:
$info = new userinfo();
$info->fetchdatabyemail('email#email.com');
echo $info->city;
}
You should have a private variable and getter/setter for it (this is the proper way, see code below). You could also declare $city as a public variable and access directly to it from the class' instance.
class userinfo
{
private $city = '';
public function getCity()
{
return $this->city;
}
public function fetchDataByEmail($email)
{
// Your code here
$this->city = $row['city'];
}
}
$info = new userinfo();
$info->fetchDataByEmail('someone#example.com');
echo 'City: '.$this->getCity();
I think your problem is the scope/visbility of your variables think you need to declare them outside of the scope of the function:
http://www.php.net/manual/en/language.oop5.visibility.php
class userinfo {
public $name;
public $num;
public $city;
public $numrows;
function fetchdatabyemail($email) {
$result=mysql_query(" SELECT * FROM users WHERE email='$email'");
while($row = mysql_fetch_array($result)) {
this->$name = $row['name'];
this->$num = $row['num'];
this->$city = $row['city'];
}
this->$numrows= mysql_num_rows($result);
}
}
You need to first declare the class variables.
class Userinfo {
$city;
// then declare the function
}
The way you were doing it, the scope of $city was only within the function, not stored as a field
while loop in each iteration is updating info.
so, u can echo in the while like
function fetchdatabyemail($email) {
$result=mysql_query(" SELECT * FROM users WHERE email='$email'");
while($row = mysql_fetch_array($result)) {
echo $row['city'];
}
or can store values in an array which is globally declared in the class and than echo the array.
in your code you have $city declared with local function scope which is not accessible from class $info->city.