PHP Count Images Search Results - php

I have a search results page which displays items from a MySQL database (table1). The code I am using to the display the results is:
if (!empty($data)) {
foreach ($data as $item) {
echo '<div class="item">';
if (strlen($item['item_desc']) > 10) {
if (strlen($item['item_link']) > 10) {
echo '<a href="/item.php?id='.$item['item_id'].'">';
} else {
echo 'No Results Found';
}
}
}
}
The images for each search result are stored in a separate table (table2). I am trying to use the code below to count the number of images in table2 for each result and display the number against each result on the search results page, but it returns a 0 value?
$result=mysql_query("SELECT count(*) as total from table2 where id = '" .$item['item_id']. "'");
$query=mysql_fetch_assoc($result);
echo $query['total'];

I am missing some data about your database structure but I can imagine you store your image id as an integer and you are requesting the count with the id being a string.
So, if I'm true this may help. Remove the quotes around the php variable with the item_id
"SELECT count(*) as total from table2 where id = " .$item['item_id'];

you can try this..
$str=$item['item_id'];
mysql_query("SELECT count(*) as total from table2 where id = '$str'");

There is a mysql function to count rows outputted from your mysql query, it is mysql_num_rows(). From what I can understand about your database your code could be this:
$item_id = $item['item_id'];
$result = mysql_query("SELECT * FROM table2 where id = '$item_id'");
$count = mysql_num_rows($result);
echo $count;
This will output how many records match your query.

Related

Add field /column to array

From mysqli request I receive a result that contains a table with 5 columns and a number of rows. I would like to perform a calculation with my data that I just received and add the result of my calc in a NEW COLUMN in my array.
So in different words, I would like to add one column to the array and fill this column with results for each row.
My code so far looks as follows and of course only prints the array that I receive from my SQL query:
<?php
error_reporting(0);
require 'init1.php';
if($result = $db->query("Select * from (select * from(SELECT * FROM `scores`
ORDER BY `battle_id` ASC,user_id asc,score desc) as t1 GROUP BY
t1.battle_id, t1.user_id) as t2 order by `battle_id` ASC,score desc")){
if($count = $result->num_rows){
echo '<p>' , $count, '<p>';
while ($row = $result->fetch_object()){
echo $row->battle_id, ' ' , $row->user_id, ' ' , $row->score, '<br>';
}
//instead of just printing the existing array, I would like to perform a
//calculation and add a result in a new column at the end of every single
//row
}
}
If you use an Array you can simply 'define' a new item in your array to store the calculation result.
while ($row = $result->fetch_row()) {
// Calculation and other stuff here
$row['calc_result'] = $calculation_result;
}
Then in order to access it outside the while scope, you would need to store each row in another array, for example:
$stored_data = array();
while ($row = $result->fetch_row()) {
// Calculation and other stuff here
$row['calc_result'] = $calculation_result;
array_push( $stored_data, $row );
}

MySQL duplicates results even after using DISTINCT every time I try to show more than one field of the same table

I have a MySQL query that shows a list of items after joining two tables:
SELECT contenidos.tituloContenido FROM contenidos
JOIN cursosContenidos ON cursosContenidos.contenidoID = contenidos.contenidoID
WHERE cursosContenidos.cursoID = ?;
There's no problem with this query, but, when I change it to show another field of the contenidos table, the results are duplicated.
So they get duplicated when doing:
SELECT contenidos.contenidoID, contenidos.tituloContenido FROM contenidos
JOIN cursosContenidos ON cursosContenidos.contenidoID = contenidos.contenidoID
WHERE cursosContenidos.cursoID = ?;
I've tried adding a GROUP BY cursosContenidos.contenidoID clause, and DISTINCT as well, but they keep appearing duplicated. Any idea on why?
To retrieve the results, I'm using PHP:
$mostrarContenidos = $conectar1->prepare("
SELECT contenidos.tituloContenido FROM contenidos
JOIN cursosContenidos ON cursosContenidos.contenidoID = contenidos.contenidoID
WHERE cursosContenidos.cursoID = ?;
");
$mostrarContenidos->bindParam(1, $cursoID);
$mostrarContenidos->execute();
$contenidos = $mostrarContenidos->fetch(PDO::FETCH_ASSOC);
if ($contenidos) {
echo '<h2>Contenidos del Curso</h2>';
foreach ($contenidos as $value) {
echo 'Id: '.$contenidos['contenidoID'].'<br>';
echo 'Title: '.$contenidos['tituloContenido'].'<br>';
}
} else {
echo 'error retrieving results';
}
The expected result is:
Id: 1
Title This is my super title
What I get:
Id: 1
Title This is my super title
Id: 1
Title This is my super title
Your SQL query is most likely not returning multiple rows - you are only outputting it twice. This is because your foreach statement loops over each column in the single row you've fetched, rather than each row of the result set.
To clarify a bit further, this line just fetches the first (and probably only) row:
$contenidos = $mostrarContenidos->fetch(PDO::FETCH_ASSOC);
The foreach loop goes through each column in the row, and outputs info about the whole row for each column.
If you want $contenidos to be an array of all rows, you could do this instead:
$contenidos = $mostrarContenidos->fetchAll(PDO::FETCH_ASSOC);
The problem is not in the query, but in the php.
In your foreach-loop you assign the result-array-elements to $value, but then you don't use $value.
You should use :
echo 'Id: '.$value['contenidoID'].'<br>';
echo 'Title: '.$value['tituloContenido'].'<br>';
This should do it: GROUP BY contenidos.contenidoID, contenidos.tituloContenido
Should work with distinct
SELECT distinct contenidos.contenidoID, contenidos.tituloContenido FROM contenidos
JOIN cursosContenidos ON cursosContenidos.contenidoID = contenidos.contenidoID
WHERE cursosContenidos.cursoID = ?;

PDO multiple select queries

I am trying to get rows out of 2 tables. The first query works. But the second doesn't. This is my code:
echo '<table width="100%">';
echo '<tr><td>Product</td><td>Quantity</td><td>Price</td><td>Remove</td></tr>';
foreach ($_SESSION['cart'] as $key => $cartproduct) {
list($productid, $productquantity) = split("\|", $cartproduct, 2);
global $db;
$result = $db->prepare('SELECT name FROM products WHERE ID= :ID LIMIT 1; SELECT price FROM prices WHERE productid = :ID AND quantity = :quantity LIMIT 1');
$result->bindParam(':ID', $productid);
$result->bindParam(':quantity', $productquantity);
$result->execute();
$row = $result->fetch();
if($result->RowCount() == 1){
echo '<tr><td>' . $row['name'] . '</td><td>' . $productquantity . '</td><td>' . $row['price'] . '</td><td>Remove</td></tr>'; //LINE15
}else{
unset($_SESSION['cart'][$key]);
}
}
echo '</table>';
The row name is from the products table and the name price is from the prices table. This is the error I get:
Notice: Undefined index: price in /var/www/html/design2/pages/cart.php on line 15
I am sure the query is working. Can anyone tell my what i am doing wrong?
You are receiving index not defined because of the way your query is structured. You have:
SELECT name FROM products WHERE ID= :ID LIMIT 1; SELECT price FROM prices WHERE productid = :ID AND quantity = :quantity LIMIT 1
This is structured to return 2 result sets. You grab the first result set here:
$row = $result->fetch();
But then you try to access $row['price'] which doesn't exist in that result set. That result set is only the result from the first SELECT. You can see this if you just var_dump($row) and see what your result set looks like.
It looks like you can combine your query so that you get one result set:
SELECT p.name, pp.price FROM products p
INNER JOIN prices pp ON p.ID = pp.productid
WHERE p.ID= :ID AND pp.quantity = :quantity
LIMIT 1;
If you can't combine the queries into one, then you should iterate over your result sets and access the relevant $row index. That would look something like:
while($row = $result->fetch()) {
if(isset($row['name'])) {
//do something
} else if(isset($row['price'])) {
//do something else
}
}
Some things to consider:
You may need a LEFT JOIN instead of an INNER JOIN. This depends on
whether or not products always have a corresponding record in the
prices table.
I'm not sure what you're trying to achieve with
LIMIT 1. You may need to consider and ORDER BY -- unless it really
doesn't matter which record you return in your result.
You should consider testing your variables $productid and $productquantity to verify they have your intended values after splitting $cartproduct. What if one is empty / blank ?
You should test your result before trying to access the result array at a specific index.
For example:
if(isset($row['name']) && isset($row['price'])) {
//echo your results
} else {
//return an error
}

PHP - how to output a MySQL average store rating in a loop

I have a table with ratings for every store in a directory. I want to display the average rating from each store on a business directory list page. I have the directory business listing page finished without the average rating.
I believe I have figured out how to create an average rating, but I don't know how to get the rating to output in the loop for each store.
Here is how I calculate the rating:
$result = mysql_query("SELECT AVG(rating) FROM reviews GROUP BY store_id WHERE store_id = '$storeid'");
$rating_for_page = mysql_fetch_row($result);
$rating = $rating_for_page[0];
Use the query:
echo "<table>\n";
echo "<tr><th>Store ID</th><th>Name</th><th>Avg. Rating</th></tr>\n";
$result = mysql_query("SELECT s.store_id, s.store_name, AVG(r.rating) AS avg_rating
FROM stores as s
JOIN ratings as r ON s.store_id = r.store_id
GROUP BY s.store_id");
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td>$row[store_id]</td><td>$row[store_name]</td><td>$row[avg_rating]</td></tr>\n";
}
echo "</table>\n";
Then loop through the results of this query. Each row will be the average rating of a different store.
You should iterate through the results if I am understanding the issue correctly. Also, in your MySQL command you need to set an AS for the AVG(rating). And I have set mysql_fetch_assoc (instead of mysql_fetch_row) for the results to be returned in an associative array:
foreach ($storeids as $storeid) {
$result = mysql_query("SELECT AVG(rating) AS rating FROM reviews GROUP BY store_id WHERE store_id = '$storeid'");
while ($row = mysql_fetch_assoc($result)) {
echo $row['rating'];
}
}
EDIT Looking at your query and seeing the $storeid being set, unclear where that value is coming from but I wrapped the solution I have provided in a foreach loop which assumes you have a list—and hopefully an array—that contains all of the $storeids in to loop through.

Getting results from 2 consecutive queries (PHP, SQL)

I need to return data from 2 separate tables at the same time. The info I need from the 2nd table is determined by what is returned from the first table. Here's what I'm working with..
$query = "SELECT * FROM pending WHERE paymentid = '".$_GET['vnum']."'";
$result = mysql_query($query);
$num = #mysql_num_rows($result);
$linkid = $res['paymentid'];
if ($num==0) {
echo "Hello, ".$_SESSION['Fname']."<br />There was an error, I cannot find this payment in the records.";
} else {
$picquery = mysql_query("SELECT * FROM _uploads_log WHERE linkid = '".$linkid."'");
$numb = #mysql_num_rows($picquery);
if ($numb==0) {
echo "there is no picture"; }
else {
echo "<img src=\"".$res['log_filename']."\" width=\"100\">"; }
I don't understand how to return the results as an array, if $res[] returns the results for the first query, then what returns the results for the second one?
or is there a better way to do this entirely?
Thank you
You need to do a join, but in order to still get results from your first query even if there is no picture (I assume that's why you split it up) you want a left join.
select * from pending left join _uploads_log on pending.paymentID=$_GET['vnum'] and _uploads_log.linkid = pending.paymentID
(note: php markings removed for readability - you'll have to add them back in)
This should (untested since I don't have your tables) return the full row for your vnum variable and also include the picture data if there is one.

Categories