why are my php object member variables null after instantiating them? - php

I'm trying to make an api in php. In this part I query my database and load the data into chuckquote objects then add those objects to an array to be encoded in json and received whenever the app sends a get request.
When I echo the query results every thing comes out fine but if i echo the id right after it gets instantiated its something completely different and when I encode the array everything is NULL and there is a 5th blank row that now contains the dates. How do I fix this or at least what am i doing wrong here ?
if($method == "GET")
{
$sql = "SELECT * FROM chuckquotes";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
//echo " " . $row["ID"] . " " . $row["quote"] . " " . $row["author"] . " " . $row["datentime"] . " " ;
$crow = new chuckquote;
echo $crow->$id = $row["ID"];
$crow->$quote = $row["quote"];
$crow->$author = $row["author"];
$crow->$date = $row["datentime"];
$Jsonarray[] = $crow;
}
echo json_encode($Jsonarray);
}
else
{
echo "0 results";
}
$conn->close();
}
Class
class chuckquote
{
public $id;
public $quote;
public $author;
public $date;
}
OUTPUT:
[{"id":null,"quote":null,"author":null,"date":null,"":"2019-02-17 06:47:13"},{"id":null,"quote":null,"author":null,"date":null,"":"2019-02-17 06:47:13"},{"id":null,"quote":null,"author":null,"date":null,"":"2019-02-17 06:47:13"},{"id":null,"quote":null,"author":null,"date":null,"":"2019-02-17 06:47:13"}]

Remove the $ sign from the property name. From
echo $crow->$id = $row["ID"];
$crow->$quote = $row["quote"];
$crow->$author = $row["author"];
$crow->$date = $row["datentime"];
to
$crow->id = $row["ID"];
$crow->quote = $row["quote"];
$crow->author = $row["author"];
$crow->date = $row["datentime"];
In php, you don't need to use $ sign while accessing a class property.
Although it's best practice to create a constructor for this assignment. Example class with constructor.
class chuckquote
{
public $id;
public $quote;
public $author;
public $date;
/**
* chuckquote constructor.
* #param $id
* #param $quote
* #param $author
* #param $date
*/
public function __construct($id, $quote, $author, $date)
{
$this->id = $id;
$this->quote = $quote;
$this->author = $author;
$this->date = $date;
}
}
And then you can assign the values when instantiate the class.
$crow = new chuckquote($row["ID"], $row["quote"], $row["author"], $row["datentime"]);

Related

Can not pass id to url

I have the following button which should delete the item which has been chosen
$content .= "<td> " . "<a href=/index.php?p=3&id=$id>delete</a>";
However this always sends me to:
http://localhost/index.php?p=3&id=
When p=3 it should call the following function:
case 3:
$items = new dbconnection();
$content = $items->deleteItem($_GET['id']);
/
public $id;
public function deleteItems($id) {
$conn = dbconnection::startconnection();
$this->id = $id;
$sql = "DELETE FROM items where id = '$this->id'";
$stmt = $conn->prepare($sql);
$stmt->execute();
$content ="<p>" . "<a href=index.php>Go back</a>" . "</p>";
return $content;
}
public function __construct($id = 1) {
}
Why is the ID not getting send to the URL?

Echo from function php

hello i want to echo a result from functions
code
function AboutUser()
{
global $Connection;
$GetUsers = mysqli_query($Connection, "SELECT * FROM users WHERE username='GentritAbazi'");
while($Show_Users = mysqli_fetch_array($GetUsers))
{
return $SignupDate = $Show_Users['signup_date'];
$Email = $Show_Users['email'];
$Gender = $Show_Users['gender'];
$Country = $Show_Users['country'];
}
}
Now my code not work
AboutUser()
how to do this ?
function AboutUser()
{
global $Connection;
$GetUsers = mysqli_query($Connection, "SELECT * FROM users WHERE username='GentritAbazi'");
while($Show_Users = mysqli_fetch_array($GetUsers))
{
echo $Show_Users['signup_date'];
echo $Show_Users['email'];
echo $Show_Users['gender'];
echo $Show_Users['country'];
}
}
Because you return $SignupDate = $Show_Users['signup_date'];
You want to echo, not return.
Let's use this in the while loop.
echo $Show_Users['signup_date'] ."<br>";
echo $Show_Users['email'] ."<br>";
echo $Show_Users['gender'] ."<br>";
echo $Show_Users['country'] ."<br>";
echo '<hr>'
But that is most elegant, if you collect all the data into a big array, and loop through that array.
return mysqli_fetch_all($GetUsers);
Based on the comments, and after I realized, you probably want to get one users data, here is the updated code:
function AboutUser($userName) {
global $Connection;
$res = mysqli_query($Connection, "SELECT * FROM users WHERE username='". mysqli_real_escape_string($Connection, $userName)."'");
return mysqli_fetch_row($res);
}
$userData = AboutUser('GentritAbazi');
if (!empty($userData)) {
echo $userData['signup_date'] ."<br>";
echo $userData['email'] ."<br>";
echo $userData['gender'] ."<br>";
echo $userData['country'] ."<br>";
}
You can have the function echo the value instead of returning it, like mentioned above.
Or you can use special tags e.g.
<?=
AboutUser();
?>
Hopefully this works

Displaying SELECT query results using oop php

I am a total noob with performing OOP, and am currently looking to refactor a procedural PHP project. Currently, I am having issues trying to simply display my results from a SELECT query--ironically doing an INSERT query made sense instead. This is my Class file:
<?php
class MadLibs {
private $noun;
private $verb;
private $adverb;
private $adjective;
private $story;
// Getters
public function getNoun() {
return $this->noun;
}
public function getVerb() {
return $this->verb;
}
public function getAdverb() {
return $this->adverb;
}
public function getAdjective() {
return $this->adjective;
}
public function getStory() {
return $this->story;
}
// Setters
public function setNoun($noun) {
$this->noun = $noun;
}
public function setVerb($verb) {
$this->verb = $verb;
}
public function setAdverb($adverb) {
$this->adverb = $adverb;
}
public function setAdjective($adjective) {
$this->adjective = $adjective;
}
public function setStory($story) {
$this->story = $story;
}
// Figured this one out
public function insertStoryToDatabase() {
date_default_timezone_set('America/Chicago');
$submit_date = date('Y-m-d' . " " . 'H:i:s');
$dbc = mysqli_connect('localhost','root','','mad_libs')
or die('Error establishing connection');
$query = "INSERT INTO storyTime (noun, verb, adjective, adverb, createdDate, fullStory) " .
"VALUES ('$this->noun','$this->verb','$this->adjective','$this->adverb','$submit_date','$this->story')";
mysqli_query($dbc,$query)
or die('Error querying database');
mysqli_close($dbc);
}
// method I am having trouble setting up
public function displayAllStories() {
$dbc = mysqli_connect('localhost','root','','mad_libs')
or die('Error establishing connection');
$result = "SELECT fullStory, createdDate FROM storyTime ORDER BY createdDate DESC";
$display = mysqli_query($dbc,$result)
or die('Error gathering data!');
while ($row = mysqli_fetch_array($display)) {
echo $row['story'] . '<br/>';
}
return $display;
}
}
?>
And this is what I am doing in my other php file:
<?php
require_once('MadLibs.php');
// Instantiating instance of MadLibs()
$foo = new MadLibs();
// Playing around to see ensure getters/setters were correct
$foo->setNoun('Bob');
$foo->setVerb('jumps');
$foo->setAdverb('quietly');
$foo->setAdjective('ugly');
$foo->setStory("The " . $foo->getNoun() . " always " . $foo->getVerb() . " at the "
. $foo->getAdjective() . " strangers " . $foo->getAdverb() . ".");
echo $foo->getNoun();
echo '<br />';
echo $foo->getVerb();
echo '<br />';
echo $foo->getAdverb();
echo '<br />';
echo $foo->getAdjective();
echo '<br />';
echo $foo->getStory();
$foo->insertStoryToDatabase();
$foo->displayAllStories();
?>
I'm sure it's something simple, but for the life of me I can't figure out what I'm doing wrong.
Any and all feedback is most appreciated!
You trying to display wrong variable in displayAllStories() function .
'echo $row['story']should be change to$row['fullStory'];` or change your query to
SELECT fullStory as story, createdDate FROM storyTime ORDER BY createdDate DESC

Loading person objects into array using mysqli method

I am trying to load the people stored in my database into Person objects using the mysqli_result::fetch_object method and then print store them in an array so that I can print the array out as an HTML table
I keep getting a Call to member function on a non-object error on line 84. When I do a var_dump on $row, it prints out NULL. can anyone tell me what I am doing wrong?
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href ="Stylesheet.css" rel="stylesheet" type="text/css">
<title>Assignment 3</title>
</head>
<body>
<?php
require ('Person.php');
//Making an empty array to store Person objects
$empty = array();
//Defining parameters for mysqli connect functio
$p1 = '2011.ispace.ci.edu';
$p2 = 'username';
$p3 = 'password';
$p4 = 'dbname';
//Connecting to the database and checking to see if it fails
$db = new mysqli($p1, $p2, $p3, $p4);
if ($db->connect_error)
{
echo "Error Connecting:" . " " . $db->connect_error;
}
//Querying the database to get the information from the Person table
else
{
$result = $db->query(
"SELECT *
FROM Person"
);
if($result === false){
printf($db->error);
}
var_dump($result);
//Looping through the rows and storing them in the array
$totalRows = $result->num_rows;
if ($totalRows > 0)
{
$emp = 'Person';
while($row = $result->fetch_object($emp));
{
$empty[] = $row;
$row++;
var_dump($row);
}
}
}
//Making the table headers
echo "<h1>Assignment 3 Incorporated</h1>";
echo "<table>";
echo "<tr>";
echo "<td><strong>Name</strong></td>";
echo "<td><strong>Title</strong></td>";
echo "<td><strong>Office</strong></td>";
echo "<td><strong>Phone Number</strong></td>";
echo "<td><strong>Email</strong></td>";
echo "</tr>";
//Printing out the table with foreach loop
foreach ($empty as $newPerson) {
echo "<tr>";
echo "<td>" . $newPerson-> getfirstName() . " " . $newPerson-> getlastName() . "</td>";
echo "<td>" . $newPerson-> gettitle() . "</td>";
echo "<td>" . $newPerson-> getoffice() . "</td>";
echo "<td>" . $newPerson-> getphoneNumber() . "</td>";
echo "<td><a href='mailto:" . $newPerson-> getemail() . "'>" . $newPerson-> getemail() . "</a></td>";
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
Person.php
<?php
class Person {
private $firstName;
private $lastName;
private $title;
private $office;
private $phoneNumber;
private $email;
//private $data;
//Constructor
/* public function __construct($name)
{
$this-> setname($name);
}
*/
//Interface Methods
//Get/Set Name
public function setname($name)
{
//using explode function to split name into 2 strings
$this-> name = $name;
if(is_string($name)) {
list($lastName, $firstName) = explode(",",$this -> name);
$this->firstName = $firstName;
$this->lastName = $lastName;
}
else {
user_error('Error: Persons Name Must Be a String!');
}
}
public function getfirstName()
{
return $this-> firstName;
}
public function getlastName()
{
return $this-> lastName;
}
public function getname()
{
/**
$nameSplit = explode(",",$this ->name);
foreach ($nameSplit[1] as $firstName);
foreach ($nameSplit[0] as $lastName);
echo $firstName . "," . $lastName;
return $this-> name;
**/
}
//Get/Set Title
public function settitle($title)
{
$this-> title = $title;
}
public function gettitle()
{
return $this-> title;
}
//Get/Set office
public function setoffice($office)
{
$this-> office = $office;
}
public function getoffice()
{
return $this-> office;
}
//Get/Set phone number
public function setphoneNumber($phoneNumber)
{
$this-> phoneNumber = $phoneNumber;
}
public function getphoneNumber()
{
//str_replace to modify phone number format
if(is_string($this-> phoneNumber)) {
$find3 = array (')', '(', ' ');
$replace3 = array ('', '', '-');
$phonestr = str_replace($find3, $replace3, $this-> phoneNumber);
return $phonestr;
}
else {
return user_error("Error: Person's phone number must be a string");
}
}
//Get/Set email
public function setemail($email)
{
$this-> email = $email;
}
public function getemail()
{
return $this-> email;
}
}
?>
You don't need multiple loops ...
if ($totalRows > 0) {
$emp = 'Person';
while ( $row = $result->fetch_object($emp) )
{
$newPerson = new person($row);
echo "<tr>";
echo "<td>" . $newPerson->getfirstName() . " " . $newPerson->getlastName() . "</td>";
echo "<td>" . $newPerson->gettitle() . "</td>";
echo "<td>" . $newPerson->getoffice() . "</td>";
echo "<td>" . $newPerson->getphoneNumber() . "</td>";
echo "<td><a href='mailto:" . $newPerson->getemail() . "'>" . $newPerson->getemail() . "</a></td>";
echo "</tr>";
}
}
You class Constructor should look like this
class Person {
private $firstName;
private $lastName;
private $title;
private $office;
private $phoneNumber;
private $email;
public function __construct($row) {
$this-> setname($row->firtname);
$this-> settitle($row->title);
//And So on ...
}
.... So On
Lastly .... Don't always delete question and posting it back .. always give your question sometime it would surely be answered

how do I make this function a class?

i've been creating functions for too long without taking my code to 'classes'.
I learn well through example and I just wanted to convert this simple function into a class so I can compare something I know with something I don't...
Take the following function:
function affiliateName($affiliateID) {
$sql = 'SELECT * FROM affiliates WHERE uID="' . $affiliateID . '" ';
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
$affiliateName = $row['firstName'] . ' ' . $row['lastName'];
return $affiliateName;
}
And how would I make that a class?
<?php
class AffiliateModel
{
public function first($id)
{
$sql = 'SELECT *, CONCAT(firstName, ' ', lastName) AS qualifiedName FROM affiliates WHERE uID="' . $id . '" LIMIT 1';
$res = mysql_query($sql);
return mysql_fetch_object($res);
}
}
$model = new AffiliateModel();
$a = $model->first($id);
echo $a->qualifiedName;
?>
Hope it helps
<?php
class affiliate{
// fields or properties
public $name = '';
public $id = 0;
// constructor
public function affiliate($id = 0){
$this->set_ID($id);
}
// methods
public function set_ID($id){
return $this->id = $id;
}
public function get_Name(){
if($this->name != ""){
$sql = 'SELECT * FROM affiliates WHERE uID="' . $this->id . '" ';
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
return $this->name = $row['firstName'] . ' ' . $row['lastName'];
}else{
return $this->name;
}
}
}
// Example:
$currentAffiliate = new affiliate(153);
echo $currentAffiliate->name;
?>
I prefer the following design as it is the simplest to use:
class affiliates {
static function load($id) {
return new self(intval($id));
}
private function __construct($id) {
$query = "SELECT * FROM affiliates WHERE id = " . intval($id);
$result = mysql_query($query);
// TODO: make sure query worked
foreach(mysql_fetch_assoc($result) as $field => $value)
$this->$field = $value;
}
// composite fields - made by combining and/or re-formatting other fields
function qualifiedName() {
return $this->firstName . ' ' . $this->lastName;
}
function properName() {
return $this->lastName . ', ' . $this->firstName;
}
}
$a = affiliates::load(22);
// all db fields are available as properties:
echo $a->id; // 22
echo $a->firstName; // Fred
echo $a->lastName; // Smith
// composite fields are methods
echo $a->qualifiedName(); // Fred Smith
echo $a->properName(); // Smith, Fred
// to get a single field from a particular person
echo affiliates::load(72)->qualifiedName();

Categories