return values from class php oop - php

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.

Related

How to use php functions in IF statement

INTRO
I am trying to better understand my knowledge of Php and using classes to better prganise my code so this is just an exercise for a better understanding rather than a real world solution.
BRIEF
I am calling in a function from a class which I have just learnt to do but I want to know the best way to do something simple tasks like use the object in an IF statement.
SCENARIO
So for instance I am setting my classes like so:
class user
{
// Get users ID
function get_user_id()
{
global $conn;
$sql = 'SELECT id FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc() ){
echo $row['id'] . ', '; }
}
}
// Get users name
function get_user_name()
{
global $conn;
$sql = 'SELECT name FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc() ){
echo $row['name'] . ', '; }
}
}
}
$userId = new user;
$userName = new user;
I am then initializing in my classes like so:
<?php $userId->get_user_id(); ?>
<?php $userName->get_user_name(); ?>
and THEN I am wanting to performa simple task like show a user based on the value of their ID, the above will return 2 sets of results of 4 so id 1, 2, 3, 4 & Dan, Andy, Ryan, Aran
so I am performing a simple IF statement like so:
if($userId > 1){
echo $userName;
} else {
echo 'not working';
}
But it returns 'not working' - I am just wanting to better understand how to use the functions in a way that A works and B best practice.
It doen't look like you've understood OOP just yet.
These code examples should hopefully give you an introduction but as in other comments, read up on OOP. I struggled with it at first but keep at it!
Create your user class
This class represents a single user and the actions associated with a user, think of it as a blue print. It should only perform functions related to a user, it shouldn't keed to 'know' about anything else. For example, database functions sholud be done elsewhere.
class User {
private $id;
private $name;
function __construct($array)
{
$this->id = $array['id'];
$this->name = $array['name'];
}
function getId()
{
return $this->id;
}
function getName()
{
return $this->name;
}
}
Load all users into an array
$sql = 'SELECT * FROM user';
$result = $conn->query($sql);
$users = [];
while ($row = $result->fetch_assoc() ){
$users[] = new User($row);
}
// this array now contains all your users as User objects
var_dump($users);
// echo all user's details
foreach($users as $user) {
echo $user->getId();
echo ' - ';
echo $user->getName();
echo "\r\n";
}
Load a single user
$sql = 'SELECT * FROM user WHERE id = 1';
$result = $conn->query($sql);
if ($row = $result->fetch_assoc()) {
$user = new User($row);
} else {
exit('User ID does not exist');
}
// echo the user's ID and name
echo $user->getId();
echo ' - ';
echo $user->getName();
Resourses
Laracasts - https://laracasts.com/series/object-oriented-bootcamp-in-php
Search PHP OOP explained - https://www.google.co.uk/search?q=php+oop+explained
<?php
class user {
// Get users ID
function get_user_id() {
global $conn;
$data = array();
$sql = 'SELECT id FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row['id'] . ', ';
}
}
return $data;
}
// Get users name
function get_user_name() {
global $conn;
$data = array();
$sql = 'SELECT name FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row['name'] . ', ';
}
}
return $data;
}
}
$userId = new user;
$userName = new user;
// all user ids
$all_ids = $userId->get_user_id();
echo '<pre>';
print_r($all_ids);
// all user name
$all_name = $userId->get_user_name();
echo '<pre>';
print_r($all_name);`enter code here`
Check first response from both function after use if condition
You are comparing object with 1 not the value returned by function get_user_id().
So instead of
<?php $userId->get_user_id(); ?>
<?php $userName->get_user_name(); ?>
Try
<?php $id=$userId->get_user_id(); ?>
<?php $name= $userName->get_user_name(); ?>
and then put in your condition
if($id > 1){
echo $name;
} else {
echo 'not working';
}
I will suggest you to replace echo with return statement.
call your class as an object
$userid = user();
$username = user();
you can also try something like this
class user
{
// Get users ID
function get_user_id($id = "")
{
global $conn;
// check if id is empty or not
if(!empty($id)) {
$sql = 'SELECT id FROM users WHERE id = '.$id;
}else{
$sql = 'SELECT id FROM users';
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc() ){
echo $row['id'] . ', '; }
}
}
// Get users name
function get_user_name($name = "")
{
global $conn;
// check if name is empty or not
if(!empty($name)) {
$sql = 'SELECT name FROM user WHERE name = '.$name;
}else{
$sql = 'SELECT name FROM user';
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc() ){
echo $row['name'] . ', '; }
}
}
}
$userId = new user();
$userName = new user();
$userId->get_user_id(1);
$userName->get_user_name();
echo $userId;
echo $userName;
please make sure you sanitize the id and name before use
IN both get_user_id, get_user_name methods please
return $row = $result->fetch_assoc();
so, it will value comes in $userId, $userName and you can access it.
right now you return nothing so $user_id has null value so, it always goes in else condition.
Example
function get_user_id()
{
global $conn;
$sql = 'SELECT id FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$value = '';
while ($row = $result->fetch_assoc() ){
$value .= $row['id'] . ', ';
}
return $value;
}
}

fetch database data with singleton design pattern

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

php class return array

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.

Re create as objects and classes PHP

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

Pass values from array to a function

I have the following code which gets all news:
private function get_news()
{
$news = array();
$query = $this->database->query("SELECT * FROM `news` ORDER BY `news_id` DESC");
while($row = mysql_fetch_array($query))
{
$news[] = $row;
}
return $news;
}
In the same class I have a bbedit() function. I want to get the value of $news[int]['news_content'] and pass it to that function bbedit().
Use $this to call a function within class:
private function bbedit(){
$news = $this->get_news(); // news will have all your array
foreach($news as $key => $val){
// do something with $val['news_content'];
}
}
or
while($row = mysql_fetch_array($query)){
$news[] = $this->bbedit($row['news_content']);
}

Categories