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;
}
}
Related
While creating a group with user ids, I am checking if the entered id exists in database. If it exists, group should be created, if not it should pop out an error.
I am passing array with user ids to a function user_check, but it is not getting checked. Here is my code:
<?php
function user_check($user_id)
{
$u1 = mysqli_query($con, "SELECT uid from users where uid<>'" . $_SESSION['user_id'] . "'");
while ($row = mysqli_fetch_array($u1)) {
$users = $row['uid'];
echo "users" . $users;
$users1 = sort($users);
$users2 = sort($user_id);
printf($users1);
if ($user1 == $user2) {
echo "same";
} else {
echo "not same";
}
}
}
Given a list of user_ids (that you have validated/filtered already) you could write a function something like the following (untested):
function all_users_exist(array $user_ids, Mysqli $con)
{
$result_uids = [];
$ids = implode(',', $user_ids);
$sql = "SELECT uid from users WHERE uid IN ($ids)";
$result = $con->query($sql);
if($result)
while ($row = $result->fetch_array(MYSQLI_ASSOC))
$result_uids[] = $row['uid'];
sort($user_ids);
sort($result_uids);
return $user_ids == $result_uids;
}
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();
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 want show my message system user Profile name(If have) else show user name.
In my every code I used as below, which work well.
if (empty($pname)) $pname = $username;
But in below I cannot understand how to Return 'profile name else user name' in my "function getusername($userid)".
Here if I use return $row[0] at my "function getusername" Its show username, But I want to show Profile name and If profile name empty then show user name.
Get profile name/user name code:
function getusername($userid) {
$sql = "SELECT username,pname FROM users WHERE `id` = '".$userid."' LIMIT 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)) {
$row = mysql_fetch_array($result);
$username = $row['username'];
$pname = $row['pname'];
if (empty($pname)) $pname = $username;
// Now here return $row[0] show only username But How to return pname else username?
return $row[0];
} else {
return "Unknown";
}
}
This code fetch a specific message
function getmessage($message) {
$sql = "SELECT * FROM mail WHERE `id` = '".$message."' && (`from` = '".$this->userid."' || `to` = '".$this->userid."') LIMIT 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)) {
// reset the array
$this->messages = array();
$row = mysql_fetch_assoc($result);
$this->messages[0]['id'] = $row['id'];
$this->messages[0]['title'] = $row['title'];
$this->messages[0]['message'] = $row['message'];
$this->messages[0]['from'] = $this->getusername($row['from']);
$this->messages[0]['to'] = $this->getusername($row['to']);
} else {
return false;
}
}
Use this
function getusername($userid) {
$sql = "SELECT username,pname FROM users WHERE `id` = '".$userid."' LIMIT 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)) {
$row = mysql_fetch_array($result);
$username = $row['username'];
$pname = $row['pname'];
if (empty($pname)) $pname = $username;
// Now here return $row[0] show only username But How to return pname else username?
return $pname;
} else {
return "Unknown";
}
}
The problem is with how you are returning the value.
Change:
if (empty($pname)) $pname = $username;
// Now here return $row[0] show only username But How to return pname else username?
return $row[0];
To:
if(empty($pname)) return $username;
else return $pname;
Also, it is suggested you use mysqli instead of mysql.
Can't you use something like this?
return isset($pname) ? $pname : $username;
This basically is: if $pname is set, then return $pname, else return $username
I am working on an Item Inventory Web App. I want users should be able to add and assign item to a user. Each user is entitled to one item at a time. If, say, user a already has an item assigned and you want to add more item, the system should lodge an error that will tell you
to withdraw the item be issuing a new one but the errors are not getting lodged in the error[] array even though it shows that the array is not empty. It only echo out the serial number a = 1 and a++ but the text is not there.
class.inc.php
class Summary {
public $result;
public $conn;
public $SQ;
public $q;
public $updateDB;
public $checkDB;
public $returned_result;
public $a;
public $data;
public $col;
public function __construct(){
$this->conn = new PDO('mysql:host=localhost; dbname=dB', 'root', '');
$this->conn->setAttribute(PDO:: ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function updateDB($coloumn, $data, $id){
$SQ = "UPDATE mytable SET $coloumn = ? WHERE staffID = ?";
$q = $this->conn->prepare($SQ) or die("ERROR: " . implode(":", $this->conn->errorInfo()));
$q->bindParam(1, $data);
$q->bindParam(2, $id);
if ($q->execute()){
$success = 'Record updated successfully';
};
return $success;
}
public function checkDB($col, $data){
$status = 'Active';
$SQ = "SELECT surname FROM mytable WHERE $col = ? AND status = ?";
$q = $this->conn->prepare($SQ) or die("ERROR: " . implode(":", $this->conn->errorInfo()));
$q->bindParam(1, $data);
$q->bindParam(2, $status);
$q->execute();
if($result = $q->fetch(PDO::FETCH_BOTH)){
$a = $result[0];
if ($a == ''){
$this->returned_result = 'N';
}
else {
$this->returned_result = "This item (". $data . ") is in use by ". $a . ". Please widthraw the item";
}
}
return $this->returned_result;
}
}
index.php:
include('class.inc.php');
$summary = new Summary;
$error = array();
if(isset($_POST['saveRecord']) ) {
$system_name = strtoupper ( $_POST['system_name'] );
$result =$summary->checkDB('systemName', $system_name); //check if the item is in use
if ( $result == 'N' ){
$summary->updateDB('systemName', $system_name, $id);
$update = $summary->updateDB;
}
else $error[] = $result;
$system_serial_number = strtoupper ( $_POST['system_serial_number'] );
$result =$summary->checkDB('CPUSerial', $system_serial_number); //check if the item is in use
if ( $result == 'N' ){
$summary->updateDB('CPUSerial', $system_serial_number, $id);
$update = $summary->updateDB;
}
else $error[] = $result;
}
if(isset($_POST['saveRecord']) && !empty( $error ) ) {
echo "<div class = 'text-error'>";
$a = 1;
foreach ($error as $err){
echo '<p>' . $a . '. ' .$err . '</p>';
$a++;
}
echo "</div>";
}
Any help will be greatly appreciated. And what am I doing wrong with regards to OOP way of programming?