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
Related
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"]);
I'm trying to read from mysql with php and with oop.How can use from propeties?
This is my class and search function for reading from the database:
<?php
require_once('dbconfig.php');
class Film {
public $name;
public $year;
public $country;
public $director;
private $conn;
public function __construct() {
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql) {
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function search($name,$year,$country,$director) {
try {
$stmt = $this->conn->prepare("SELECT * FROM table where name='$name' or year='$year' or country='$country' or director='$director'");
$stmt->execute();
$num_rows = $stmt->rowCount();
if ($num_rows > 0) {
echo "</br>".$num_rows." film is found. </br>";
echo "</br><table><tr><th>Name</th><th>Year</th><th>Country</th><th>durationMinutes</th><th>Director</th></tr>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['year'] . "</td><td>" . $row['country'] . "</td><td>" . $row['durationMinutes'] . "</td><td>" . $row['director'] . "</td></tr>";
}
echo "</table>";
} else {
echo "Nothing found !";
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
}
I want search() is based on the object and properties.
How to change my code?
Did you mean you want to call that function?
just put this code wherever you wanna place it e.g in index.php.
$film->search($name,$year,$country,$director);
but you have to initial class film in your connection file like this
session_start();
$host = "localhost";
$user = "root";
$pass = "";
$database="database";
try {
$con = new PDO ("mysql:host={$host}; dbname={$database}", $user, $pass);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
}
catch (PDOEXception $e) {
echo $e->getMessage();
}
include_once 'class_film.php';
$film= new Film($con);
I've been trying for the last six hours to figure out what is wrong with my code. My page keeps outputting 'Catchable fatal error: Object of class PDOStatement could not be converted to string.' I don't know why! I looked at previous assignments, tried googling the type of error, and nothing has changed the output. I want to display my menu items by category id. Here's my code.
class Menu {
public $conn;
public function __construct() {
$db = new Database();
$this->conn = $db->conn;
}
public function __destruct() {
$this-> conn = null;
}
/* Get function */
public function __get($name) {
return $this->$name;
} // End get function
public function __set($name, $value){
$this->$name=$value;
}
public function menu_items($category_id = 0){
try {
$sql = "SELECT item_id, category, category_id, display_order, item_name, item_image, item_description, item_cost FROM menu_items WHERE category_id = $category_id";
$result = $this->conn->query($sql);
return $result;
}
catch (PDOException $e){
echo 'Error: ' . $e->getMessage();
exit();
}
}
}
UPDATE: Here is where everything is outputting. Could there be something wrong with this code instead?
include(ABSOLUTE_PATH . 'classes/menu.class.php');
// Create Menu object
$menu = new Menu();
$menu_categories = $menu->menu_categories();
include(ABSOLUTE_PATH . '_includes/header.inc.php');
?>
<hr />
<h2><?=$page?></h2>
<?
while($item = $menu_categories->fetch(PDO::FETCH_OBJ)) {
// Retrieve menu items
$menu_items = $menu->menu_items($menu_categories);
$item_count = $menu_items->rowCount();
if($item_count > 0) {
echo '<h3>' . $item->category . '</h3>';
?>
<table id="menu_items" class="listing">
<?
// Loop through menu records
while($item = $menu_items->fetch(PDO::FETCH_OBJ)) {
echo "\t<tr>\n";
echo "\t\t" . '<td class="item"><h4>' . $item->item_name . '</h4><p>' . $item->item_description . '</p></td>' . "\n";
echo "\t\t" . '<td class="price">$' . $item->item_cost . '</td>' . "\n";
echo "\t\t" . '<td class="image"><img src="' . URL_ROOT . '_assets/images/menu/' . $item->item_image . '" alt="' . $item->item_name . '" /></td>' . "\n";
echo "\t</tr>\n";
}
?>
</table>
<?
}}
?>
<hr />
<?
include(ABSOLUTE_PATH . '_includes/footer.inc.php');
?>
Aha
here is your problem:
while($item = $menu_categories->fetch(PDO::FETCH_OBJ)) {
// Retrieve menu items
$menu_items = $menu->menu_items($menu_categories); //<--Error
$item_count = $menu_items->rowCount();
You should call:
$menu_items = $menu->menu_items($item->id);
You are passing $menu_categories (a PDOStatement) into menu_items(), then trying to use it as a string directly in your query. That is where the error is actually occurring.
A good practice that would have made this error more apparent is to type check query parameters. So in menu_items():
public function menu_items($category_id = 0){
if(!is_numeric($category_id)) {
//Do something better here, but just for example
echo "Error";
return false;
}
try {
$sql = "SELECT item_id, category, category_id, display_order, item_name, item_image, item_description, item_cost FROM menu_items WHERE category_id = $category_id";
$result = $this->conn->query($sql);
return $result;
...
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
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();