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();
Related
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;
}
}
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;
}
}
I am new in PHP OOP and was wondering if someone could help me with this.
I have a basic class with one method which returns data from database. Currently I am calling the method which displays everything inside the function.
Here is my class Definition:
class Products{
//properties
public $familyName = "";
public $familyProduct = "";
//Methods
public function getFamily($catId){
global $conn;
$sql = "SELECT * FROM product_family WHERE catID = '$catId'";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo "<li>".$row['familyName']."</li>";
echo "<li>".$row['familyProduct']."</li>";
}
}
}
}
Here is how I call the method:
$Products = new Products;
$Products->getFamily( 4 );
This works however, how can I assign each data coming from database ( ex familyName, familyProduct ) into variables inside class implementation and then access them individually where ever I need to. Something like this:
$Products = new Products;
$Products->familyName;
$Products->familyProduct;
I have empty properties but I am not sure how can I assign values to them coming from the loop and then return them each.
Thanks,
There are view things I would change in your Code.
Don't make Properties public use use Getters and Setters.
This will protect you Object from being used the wrong way e.g. now you can't change the familyName from outside: $products->familyName = "some value" because this would make the data of the object corrupt.
global $conn; is a no go in OOP use the construct of the Object,
in your case $products = new Products($conn);
Now you can set a Cat ID $products->setCatId(4); and read the result
$familyName = $products->getFamilyName(); or $familyProduct = $products->getFamilyProduct();
If you have more than one result you will get an array, if catId will always result one row you can delete this part. If you learn more about OOP you will find out that the hole SQL stuff can be done with a separate Object, but this is off Topic.
class Products
{
// Properties
protected $conn;
protected $catId;
protected $familyName;
protected $familyProduct;
public function __construct($conn)
{
$this->conn = $conn;
}
// set Cat ID and get date
public function setCatId($catId)
{
$this->catId = (int) $catId;
$this->getDate();
}
public function getCatId()
{
return $this->catId;
}
// get Family Name
public function getFamilyName()
{
return $this->familyName;
}
// get Family Product
public function getFamilyProduct()
{
return $this->familyProduct;
}
// get date
protected function getDate()
{
$sql = "SELECT * FROM product_family WHERE catID = '$this->catId'";
$result = $this->conn->query($sql);
// Default if no result
$this->familyName = null;
$this->familyProduct = null;
// if one Result
if ($result->num_rows == 1)
{
$row = $result->fetch_assoc();
$this->familyName = $row['familyName'];
$this->familyProduct = $row['familyProduct'];
}
if ($result->num_rows > 1)
{
$this->familyName = [];
$this->familyProduct = [];
while ($row = $result->fetch_assoc())
{
$this->familyName[] = $row['familyName'];
$this->familyProduct[] = $row['familyProduct'];
}
}
}
}
I've written a class which in the construct accesses the db and gets a list of names. These names go into an associative array e.g. ('name' => 'id').
i.e. the point is to pass in the name to get back an ID:
$id = names::nameToId('some name');
print $id;
// prints int
The problem is when I try and return the array from the construct I get an error:
Notice: Undefined variable: nameArray in (etc)
Here is the code so far:
class nameToId {
public $nameArray;
private $mysqli;
public function __construct($mysqli) {
...
while($row = mysqli_fetch_assoc($res)) {
$nameArray[$row['name']] = $row['id'];
}
return $nameArray;
}
static public function nameToId($name) {
$nameId = $nameArray[$name];
return $nameId;
}
}
$namesToId = new nameToId($mysqli);
$nameId = $namesToId::nameToId('some name');
echo $nameId;
Why doesn't $nameArray get passed to nameToId()? I'm new to classes, and I thought by declaring $nameArray as public when I first create the class that it would make it available. I have also tried to make it global even though I know that is not good form but even still it didn't work.
Because you cannot return anything from a constructor. Any return value is being ignored and just goes into the aether. $nameArray is a local variable and is not shared in any other scope, i.e. you can't access it in nameToId. Further, since nameToId is static, it won't have access to data from any non-static methods like __construct to begin with.
You probably want something like this:
class nameToId {
public $nameArray;
private $mysqli;
public function __construct($mysqli) {
...
while ($row = mysqli_fetch_assoc($res)) {
$this->nameArray[$row['name']] = $row['id'];
}
}
public function nameToId($name) {
return $this->nameArray[$name];
}
}
$namesToId = new nameToId($mysqli);
echo $namesToId->nameToId('some name');
Fix your code:
class nameToId {
public static $nameArray;
private $mysqli;
public function __construct($mysqli) {
$this->mysqli = $mysqli;
$sql = 'SELECT id, name FROM teams';
$res = mysqli_query($this->mysqli,$sql);
while($row = mysqli_fetch_assoc($res)) {
self::$nameArray[$row['name']] = $row['id'];
}
}
static public function nameToId($name) {
$nameId = self::$nameArray[$name];
return $nameId;
}
}
$namesToId = new nameToId($mysqli);
$nameId = $namesToId::nameToId('some name');
echo $nameId;