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
Related
I was experimenting if I could use a mySQL database to store CSS settings. I set up a simple database "colors" with one table "color" that had simple structure tag and color columns. In that, one row is h1 => red.
<?php
//function to dynamically change CSS
$tag = 'h1';
$q = "SELECT * FROM `colors` WHERE `tag`='" . $tag . "'" ;
echo $q . "<br>";
$query = mysqli_query($link, $q);
if ($row = mysqli_fetch_assoc($query))
{
echo $row['color'];
} else
{
echo "error - no such tag";
}
?>
When I tried to convert to a function, the code does not work at all.
<?php
//function to dynamically change CSS
function getCSS($tag)
{
$tag = 'h1';
$q = "SELECT * FROM `colors` WHERE `tag`='" . $tag . "'" ;
echo $q . "<br>";
$query = mysqli_query($link, $q);
if ($row = mysqli_fetch_assoc($query))
{
echo $row['color'];
} else
{
echo "error - no such tag";
}
}
getCSS('h1');
?>
Help please?
My guess is that in
$query = mysqli_query($link, $q);
$link goes out of scope and is empty. You should pass it to the function as well.
For the record: using $tag without escaping could be an sql injection attack possibility.
in function, there is no $link, you shoud define it as a global variable.
At the start of your function add a reference to your global DB link:
function getCSS($tag) {
global $link;
...
This should work:
<?php
$link = mysqli_connect('server_host', 'user', 'password', 'database') OR die('Could not connect because: '.mysqli_connect_error());
//function to dynamically change CSS
function getCSS($link, $tag){
$q = 'SELECT * FROM colors WHERE tag = "' . $tag . '"' ;
$r = mysqli_query($link, $q);
if(mysqli_num_rows($r)>0){ // check if there are results
while($row = mysqli_fetch_assoc($r)){
//echo '<pre>';
//print_r($row); // print the result array for debugging
//echo '</pre>';
echo $row['color'] . '<br />';
}
return $row;
} else { // if no result is found
echo 'No such tag';
}
}
// test it:
echo '<br />if tag is h1<br />';
getCSS($link, 'h1');
echo '<br />if tag is h2<br />';
getCSS($link, 'h2');
?>
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 newbie in php. i am using the following code to get my desired data from mysql database. but what i want to do, whenever database show a result i want to put it into a bootstrap grid( like col-sm-4) each time. Right now my grid is coded in HTML, how can i generate it with the query result each time ? thanks in advance.
<div class="col-sm-4">
<h3>image </h3><br>
<?php
$sql = "SELECT * FROM sctable";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$link = "http://localhost/sc/uploads/" .$row[1];
echo "<img width='100%' height='200' src=$link />"."<br />";
echo "";
}
?>
</div>
Do you mean something like this where you just want to put each rows data into its own div
<?php
$sql = "SELECT * FROM sctable";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo '<div class="col-sm-4">';
echo '<h3>image </h3><br>';
$link = "http://localhost/sc/uploads/" .$row[1];
echo '<img style="width:100%;height:200px" src="' . $link . '"/>';
echo '</div>';
}
?>
Just for future reference, its a bad idea to use the full url for your own site in code like this. If you move it to a live site this code wont work anymore. Better to use relative paths and let the system do some of the work for you. So it should work whatever the domain is where you move the code.
<?php
$sql = "SELECT * FROM sctable";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo '<div class="col-sm-4">';
echo '<h3>image </h3><br>';
> Changed next line
$link = "sc/uploads/" .$row[1];
echo '<img style="width:100%;height:200px" src="' . $link . '"/>';
echo '</div>';
}
?>
You can just wrap the image:
echo "<div class='col-sm-4'> <img width='100%' height='200' src='$link' /></div>";
I have to print customer name once and all the products for each customer.My code is below.
<div id="Allproducts">
<?php
$AllprodsRes = $conn -> query("select * from sepproducts");
if($AllprodsRes ->num_rows > 0){
$result = $AllprodsRes -> fetch_array();
?>
<label for="name"><?php echo $result['name'] . " " . $result['surname']; ?></label>
<?php } ?>
<?php do{ ?>
<p><?php echo $result['product_name'] . " " //$result['count']; ?></p>
<?php }while($result = $AllprodsRes -> fetch_array()); ?>
</div>
view sepproducts
CREATE
ALGORITHM = UNDEFINED
DEFINER = `root`#`localhost`
SQL SECURITY DEFINER
VIEW `sepproducts` AS
select
`customers`.`name` AS `name`,
`customers`.`surname` AS `surname`,
`custproducts`.`product_name` AS `product_name`,
count(0) AS `count`
from
(`custproducts`
join `customers` ON ((`custproducts`.`custid` = `customers`.`custid`)))
group by `custproducts`.`product_name`
Any help is welcome and appreciated.
Thanks in advance.
What you can use is something like the following (assuming you use MySQLi):
<?php
$con = new mysqli('localhost', 'username', 'password', 'db');
$query = $con->query('SELECT * FROM...');
$currentCustomer = null;
while ($result = $query->fetch_array()) {
$name = $result['name'] . ' ' . $result['surname'];
// Check to see if we're working with a new customer.
if ($currentCustomer != $name) {
echo $name . '<br />';
$currentCustomer = $name;
}
echo $result['product_name'] . '<br />';
echo $result['product_type'] . '<br />';
// ETC.
}
?>
Or if you only have one customer to worry about, use the following:
<?php
$con = new mysqli('localhost', 'username', 'password', 'db');
$query = $con->query('SELECT * FROM...');
if ($query->num_rows > 0) {
$result = $query->fetch_array();
echo $result['name'] . ' ' . $result['surname'] . '<br />';
do {
echo $result['product_name'] . '<br />';
echo $result['product_type'] . '<br />';
// ETC.
} while ($result = $query->fetch_array());
}
?>
In effect, it checks if records have been found and if so, writes one result to our array $result. We then output the customer's name OUTSIDE of the loop (so this only occurs once), then use a do...while() loop to continue through the rest of the result array.
I hope this helps!
Depending on the databse you use you could join multiple rows into a single column. Ultimately this is a display problem. I say keep doing what you are doing and in your view keep track of the current name in the loop and compare to the next name - if the name is the same ignore it, when the name differs set current_name to this new name and continue. This way each name only shows once.
Hey guys hope someone can help with this.
I am using substr to give an abstract of articles. Now the problem is when you click the link to see the whole article you still see the substr version. Now this obviously happens because of the way the code is.
I need to make another query that will say if someone clicks the link then display the full article without the substr. I have no idea how to go about this can anyone help? While I am learning my PHP knowledge is fairly limited.
<?php
class MyCMS
{
function get_content($id = "")
{
if ($id != ""):
$id = mysql_real_escape_string($id);
$sql = "SELECT * FROM content WHERE blog_id = '$id'";
$return = '<p> Go Back To Content Page</p>';
else:
$sql = "SELECT blog_id, title, date, body FROM content ORDER BY blog_id DESC LIMIT 0, 3";
endif;
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res) !=0):
while($row = mysql_fetch_assoc($res))
{
echo '<div id="roundedbox"><h2>' . $row['title'] . ' </h2>';
echo '<div id="date"><h5><p>' . $row['date'] . '</p></h5></div>';
echo substr('<p>' . $row['body'] . '</p>',0, 90)." .... "." read more </div>";
}
else:
echo '<p> UH OOH! THERE IS NO SUCH PAGE IT DOES\'T EXIST </p>';
echo $return;
endif;
}
}
?>
Normally you would encapsulate the article into a data class (alias "Model", see MVC architecture). This model holds all the data of the article and have a method to return the abstract or the long version of the article. To identify the version the client would like to see, pass another argument to your URL.
class Article {
protected $text;
protected $title;
public __construct ($title, $text) {
$this->title = $title;
$this->text = $text;
}
/**
* Returns the short excerpt of the article
*/
public getShortAbstract () {
// your substr() function
}
/**
* Returns the full article
*/
public getText () {
return $this->text;
}
}
Add another argument to the function to determine whether it returns the full article or an excerpt:
<?php
class MyCMS
{
function get_content($id = "", $excerpt = FALSE)
{
if ($id != ""):
$id = mysql_real_escape_string($id);
$sql = "SELECT * FROM content WHERE blog_id = '$id'";
$return = '<p> Go Back To Content Page</p>';
else:
$sql = "SELECT blog_id, title, date, body FROM content ORDER BY blog_id DESC LIMIT 0, 3";
endif;
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res) !=0):
while($row = mysql_fetch_assoc($res))
{
echo '<div id="roundedbox"><h2>' . $row['title'] . ' </h2>';
echo '<div id="date"><h5><p>' . $row['date'] . '</p></h5></div>';
if ($excerpt):
echo substr('<p>' . $row['body'] . '</p>',0, 90)." .... "." read more </div>";
else:
echo '<p>' . $row['body'] . '</p>';
}
else:
echo '<p> UH OOH! THERE IS NO SUCH PAGE IT DOES\'T EXIST </p>';
echo $return;
endif;
}
}
?>
Then when you are calling the get_content() function, pass it the id and excerpt flag as follows:
get_content(123, TRUE); //for excerpt
get_content(123); //for full post
I don't think you want to do this with PHP, because when you're doing this with PHP you have to refresh the whole page.
I would advise you to use Javascript for this, like the jQuery library slideToggle.
With this method, Google will still index all the content.