Get the value of return within class - php

Goodday. The question is, how can I get the return value and pass to my other php file?
myclass.php file
class myClass{
function banner(){
$sql = "Select * From tblBanner";
$query = mysql_query($sql) or die (mysql_error());
$row = mysql_fetch_assoc($query);
$banner = $row;
return $banner;
}
}
my index.php file
include 'myclass.php';
$banner = new myclass;
$ban = $banner->banner;
echo $ban;
This is what im trying to do. Im a newbie so spare with me. Thank you.

Like I already wrote in the comments, $banner->banner would be a property of the class "myClass". But you want to get a method, so you have to use $banner->banner().
myclass.php file
class myClass{
function banner(){
$sql = "Select * From tblBanner";
$query = mysql_query($sql) or die (mysql_error());
$row = mysql_fetch_assoc($query);
$banner = $row;
return $banner;
}
}
my index.php file
include 'myclass.php';
$banner = new myclass;
$ban = $banner->banner();
// example for array:
foreach($ban as $banner) {
echo $banner;
}
// example for string:
echo $ban;
An example for $banner->banner:
myclass.php file
class myClass{
public $banner = 'Banner Property';
function banner(){
$sql = "Select * From tblBanner";
$query = mysql_query($sql) or die (mysql_error());
$row = mysql_fetch_assoc($query);
$banner = $row;
return $banner;
}
}
my index.php file
include 'myclass.php';
$banner = new myclass;
$ban = $banner->banner;
echo $ban;

Related

Get datas from table and display with OOP

How I can get the comments with OOP from my database? Im trying with below code but it displaying the error. Im new using the classes and I git stuck here trying to reselve this issue.
Below is the code in class Comments:
function getComments(){
$komentet = array();
$connect = mysql_connect("localhost","root","") or die(mysql_error());
$select = mysql_select_db("profile") or die(mysql_error());
$id = $_SESSION['id'];
$result = mysql_query("SELECT * FROM posts order by mycoment DESC") or die(mysql_error());
while($row = mysql_fetch_array($result)){
array_push($komentet,$row['mycoment']);
}
return $komentet;
}
With the below code, Im trying to display the datas in my web page but I can not.
<?php
$komentet = $comm->getComments();
foreach($komentet as $cm){
echo "<tr><td>".$cm."</td></tr>";
}
?>
It returning the following error:
Notice: Undefined variable: comm in C:\xampp\htdocs\profile\uprofile.php on line 194
Fatal error: Call to a member function getComments() on null in C:\xampp\htdocs\profile\uprofile.php on line 194
Full classs is the code below:
<?php
class Comments {
public $datetime;
public $comment;
function insertDate(){
$connect = mysql_connect("localhost","root","") or die(mysql_error());
$select = mysql_select_db("profile") or die(mysql_error());
$id = $_SESSION['id'];
$this->datetime = date("F j, Y, g:i a");
$sql = "INSERT INTO posts(userid, mycoment, time) VALUES('$id','$this->comment','$this->datetime')";
if(mysql_query($sql)){
echo "Comment Added";
}else{
echo "Comment Failed";
}
}
function getComments(){
$komentet = array();
$connect = mysql_connect("localhost","root","") or die(mysql_error());
$select = mysql_select_db("profile") or die(mysql_error());
$id = $_SESSION['id'];
$result = mysql_query("SELECT * FROM posts order by mycoment DESC") or die(mysql_error());
while($row = mysql_fetch_array($result)){
array_push($komentet,$row['mycoment']);
}
return $komentet;
}
}
the problem you have is you crate the instance of the class Comments inside of a condition, which does not pass:
require_once('comments.php');
if(isset($_POST['postsomething'])){
$comm = new Comments();
$comm->comment = trim($_POST['mycoment']);
$comm->insertDate();
}
$komentet = $comm->getComments();
foreach($komentet as $cm){
echo "<tr><td>".$cm."</td></tr>";
}
so you should alter it like this:
require_once('comments.php');
$comm = new Comments();
if(isset($_POST['postsomething'])){
$comm->comment = trim($_POST['mycoment']);
$comm->insertDate();
}
$komentet = $comm->getComments();
foreach($komentet as $cm){
echo "<tr><td>".$cm."</td></tr>";
}
I've made a little work for you and refactored the Comments class using mysqli extension and ridding som DRY (Don't Repeat Yourself) breaches. I highly suggest you to stick on mysqli and avoid any code duplication.
class Comments
{
public $datetime;
public $comment;
function insertDate(){
$id = $_SESSION['id'];
$this->datetime = date("F j, Y, g:i a");
$sql = "INSERT INTO posts(userid, mycoment, time) VALUES('$id', '$this->comment', '$this->datetime')";
if($this->getConnection()->query($sql)){
echo "Comment Added";
} else{
echo "Comment Failed";
}
}
function getComments(){
$komentet = array();
$result = $this->getConnection()->query("SELECT * FROM posts order by mycoment DESC");
while($row = $result->fetch_assoc()){
array_push($komentet, $row['mycoment']);
}
return $komentet;
}
private function getConnection(){
if($this->connection === null)
$this->connection = mysqli_connect("localhost", "root", "", "profile") or die(mysqli_error($this->connection));
return $this->connection;
}
/** #var mysqli */
private $connection;
}

Unable to correctly return and store my mysqli result

I am trying to return my mysqli result and store it in a static variable so that I can pass it on to another function. As you can see below the second function needs to be able to read the result from the first one. The scope problem should have been fixed with returning and storing it then storing my function within a variable inside the second function:
What am I doing wrong? Why is this not working? It works for things like my database connection.
function profile_info() {
$connection = database();
static $result;
$query = "SELECT id, name, first_name, last_name, birthdate, occupation, status
FROM users";
$result = mysqli_query($connection, $query);
return $result;
}
I then store the returned result within my function below `$result = profile_info():
function users_overview () {
$connection = database();
$result = profile_info();
echo "<div id='users_overview'>";
while($row = mysqli_fetch_array($result)) {
if (!empty($row['status']) && $row['status'] == 'Online') {
$status = "<div class='online'></div>";
}
else {
$status = "<div class='offline'></div>";
}
include 'php/core/age_converter.php';
include 'php/includes/profile_information.php';
}
echo "</div>";
}
users_overview();
Seems two time $connection = database(); is being called when you include the call to profile_info(); from users_overview ()
Check now if it works now,
function profile_info() {
$connection = database();
static $result;
$query = "SELECT id, name, first_name, last_name, birthdate, occupation, status
FROM users";
$result = mysqli_query($connection, $query);
return $result;
}
function users_overview () {
$result = profile_info();
echo "<div id='users_overview'>";
while($row = mysqli_fetch_array($result)) {
if (!empty($row['status']) && $row['status'] == 'Online') {
$status = "<div class='online'></div>";
}
else {
$status = "<div class='offline'></div>";
}
include 'php/core/age_converter.php';
include 'php/includes/profile_information.php';
}
echo "</div>";
}
users_overview();
As you don't want to globally define the variable and you can use the OOPs Concept. Data will be wrap in object. I wrote a code for you.
class user{
private $conn;
private $result;
function __construct(){
$conn1 = new mysqli("localhost", "root", "", "siteData");
$this->setConn($conn1);
}
public function profile_info(){
$query = "SELECT * FROM users";
$num = $this->getConn();
$result = $num->query($query);
return $result;
}
function users_overview () {
$result = $this->profile_info();
while($row = mysqli_fetch_array($result)){
//get your result
}
}
function setConn($conn1){
$this->conn = $conn1;
return $this->conn;
}
function getConn(){
return $this->conn;
}
}
$temp = new user();
$temp->users_overview();

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.

display database variables in file

So I had my variables all hard coded into my page like so:
$base_url = 'something';
$logo_url = 'somethingelse';
And then I went and put all these into a database for easier updating, Now I need to place them back into the config.php file so my website can use them.
I tried doing the following: (database.php includes all the connection details)
function get_identifiers() {
require_once 'database.php';
$result = mysqli_query($con,"SELECT * FROM settings");
while($row = mysqli_fetch_array($result))
{
$identifier = $row['identifier'];
$value = $row['value'];
$identifier = $value
}
mysqli_close($con);
}
But I got nothing. What can I do?
You should set your identifiers in an array, return it, and then extract it:
require_once 'database.php';
function get_identifiers() {
$retval = array();
$result = mysqli_query($con,"SELECT * FROM settings");
while($row = mysqli_fetch_array($result))
{
$identifier = $row['identifier'];
$value = $row['value'];
$retval[$identifier] = $value;
}
mysqli_close($con);
return $retval;
}
Then run this on your page:
extract(get_identifiers());
This will change all of your settings into variables, as you want.
I think its because your making $identifier = $value... If you want to get the name of the identifier as the variable name use $$identifier = $value;
however I too would suggest using either object or array
$config = new stdClass;
while($row = mysqli_fetch_array($result)) {
$indentifier = $row['identifier'];
$config->$identifier = $row['value'];
}

return values from class php oop

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.

Categories