Displaying SELECT query results using oop php - 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

Related

Very Basic SQL Making Page Bomb

So I'm training in MVC and extending functionality from a tutorial. I'm not getting any echos after "SUBMITTED: " with each of the values for binding. I double-checked and ran the query in PHPMyAdmin and it's inserting fine. The page is just bombing as soon as I call $this->query and I don't understand why. In the add function that's bombing, I'm trying to add a List Item. List Items (like Vacuum) belong to a List (like Cleaning). The class where I add Lists is EXACTLY the same and works perfectly.
public function add(){
// Sanitize POST
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
// show the List name
$lModel = new ListModel();
$lName = $lModel->getListTitle($this->listID);
if($post['submit']){
echo "SUBMITTED: Name: " . $post['name'] . " ID: " . $this->listID . " And 1 for Position<br>";
// Insert
$this->query("INSERT into list_item (list_id, name, position) VALUES (:list_id, :name, :position)");
echo "After query<br>";
$this->bind(':list_id', $this->listID);
$this->bind(':name', $post['name']);
$this->bind(':position', 1);
echo "After binding<br>";
//Verify
$this->execute();
echo "Execute?<br>";
if($this->lastInsertId()){
echo "Insert ID " . $this->lastInsertId();
//redirect
//header("Location: " .ROOT_URL."listItems/index/" . $this->listID);
}else{
echo "Didn't insert<br>";
Messages::setMsg('Failed to insert list','error');
}
}
//echo "lName: $lName";
return $lName;
}
}
Here is the entire class for your viewing pleasure.
<?php
class ListItemModel extends Model{
public $listID;
public function __construct($id){
$this->listID = $id;
}
public function Index(){
return "some data";
$this->query("SELECT * FROM list_item WHERE list_id = :list_id ORDER BY create_dt DESC");
$this->bind(':list_id', $this->listID);
$rows = $this->resultSet();
return $rows;
}
public function add(){
// Sanitize POST
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
// show the List name
$lModel = new ListModel();
$lName = $lModel->getListTitle($this->listID);
if($post['submit']){
echo "SUBMITTED: Name: " . $post['name'] . " ID: " . $this->listID . " And 1 for Position<br>";
// Insert
$this->query("INSERT into list_item (list_id, name, position) VALUES (:list_id, :name, :position)");
echo "After query<br>";
$this->bind(':list_id', $this->listID);
$this->bind(':name', $post['name']);
$this->bind(':position', 1);
echo "After binding<br>";
//Verify
$this->execute();
echo "Execute?<br>";
if($this->lastInsertId()){
echo "Insert ID " . $this->lastInsertId();
//redirect
//header("Location: " .ROOT_URL."listItems/index/" . $this->listID);
}else{
echo "Didn't insert<br>";
Messages::setMsg('Failed to insert list','error');
}
}
//echo "lName: $lName";
return $lName;
}
}
?>
And here's the query function in Model as requested
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
I figured it out!!!
Because I was using the constructor in ListItemModel (which extends Model) to pass in the $id for the list, I needed parent::__construct().
Thanks, everyone!

How to use the oop in reading from mysql in mysql?

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

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

how to call the function once at a time? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm working on my PHP script to call the function once at a time when I click the link on my site.
When I click the link on my site to connect to the get-listing.php script, it will call to both function of tvguidecom and skyuk at the same time which it will output one of those webpage.
I think the problem are on this line:
while ($row = mysql_fetch_array($result1))
{
tvguidecom($row);
skyuk($row);
}
Here is the full code:
<?php
$errmsg_arr = array();
$errflag = false;
$link;
include ('simple_html_dom.php');
function db_connect()
{
define('DB_HOST', 'localhost');
define('DB_USER', 'mydbname');
define('DB_PASSWORD', 'mydbpassword');
define('DB_DATABASE', 'mydbname');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
}
function tvguidecom($row)
{
include ('tvguide.get-listing.php');
}
function tvguide2($row)
{
include ('skyuk.php');
}
db_connect();
function clean($var)
{
return mysql_real_escape_string(strip_tags($var));
}
$channels = "";
$id = "";
if(isset($_GET['channels']))
{
$channels = $_GET['channels'];
}
if(isset($_GET['id']))
{
$id = $_GET['id'];
}
if($errflag)
{
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
echo implode('<br />',$errmsg_arr);
}
else
{
$insert = array();
if(isset($_GET['channels']))
{
$insert[] = 'channels = \'' . clean($_GET['channels']) .'\'';
}
if(isset($_GET['id']))
{
$insert[] = 'id = \'' . clean($_GET['id']) . '\'';
}
if($channels && $id)
{
$qrytable1="SELECT id, channels, links FROM tvguide WHERE channels='$channels' && id='$id'";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
tvguidecom($row);
skyuk($row);
}
mysql_close();
exit;
}
else if(!$channels && ! $id)
{
$qrytable1="SELECT id, channels, links, streams FROM tvguide";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
echo "<p id='channels'>".$row["id"]. " " . $row["channels"]. "</p>";
echo '<a id="link1" href="http://example.com/get-listing.php?channels=' . $row["channels"] . "&id=" . $row["id"] . '">http://example.com/get-listing.php?channels=' . $row["channels"] . "&id=" . $row["id"] . '</a><br><br>';
//echo "<p id='links'>";
//echo '<a id="link1" href="http://example.com/get-listing.php?channels=' . $row["channels"] . "&id=" . $row["id"] . "'>http://example.com/get-listing.php?channels=" . $row["channels"] . "&id=" . $row["id"] .'>test</a></p>';
//echo '<a id="link1" href="http://example.com/get-listing.php?channels=';
echo '<a id="streams" href="' . $row['streams'] . '">Stream 1</a><br><br>';
}
}
}
?>
I want to call either of function once at a time when I click the link on my site. Example: I want to call tvguidecom function to see if it will output the data in my get-listing script or else move on to the next function and call the skyuk function.
Can you please show me an example of how I can call the function once at a time when I click the link on my site?
The best thing you can do is having your functions returning a boolean so you can check if you should continue the process.
I guess the function tvguidecom looks like:
function tvguidecom() {
// do something without return value
}
Add a return value in it:
function tvguidecom() {
// do something
return $status;
}
So in your code you can test for the return value
while ($row = mysql_fetch_array($result1))
{
if (tvguidecom($row)) {
skyuk($row);
}
}
Note: on a different topic, you shouldn't use anymore mysql extension because it is deprecated. You should use instead mysqli or pdo.
TL;DR
while ($row = mysql_fetch_array($result1))
{
// this ensures that `tvguidecom()` does its stuff, and `skyuk()`
// waits for results returned by the function.
skyuk(tvguidecom($row));
}
function tvguidecom($row) {
// do stuffs, returns original input $row;
return $row;
}
** Another approach, callbacks.**
while ($row = mysql_fetch_array($result1))
{
tvguidecom($row, callback);
}
and fn:
tvguidecom(a, callback) {
// dostuffs and when complete
callback( result );
}
** syntax may be incorrect, refer to link supplied. Hope this helps.

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