how do I make this function a class? - php

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();

Related

Php - Validations and errors - unique name

I don't want to save duplicate name record. I want to display errors back to the user.
But it doesn't work. I don't know what I'm doing wrong.
protected function has_unique_name($value, $current_id="0") {
$sql = "SELECT * FROM photographs ";
$sql .= "WHERE caption='" . self::$database->escape_string($this->caption) . "' ";
$sql .= "AND id != '" . self::$database->escape_string($current_id) . "'";
echo $sql;
$result = self::$database->query($sql);
$products_count = $result->num_rows;
echo $products_count . "<br />" ;
$result->free();
return $products_count === 0;
}
protected function validate() {
$this->errors = [];
$value = $this->caption;
$current_id = isset($this->id) ? $this->id : '0';
if(!$this->has_unique_name($this->caption, $current_id)) {
$errors[] = "The name must be unique.";
}
return $this->errors;
}
public function create() {
$this->validate();
if(!empty($this->errors)) { return false; }
...

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

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"]);

Object of class PDOStatement could not be converted to string (help)

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;
...

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

(not all) Data can't reach database

I want to send data to my database (group_id, user_id and group_name) but only the first two are getting into the database. When I var_dump $groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname); it gives me the correct group_name. What am I doing wrong?
When I replace '" . $db->conn->real_escape_string($this->Invitation_group_name) . "' with a random word it is working well..
PHP
$groupinvitation = new GroupInvitation();
if (isset($_POST["Accept"])) {
try {
$group_id = mysql_real_escape_string($_POST["group_id"]);
$groupinfo = $group->GetGroupInfoByGroupId($group_id);
$groupname = $groupinfo['group_name'];
$requestnumber = mysql_real_escape_string($_POST['acceptID']);
$groupinvitation->AddAsGroupMember($number, $group_id);
$groupinvitation-> AcceptGroupRequest($requestnumber);
$groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname);
$feedback = "Awesome, You just added a friend!";
} catch(Exception $e) {
$feedback = $e -> getMessage();
}
}
DECLARATIONS:
class GroupInvitation
{
private $m_sGroup_invitation_group_name;
public function __set($p_sProperty, $p_vValue)
{
switch($p_sProperty)
{
case "Invitation_group_name":
$this->m_sGroup_invitation_group_name = $p_vValue;
break;
}
}
public function __get($p_sProperty)
{
switch($p_sProperty)
{
case "Invitation_group_name":
return $this->m_sGroup_invitation_group_name ;
break;
}
}
FUNCTION:
public function AddAsGroupMember($number, $group_id)
{
$db = new Db();
$insert = "INSERT INTO tblgroup_member(
group_id,
user_id,
group_name
) VALUES (
'" . $db->conn->real_escape_string($group_id) . "',
'" . $db->conn->real_escape_string($number) . "',
'" . $db->conn->real_escape_string($this->Invitation_group_name) . "'
)";
$db->conn->query($insert);
}
Try changing
$groupinvitation->AddAsGroupMember($number, $group_id);
$groupinvitation-> AcceptGroupRequest($requestnumber);
$groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname);
to
$groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname);
$groupinvitation->AddAsGroupMember($number, $group_id);
$groupinvitation-> AcceptGroupRequest($requestnumber);
You could be setting the property after the insert.

Categories