hi im trying to remove all my old globals from my old procedural code and im stuck on one that calls the current user.
The global is set on login and then used everywhere, so instead on login i set a token in database with a hashed cookie and intend to call the row that way but cant seem to get it working in a class.
Any help would be much appreciated bit of a noob with class objects
this works without class
test.php
// works
$res = DB::run("SELECT * FROM users INNER JOIN groups ON users.class=groups.group_id WHERE token=? AND users.enabled='yes' AND users.status = 'confirmed'", [$_COOKIE['pass']]);
$row = $res->fetch(PDO::FETCH_ASSOC);
// removed global $GLOBALS["CURUSER"] = $row;
echo $row["id"];
echo '<br>';
echo $row["username"];
echo '<br>';
echo $row["password"];
echo '<br>';
now if i put it in a class & controller it does not work
Test.php
class Test extends Controller {
public function __construct(){
$this->userModel = $this->model('User');
}
public function index()
{
dbconn();
stdhead('User');
$row = $this->userModel->getCurrentUser();
echo $row["id"];
echo '<br>';
echo $row["username"];
echo '<br>';
echo $row["password"];
echo '<br>';
stdfoot();
}
}
User.php
<?php
class User {
private $db;
public function __construct(){
$this->db = new Database;
}
// get current user
public function getCurrentUser(){
$res = db->run("SELECT * FROM users INNER JOIN groups ON users.class=groups.group_id WHERE token=? AND users.enabled='yes' AND users.status = 'confirmed'", [$_COOKIE['pass']]);
$row = $res->fetch(PDO::FETCH_ASSOC);
return $row;
}
}
Related
Hi i am using foreach in php oops to output data from the mysqlbut each data outputs twice please check my code and help it i have tried but no correct result
Here is the code below i have used
class getdata extends db{
public function getdata(){
$sql = "SELECT * FROM users";
$results = $this->connect()->query($sql);
$numrows = $results->num_rows;
if($numrows > 0){
while($row = $results->fetch_assoc()){
$data[] = $row;
}
return $data;
}
else{
echo 'no values';
}
}
}
class showusers extends getdata{
//show users
public function showusers(){
$datas = $this->getdata();
foreach($datas as $data){
echo $data['id'].'<br>';
echo $data['name'].'<br>';
}
}
}
$showusers = new showusers();
$showusers->showusers();
Don't give your function the same name as your class.
With $showusers = new showusers(); you are already executing the showusers function.
To cite php.net:
For backwards compatibility with PHP 3 and 4, if PHP cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class.
Source:https://www.php.net/manual/en/language.oop5.decon.php
So your function showusers() is treated as a constructor for your showusers class and therefore is executed twice. Once when you create an object of the class and once when you call the method.
your code is a bit convoluted I'd suggest passing the database connection object rather than extending continiously.
In this case your constructor showUsers() outputs a list of users. therefore it repeats because you are calling this function twice.
$showusers = new showusers(); // prints users
$showusers->showusers(); // prints users again
move your display function
class showusers extends getdata{
$data;
//initialize
public function showusers(){
$this->data = $this->getdata();
}
//show users
public function displayUsers(){
foreach($this->data as $data){
echo $data['id'].'<br>';
echo $data['name'].'<br>';
}
}
}
$showusers = new showusers();
$showusers->displayUsers();
I would like to know how to insert this object method:
$object = new User;
echo $object->getAllUsers();
within this PHP/HTML attribute of "src":
echo "<a href='#'>
<img id='#' src='#howtoinsert?'></a>;
...because that object method contains the data $uid from my database that I want to echo out. I've tried many ways but they will not work. How would I do this?
This is the "Class User" that contains that object method:
class User extends Dbh {
public function getAllUsers() {
$stmt = $this->connect()->query("SELECT * FROM indeximg");
while ($row = $stmt->fetch()) {
$uid = $row['username'];
return $uid;
}
}
}
Here is the code that could build your markup
$object = new User();
$users = $object->getAllUsers();
foreach($users as $currUser)
{
echo '<img id="#" src="'.$currUser.'.jpg">';
}
But it looks like your User class needs some help as well. As is, it will only return the first user. Try something like this:
class User extends Dbh
{
public function getAllUsers()
{
$stmt = $this->connect()->query("SELECT * FROM indeximg");
$output = [];
while ($row = $stmt->fetch())
{
$uid = $row['username'];
$output[] = $uid;
}
return $output;
}
}
So i'm new to classes and functions and I'm trying to do one sql query for the entire class for every function to use. I'm a little confused on how it works. From other examples that I've seen the call the query every single function which seems like a lot of usage. (why not call it once and set them all) I know there is an easier way by just querying and making variables including a db file or whatever. This is just practice.
<?php
//User System
class usrsys
{
$results = mysqli_query($con, "SELECT * FROM users WHERE id = '".$_SESSION['coid']."'");
while($row = mysqli_fetch_array($results)) {
$fname = $row['fname'];
}
function username()
{
echo $_SESSION['Username'];
}
function fname()
{
echo $fname;
}
}
//Setting Variable
$user = new usrsys();
?>
Then I call the functions in the next file by:
<?php $user->fname(); ?>
class usrsys
{
public $fname;
public $con;
public function __construct() {
//load your conection class function here and pass it to the $this->con variable.
$results = mysqli_query($this->con, "SELECT * FROM users WHERE id = '".$_SESSION['coid']."'");
while($row = mysqli_fetch_array($results)) {
$this->fname = $row['fname'];
}
}
function username()
{
echo $_SESSION['Username'];
}
function fname()
{
echo $this->fname;
}
}
//Setting Variable
$user = new usrsys();
$user->fname();
I can't make a simple echo.
I have an admin.class.php
public static function get_quota() {
return self::find_by_sql("SELECT * FROM quota");
}
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
And my echo code in index.php
<?php
$admin = User::find_by_id($_SESSION['user_id']);
$admin_class = new Admin();
$get_quota = Admin::get_quota();
$sql = "SELECT * FROM quota";
$get_quota = Admin::find_by_sql($sql);
?>
.
.
.
<?php echo $get_quota->daily_a; ?>
So my problem is, that the code is not working. I cannot echo my data. Can you help me, please?
You have a couple of problems here:
<?php echo $get_quota->daily_a; ?>
This line references the $get_quota variable and searches for a member field daily_a. Try this:
<?php echo "Quota is:".var_export($get_quota->daily_a,true); ?>
This will show that that is simply an empty variable.
However, also note:
$get_quota = Admin::get_quota();
$sql = "SELECT * FROM quota";
$get_quota = Admin::find_by_sql($sql);
Here you are calling two separate methods from Admin and setting the variable $get_quota to the result. The second overwrites the first. Therefore the get_quota() method doesn't help us here: we need to know what your find_by_sql() method returns.
EDIT (Post new code added to question)
You can implement logging/echoing within the function you've a problem with:
public static function find_by_sql($sql="") {
global $database; //Note this is bad practice (1).
$result_set = $database->query($sql);
echo "Result Set: ".var_export($result_set,true)."\n";//This should return something if you're getting something back from the database. Also, remove this for runtime (obviously).
if (count($result_set) <= 0) { //constraint checking is always good! And cheap!
error_log("An unexpected number of rows (0) was received from the database for query='".$sql."'.");
}
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row); //Ensure that the instantiate function returns something!
}
echo "Object Array: ".var_export($object_array, true)."\n";//double-check your instantiate function is working
return $object_array;
}
Based on this code, your problem is likely with the instantiate function; if it's not returning anything, $object_array is probably empty. (But not null!).
(1) You should avoid grabbing global variables like this. Instead, instantiate a class that holds and manages your database connection. Then make your find_by_sql function non-static and have a member field pointing to your database.
Hi as I mentioned in last question that I am learning class and method in php so I have another problem to understand how to use this query method to output the result in theme.
I am trying with WordPress at the moment so please consider it. However it is not too generic with WordPress rather the logic.
<?php
class get_user_widget
{
// other mentods are here which is not related to below method
public static function get_users() {
global $wpdb;
$query = "SELECT id, user_login FROM $wpdb->users ORDER BY user_registered DESC";
$users = $wpdb->get_results($query);
// here I am using foreach so is it okay or while loop is right to use?
foreach ($users as $users)
$rs[] = $users;
return count($rs) ? $rs : array();
}
}
?>
So how can I use this in theme to render the output list of user by registered date? I have checked with print_r() and connection and everything is fine and getting output in array but need to use html.
Thanks a lot..
The class can be used like this:
$array = get_user_widget::get_users();
echo "<ul>";
foreach($array as $user) {
echo "<li>".$user->user_login."</li>";
}
echo "</ul>";
EDIT:
class get_user_widget
{
public static function get_users() {
global $wpdb;
$query = "SELECT id, user_login FROM $wpdb->users ORDER BY user_registered DESC";
$users = $wpdb->get_results($query);
if(!empty($users)) {
return $users;
}
else {
$fakeuser = new stdClass();
$fakeuser->user_login = "No users in database";
return array($fakeuser);
}
}
}