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;
...
Related
Please help,
I have populated listview control from mdb database, but I can not dinamically call php function and show list item properties onclick or keypress event on some other page element. I suppose that I have to use combination of innset command, javascript function or something similar, but how exactly in my case?
My current php code is:
<?php
$db = 'C:\wamp64\www\MushroomsPHP\files\Mushrooms.mdb';
$sqlOpis = "SELECT * FROM SveGljiveByRod";
if(!file_exists($db)){
die('Error finding access database');
}
$content=access_result_opis($db,$sqlOpis);
function access_result_opis($db,$sqlOpis){
try{
if(!file_exists($db)){
throw new RuntimeException('Access Database file path is incorrect or file does not exist.');
}
try{
$cnnt_str="odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=".$db.";Uid=; Pwd=;";
$db = new PDO($cnnt_str);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (exception $e){
print_r($e,true);
$content["error_flag"]="true";
$content["error_mesg"]="access connection error ". $e->getMessage();
return $content;
}
//run the query
try{
$result=$db->query($sqlOpis);
$result->setFetchMode(PDO::FETCH_ASSOC);
}
catch (exception $e){
$content["error_flag"]="true";
$err=$db->errorInfo();
$content["error_mesg"]="access query error ".$e->getMessage();
return $content;
}
// Listview
echo '<p>List of mushrooms</p>';
echo '<select id="mylist" name="myname" size=40 >';
$rowcount=0;
$st=0;
foreach ($result as $row ) {
$rowcount++;
if ($rowcount==1){
echo '<option onclick="' . item_describe($row["Latin"]) . '" value="Option ' . $rowcount . '" selected>' . $row["Latin"] . '</option>';
} else {
echo '<option onclick="' . item_describe($row["Latin"]) . '" value="Option ' . $rowcount . '">' . $row["Latin"] . '</option>';
}
}
echo "</select>";
echo "<p>Number of items: " . $rowcount . "</p>";
$st=1;
}
catch (exception $e){
$content["error_flag"]="true";
$content["error_mesg"]="fetch$row error ".print_r($e,true);
return $content;
}
}
?>
<?php
function item_describe($latname){
if ($st==1){
foreach ($result as $row) {
if ($row["Latin"]==$latname){
echo $row["Latin"];
echo "some text";
break;
}
}
}
}
?>
I have a PHP shopping cart I am working on. I have all my pictures stored in a folder url directory of my project. In my SQL database I have an image table that holds all of the image names. When I load the picture names with my php It somehow adds some extra random characters to the directory path:
/img/%7B$row_product_image[name]%7D 404 (Not Found)
If I hardcode the image directory img/picturename.jpg It works.
Here is what I have.
<?php
include_once "objects/database.php";
include_once "objects/product.php";
include_once "objects/product_images.php";
// object instances
$database = new Database();
$db = $database->getConnection();
$product = new Product($db);
$product_image = new ProductImage($db);
$recordsPerPage = 1;
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
extract($row);
echo '<div class="col-md-4 mb-2">';
echo '<div class="product-id d-none">{$id}</div>';
echo '<a href="product.php?id={$id}" class="product-link">';
$product_image->product_id = $pid;
$stmt_product_image = $product_image->readFirst();
while($row_product_image = $stmt_product_image->fetch(PDO::FETCH_ASSOC)) {
echo '<div class="mb-1">';
echo '<img src="img/{$row_product_image[name]}" class="w-100" />';
echo '</div>';
}
echo '<div class="product-name mb-1">{$name}</div>';
echo '</a>';
echo '</div>';
}
class ProductImage {
private $pdoConn; private $table_name = "product_images";
public $id;
public $product_id;
public $name;
public $timestamp;
public function __construct($dbconn) {
$this->pdoConn = $dbconn;
}
function readFirst() {
// SELECT query
$query = "SELECT id, pid, name " .
"FROM " . $this->table_name . " " .
"WHERE pid = ? " .
"ORDER BY name DESC " .
"LIMIT 0, 1";
// prepare query statement
$stmt = $this->pdoConn->prepare($query);
// sanitize
$this->product_id=htmlspecialchars(strip_tags($this->product_id));
// bind variable as parameter
$stmt->bindParam(1, $this->product_id);
// execute query
$stmt->execute();
// return values
return $stmt;
}
}
?>
echo '<img src="img/{$row_product_image[name]}" class="w-100" />';
PHP will NOT expand variables if string is quoted using single quotes (docs). Also you need to quote "name" string to use it as array index (docs).
That said, either fix that by avoiding single quotes (but that's ugly, so don't):
echo "<img src=\"img/{$row_product_image['name']}\" class=\"w-100\" />";
or less painful to read:
echo '<img src="img/' . $row_product_image['name'] . '" class="w-100" />';
or even use printf() to avoid spaghetting the string:
printf('<img src="img/%s" class="w-100" />', $row_product_image['name']);
Try this code: <?php while($product_rows=mysqli_fetch_array($query_run)){ ?> <div class="col-md-12"> <img src="img/<?php $product_rows['name']; ?>" class="img-responsive"?> <div?> <?php } ?>
while($row_product_image = $stmt_product_image->fetch(PDO::FETCH_ASSOC)) {
echo '<div class="mb-1">';
echo '<img src="img/'.$row_product_image['name'].'" class="w-100" />';
echo '</div>';
}
try it
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
This is the first time i am working on php and JavaScripts ... need your help in fixing something.
my site have a searchbox at the header, when a search term is submitted it goes to the search.php which holds a filter menu and search result. The filter menu is based on few selectlist. As soon as any optionis clicked in the filter menu it updates the search result.
For this i am using a javascript that calls data from another php file "SearchResult.php" to update a div with ID #Result.
PROBLEM:
it works perfectly fine at localhost however when online it causes a delay in updating the Search Result.
HELP:
Is there any way to show loading of some kind to let the viewer understand or is there anyway to make it fast.
here are my codes:
Java Script Function
function get()
{
$('#Search_Results').hide();
$.post('SearchResults.php', { Search: form.Search.value, cat: form.category.value, brand: form.brand.value },
function(output)
{
$('#Search_Results').html(output).show();
}
)
}
SEARCH FILTER FORM
enter code hereif(!empty($_REQUEST['Search'])){
$SearchTerm = $_REQUEST['Search'];
} else {
$SearchTerm = '';
}
// Search term submited
echo '<input name="Search" type="hidden" value="'.$SearchTerm.'" />';
$sql = mysql_query ("SELECT * FROM categories");
echo '<h4>Filter Categories</h4><select name="cat" onChange="get();" size="15">';
echo '<option value="" class="Select_Options">All Categories</option>';
while ($row = mysql_fetch_array($sql))
{
echo '<option class="Select_Options" value="' . $row["CategoryID"] . '">' . $row["CategoryName"] . '</option>';
}
echo '</select>';
//Few more such filters
SEARCH RESULT PAGE
if(!empty($_REQUEST['Search'])){
$SearchTerm = $_REQUEST['Search'];
}
else {
echo 'Please enter search keyword(s)';
exit();
}
if(!empty($_REQUEST['cat'])){
$cat = $_REQUEST['cat'];
$SearchQuery .= " AND categories.CategoryID = '$cat'";
}
if(!empty($_REQUEST['brand'])){
$brand = $_REQUEST['brand'];
$SearchQuery .= " AND brands.BrandID = '$brand'";
}
$sql = "SELECT DISTINCT products.ProductID, ProductKeywords, products.SectionID, products.ProductThumb, products.ProductPrice, products.CategoryID, products.SubCategoryID, products.BrandID, brands.BrandLogo, ProductTitle AS title FROM products
INNER JOIN brands ON products.BrandID = brands.BrandID
INNER JOIN sections ON products.SectionID = sections.SectionID
INNER JOIN categories ON products.CategoryID = categories.CategoryID
INNER JOIN subcategory ON products.SubCategoryID = subcategory.SubCatID $ColorJoin
WHERE MATCH (ProductKeywords) AGAINST ('$SearchTerm*' in boolean mode)$SearchQuery";
$query = mysql_query($sql);
echo '<div id="Product_Search_Container"><ul>';
while ($row = mysql_fetch_array($query))
{
$ProductID = $row["ProductID"];
$sql2 = mysql_query ("SELECT COUNT(ProColorID) AS ProductCount FROM productcolors WHERE ProductID = '$ProductID'");
while ($row5 = mysql_fetch_array($sql2))
{
$BrandID = $row["BrandID"];
$sql3 = mysql_query ("SELECT * FROM brands WHERE BrandID = '$BrandID'");
while ($row6 = mysql_fetch_array($sql3))
{
$ProductThumb = $row["ProductThumb"];
if ($ProductThumb == NULL) { $ProductThumb = "No_Image.jpg"; }
echo '<li><img src="images/Products/Thumbs/' . $ProductThumb . '" width="210px" height="275px" />
<div class="zoomer"><span class="zoom';
if ($ProductThumb != "No_Image.jpg") {
echo ' cursonstyle" style="position: relative; overflow: hidden;"><img src="images/Products/Thumbs/zoom/' . $ProductThumb . '" alt="' . $row["title"] . '" />
'; } else { echo '">'; }
echo '</span><span class="Pro_Title">' . $row["title"] . '</span>
<span class="BrandLogo"><img src="images/Brands/' . $row6["BrandLogo"] . '" /></span>
<span class="ProColors">' . $row5["ProductCount"] . ' Colors</span>
<span class="ProPrice">$' . $row["ProductPrice"] . '</span>
</a></li>';
}
}
}
echo '</ul></div>';
You could show a loading message as simple as showing it when you start the post request and hiding it in the callback.
function get()
{
$('#Search_Results').hide();
$('#loading').show().html('Please wait while loading..'); // <-- show message on function call
$.post('SearchResults.php', { Search: form.Search.value, cat: form.category.value, brand: form.brand.value },
function(output)
{
$('#loading').hide(); // <-- hide in callback function
$('#Search_Results').html(output).show();
}
)
}
You should also handle errors in your ajax request and look into prepared statements or at least use mysql_real_escape_string() for all user inputs.
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();