How to show one image instead of four images - php

In Mysql database I have column name "product_id" and there is while statement code to check if row exist ...
If value of product_id exist, then it will show "note-icon.png" image, if not exit it will say "No" but the problem is that let say that in "product_id" has four product_id's SAME NUMBER and then result will SHOW FOUR images, my question is that how to write code to show ONE image instead of FOUR images!
<?php
$sql = new mysqli($mysql_hostname, $mysql_user, $mysql_password, $mysql_database);
$query = "SELECT * FROM notes WHERE product_id = $product_id";
$results = mysqli_query($sql, $query);
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)){
if(isset($row['$product_id'])) {
echo "<p>No </p>";
} else {
echo '<img src="images/note-icon.png" width="16" height="16" />';
} }
?>

Select only one row:
MySQL:
SELECT * FROM notes WHERE product_id = ? LIMIT 1
SQL:
SELECT FIRST 1 * FROM notes WHERE product_id = ?
If you want to get all notes but draw one image per product you can do this:
$product_ids = array();
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)){
if(!isset($row['product_id'])) {
echo "<p>No </p>";
} else {
if(!isset($product_ids[$row['product_id']])) {
$product_ids[$row['product_id']] = 1;
echo '<img src="images/note-icon.png" width="16" height="16" />';
}
}
}
Some code annotations:
$product_id in your query allowed, only if you are cast it to int before
else use placeholders (prepared statements)
if(isset($row['$product_id']))
What's this? think should be:
if(!isset($row['product_id']))
also you forgot to check $results, that it is not false, before using..

U can use grouping
SELECT * FROM notes WHERE product_id = ? GROUP BY product_id

Related

Selecting And Displaying Data with the same category from mysql database to my Webpage by click of a button

php code to get table id`
include_once('dbconfig/dbcon.php');
$upload_dir = 'images/';
if(isset($_GET['brand_id'])){
$id = $_GET['brand_id'];
$sql = "SELECT * from btype where brand_id=".$id;
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_assoc($result);
}else{
$_SESSION['msg']= 'Could not select record';
}
}
`
display data in webpage`
<img src=" echo $upload_dir.$row['bom_pic']; " width= "100" height="100%">
echo $row['bspects'];
<small>Email : </small><?php echo $row['bemail'];?></h5>`
button to retrieve data and display
.$row["bname"].'
`
the problem is instead of listing all bname inthe same category it is only displaying one bname

PHP & SQL Photo Gallery Placeholder Image

I have a function called RandomPic() it will display a Random Photo from the Database. Now i want a Placeholder Image for the Gallerys Categories that are empty. but my code doesnt work. it doesn't show the placeholder image....any ideas? here is the code:
$sql = "SELECT * FROM wp_gallery WHERE catid = $id ORDER BY RAND() LIMIT 1";
if($result = $conn->query($sql)){
while ($row = mysqli_fetch_array($result))
{
if (mysqli_num_rows($result) > 0) {$imglos = '<img class="img-responsive" src="http://www.anyurl.com'.$row["filename"].'">';}
}
}
else{$imglos = 'PLACEHOLDERIMAGE GOES HERE';}
return $imglos;
}
Slightly change your code structure:
$sql = "SELECT * FROM wp_gallery WHERE catid = $id ORDER BY RAND() LIMIT 1";
if($result = $conn->query($sql))
{
if (mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_array($result))
$imglos = '<img class="img-responsive" src="http://www.anyurl.com'.$row["filename"].'">';
}
else
$imglos = 'TEST';
return $imglos;
}
else
return "database error!";
Some notes:
The mysqli_num_rows never changes after executing a query: it returns the number of rows in the resultset. So it makes no sense to check for this within a while.
There is no need for while, because your query can only return 0 or 1 results. If you do want to return multiple images you can append to $imglos:
while ( $row = mysqli_fetch_array($result) )
$imglos .= '<img class="img-responsive" src="http://www.anyurl.com'.$row["filename"].'">';

Returning each unique user from a MySQL table and also the count of the number of rows for each user

I am using the following MySQL query to generate a table for users in a database. The query is designed to just return one row for each user, even though there are multiple rows for each user. This works fine, however I also need to calculate the number of unique entries for each user, to enter into the table where it states HERE. Do I need to use another query to return the count for all entries, and if so how do I integrate this with the code I already have?
$query="SELECT from_user, COUNT(*) AS num FROM tracks GROUP BY from_user ORDER BY COUNT(*) DESC";
$result=mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$user = $row['from_user'];
echo "<tr>";
echo "<td>".$user."</td>";
echo "<td>uploads (**HERE**)</td>";
echo "<td>favourites (count)</td>";
echo "</tr>";
}
?>
</table>
Because you've already created the custom field 'num', you can use that to get the count!
Add the following line after user = ...
$count = $row['num'];
Then you can
echo "<td>uploads ($count)</td>";
It miss your table stucture to know your field name, but, if i well understand your question you can use count + distinct in mysql.
You can check this answer too.
SELECT DISTINCT(from_user) AS user,
COUNT(from_user) AS num
FROM tracks
GROUP BY from_user
ORDER BY num DESC";
For the second problem you can doing a second query, or do a join tracks .
I think, in your case it's easier to you to do se second query inside the loop to get all detail from 'user' result.
$query1="SELECT DISTINCT(from_user), COUNT(*) AS num
FROM tracks
GROUP BY from_user
ORDER BY COUNT(*) DESC";
$query2="SELECT * FROM tracks";
$result1=mysql_query($query1) or die(mysql_error());
$result2=mysql_query($query2) or die(mysql_error());
$user_array = array();
while ($row = mysql_fetch_array($result1)) {
$user = $row['from_user'];
$num = $row['num'];
$uploads_array = array();
while ($sub_row = mysql_fetch_array($result2)) {
if( $sub_row['from_user'] == $user ) {
//for example only due to the unknown structure of your table
$uploads_array[] = array(
"file_name" => $sub_row['file_name'],
"file_url" => $sub_row['file_url']
);
}
}
$user_array[] = array(
"name" => $user,
"num_entry" => $num,
"actions" => $uploads_array
);
}
// now the table with all data is stuctured and you can parse it
foreach($user_array as $result) {
$upload_html_link_arr = array();
$user = $result['name'];
$num_entry = $result['num_entry'];
$all_actions_from_user_array = $result['actions'];
foreach($all_actions_from_user_array as $upload) {
$upload_html_link_arr[] = sprintf('%s', $upload["file_url"],$upload["file_name"]);
}
$upload_html_link = implode(', ',$upload_html_link_arr);
$full_row = sprintf("<tr><td>%s</td><td>uploads : %s</td><td>favourites (%d)</td></tr>", $user, $upload_html_link, $num_entry);
// now just echo the full row or store it to a table for the final echo.
echo $full_row;
}
I hope this help, mike

PHP - Multiple MySQL result, in separate variables

I need to do a MySQL query to search for an inexact match / match containing the submitted value.
The following is an example of what is in my database:
id img
1 1001_ABC_01.jpg
2 1001_ABC_02.jpg
3 1002_ABC_01.jpg
4 1002_ABC_02.jpg
5 1002_ABC_03.jpg
6 1002_ABC_04.jpg
7 1002_ABC_05.jpg
8 1003_ABC_01.jpg
9 1003_ABC_02.jpg
10 1003_ABC_03.jpg
I need the query to search for the first part of the filename (1002) and and assign each returned result in the img field a different variable. The maximum amount of variables would be 5.
For example, if I search 1002, it should assign the following variables:
<?php
$img1 = '1002_ABC_01.jpg';
$img2 = '1002_ABC_02.jpg';
$img3 = '1002_ABC_03.jpg';
$img4 = '1002_ABC_04.jpg';
$img5 = '1002_ABC_05.jpg';
?>
so that way I can echo each filename result individually.
Again, the maximum amount of variables here will be 5, so if more than 5 results are returned, only the first 5 will be assigned variables.
Please let me know if this is possible and how to write a PHP script to do it.
SELECT img FROM <table_name> WHERE img LIKE '%search%' ORDER BY ID DESC LIMIT 5;
You could substring function, if the first four integers are fixed like this:
select substring(img,1,4) from <table_name> where img = 'search' order by ID DESC limit 5;
I hope this will help you. Always try to use latest apis and function like MySqli try to avoid mysql_* functions because they are depreciated and MySqli is also faster then mysql_ functions
$img = '1002'; // For example
$connection = new Mysqli(host, user, password, database);
$sql = "SELECT img FROM <table_name> WHERE img LIKE '$img%' LIMIT 5";
if($connection->query($sql)){
$counter = 1;
while ($row = $connection->fetch_object()){
${'img'.$counter} = $row->img;
$counter++;
}
}
$query = "SELECT * FROM my_table WHERE img_name LIKE '%1002%' LIMIT 5";
foreach ( $fetched_row as $value ) {
echo $value [ 'img_name' ]; // or whatever you want to do
}
Something like that.
Use this query
SELECT img as IMG
FROM my_table
WHERE img LIKE '1002%'
order by id desc
LIMIT 5
<?php
$query="SELECT id,img as image FROM image_table
where img like '%$keyword%' limit 5";
$res=mysql_query($query) or die(mysql_error());
while ($img = mysql_fetch_array($res)) {
echo $img['image'];
}
?>
$con = new Mysqli(host, user, password, database);
$result = $con->query("SELECT * FROM table WHERE image LIKE %$search% ORDER BY id DESC LIMIT 5");
if($result){
while ($row = $con->fetch_object()){
$img_arr[] = $row;
}
}
I hope this will help you.
$queryStr = "SELECT img FROM table_name WHERE search_str LIKE '1002%'";
$query = mysql_query($queryStr);
while($row = mysql_fetch_assoc($query)){
$imageArray[] = $row;
}
// Print the array
echo '<pre>';
print_r($imageArray);
echo '</pre>';
// How to use the array
foreach($imageArray as $key=>$val){
echo 'File Name: '.$val;
echo '<br />';
echo '<img src="'.$val.'" />';
echo '<hr />';
}
// Now show first five result
// Alternet: You can use LIMIT and order by with mysql
// With php
for($i=0;$i<5;$i++){
echo 'File Name: '.$imageArray[$i];
echo '<br />';
echo '<img src="'.$imageArray[$i].'" />';
echo '<hr />';
}
To search for a partial match you can use the LIKE operator in SQL. In this case you could write:
$sql = "SELECT img FROM tablename WHERE img like '1002%'";
How to perform this query and obtain the results in PHP depends on the database API you are using: old MySQL? MySQLi? PDO? Also, 1002 is probably user input, in which case you have to protect your program against SQL injection attacks.
As to the second part, are you sure you want different variable names and not an array? Arrays are much easier to use. You can get different variable names if you first accumulate the data in an array and then use extract:
$result = array();
$counter = 1;
$rs = mysql_query($sql); // using old mysql API
while ($row = mysql_fetch_array($rs)) {
$result["img".$counter] = $row[0];
$counter = $counter + 1;
}
extract($result);
// now $img1, $img2, $img3, ... are defined
your code will look like this:
$input = '1002'; // For example
$query = "SELECT id, img FROM table_blah WHERE img LIKE '$input%' LIMIT 5";
This query is basically selecting id, and img from the table table_blah, and img must be the same as 1002, and % meaning absolutely anything from there on. Limited to 5 results.
Then:
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
// Code for each result here.
// id = $row['id']
// img = $row['img']
}
$query = "SELECT * FROM img_table WHERE img_name regexp concat('1002', '%')"
$results = mysql_query($query);
then $results is an array of img strings

Display image for a Yes or No value in mysql table display

I have a table where one of the values is either Yes or No. I would like to have the value represented by an image according to the value. Table is also using pagination and am using code to alternate row color. Code:
<?php
$sql = "SELECT * FROM txmit ORDER BY id ASC LIMIT $start_from, 25";
$rs_result = mysql_query ($sql);
$num_rows = mysql_num_rows($rs_result);
$query = mysql_query("SELECT * FROM txmit");
$number=mysql_num_rows($query);
`while($rows=mysql_fetch_array($rs_result)){
// If $color==1 table row color = #747E80
if($color==1){
echo "<tr bgcolor='#DBDBDB'>
<td>.$rows['pid']."</td><td>".$rows['sent']."</td></tr>
?>
The $rows['sent'] is the Yes or No value...how do I get it to display image based on Yes or No value.
thanks
You could do this:
echo "<img src=img/" . $rows['sent'] == 'Yes' ? 'yes.png' : 'no.png' . ">";
If they're really just Yes and No you could also use:
echo "<img src=img/" . $rows['sent'] . ".png>"; // Yes.png or No.png
If the image path gets a bit longer I'd agree with Blazemonger's comment and make it more readable:
echo '<img src=very/long/image/path/';
if($rows['sent'] == 'Yes') {
echo 'yes.png >';
} else {
echo 'no.png >';
}

Categories