PHP image display from mysql from different tables [closed] - php

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 am creating a used car website for a class. I have a mysql database that has two tables. One for the car details and one table for car photos. I am trying to display 1 single photo of the car next to some details (like you see on cars.com) but I am struggling. The car id is one one table and the "ext_1" in on another table.
<?php
$page_title = "List cars";
require_once ('includes/header.php');
require_once('includes/database.php');
//select statement
$sql = "SELECT * FROM inventory_tbl, inventory_photos_tbl";
//execute the query
$query = $conn->query($sql);
//Handle selection errors
if (!$query) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "Selection failed with: ($errno) $errmsg<br/>\n";
$conn->close();
//require_once ('includes/footer.php');
exit;
}
//display results in a table
?>
<h2>Inventory</h2>
<table border="1px solid" border="collapse" align ="center" height='300' width='750' >
<tr><center>
<th></th>
<th>Year</th>
<th>Make</th>
<th>Model</th>
<th>Mileage</th>
<th>Price</td>
<th>Details</th>
</center>
</tr>
<?php
//insert a row into the table for each row of data
while (($row = $query->fetch_assoc()) !==NULL){
echo "<tr>";
echo "<td><img src =" .$row['id']. $row['ext_1']. " width = 100 height = 100></td>";
echo "<td>", $row['year'], "</td>";
echo "<td>", $row['make'], "</td>";
echo "<td>", $row['model'], "</td>";
echo "<td>", number_format($row['mileage']), "</td>";
echo "<td>","$", number_format($row['price']), "</td>";
echo "<td><a href='cardetails.php?id=", $row['id'],"'>View Details</td>";
echo "</tr>";
}
?>
<?php
// clean up resultsets when we're done with them!
$query->close();
// close the connection.
$conn->close();
//include the footer
require_once ('includes/footer.php');

I'm moving my answer out of the comments, so future readers are able to benefit from the solution.
First, the query needs to qualify the join condition, so change the query to:
$sql = "SELECT * FROM inventory_tbl, inventory_photos_tbl WHERE inventory_tbl.id = inventory_photos_tbl.ext_1"
Second, the img tag should only refer to the photo source/column, so it should be something like:
echo "<td><img src =" .$row['myPhotoColumn']. " width = 100 height = 100></td>";

What you're wanting to do is a left join. (Join data from the right table into the left table if the data in the right table exists).
Your SQL statement would look like this.
$sql = "SELECT * FROM inventory_tbl
LEFT JOIN inventory_photos_tbl as images
ON images.ext_1 = car_id";
Images serves as an alias to your photos table.
You match up images.ext_1 column to the main table's car_id column which is what the ON statement signifies. Think of it as a where clause for the JOIN
Now you can reference any of the data in the inventory_photos_table you want in your PHP using your $row variable such as $row['image_column_name'].
You'll probably want to wrap the image data in an if statement to show a placeholder image in case there isn't an image associated with the vehicle yet.

As i don't know your table structure. I assumed the relational column name as 'id' in inventory_photos_tbl table.
<?php
$sql = "SELECT * FROM inventory_tbl";
$query = $conn->query($sql);
while (($row = $query->fetch_assoc()) !==NULL){
$carID=$row['id'];
// In this query, i'm assuming the relational column as 'id'. (If you are having different column name, please change it here itself)
$imgQuery = $conn->query("SELECT * FROM inventory_photos_tbl WHERE id=$carID LIMIT 0,1");
while(($rowImg = $imgQuery->fetch_assoc()))
{
$carIMG=$rowImg['ext_1'];
}
echo "<tr>";
echo "<td><img src ="$carID.$carIMG" width = 100 height = 100></td>";
echo "<td>", $row['year'], "</td>";
echo "<td>", $row['make'], "</td>";
echo "<td>", $row['model'], "</td>";
echo "<td>", number_format($row['mileage']), "</td>";
echo "<td>","$", number_format($row['price']), "</td>";
echo "<td><a href='cardetails.php?id=", $row['id'],"'>View Details</td>";
echo "</tr>";
}?>

Related

Multiple Tables of same Database on the same site

I want to display 9 different tables from my sql database in 9 different html created tables on the website.
In detail: I have 9 tables ("dt_bookmarks_01", "dt_bookmarks_02" etc.) with 4 columns "id" (which is primary and auto increment), icon (for favicon), link (url) and text (for the display text).
I've created 9 different html tables with bootstrap and want to output the content of each table in a different bootstrap table of my site.
My problem is that i have no idea how to get different "foreaches" or counter for each different table.
To automaticaly add new rows to the bootstrap table I use the count and foreach function. problem here is: I dont know how to seperate them from each other. If i have 4 entries in sql table 1 it multiplies the one and only entrie of sql table 2 to match the current count of 4.
I am very new to sql and php so I guess I just miss some fundamental functions or something.
document header:
php
$sql = "
SELECT *
FROM dt_bookmarks_01, dt_bookmarks_02";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
$conn->close();
and for the html table I use:
php
<tbody>
<!--begin: SQL Selection -->
<?PHP
$count = 0;
foreach($rows as $item){
if (!empty($item['icon'])) {
$icon = '<img src="assets/media/bm-icons/'. $item['icon'] . '">';
}else{
$icon = '<img src="assets/media/bm-icons/default.png">';
}
$count++;
echo "<tr>";
/*echo "<td>" . $count . "</td>";*/
echo "<td> " . $icon . "</td>";
echo "<td> <a href=\"" . $item['link'] . "\"'>" . $item['text'] . "</a> </td>";
echo "<td></i> ";
echo "</i></td>";
echo "</tr>";
}
?>
<!--end: SQL Selection -->
</tbody>
I do not have a database on hand to give you an answer with complete code, but here is the idea:
<?php
for ($i = 1; $i <= 9; $i++)
{
$query = "SELECT index1,index2 FROM dt_bookmarks_0$i";
echo "<h1>This is the content of table $i</h1>";
# RUN THE QUERY HERE !!!
echo "<table>";
# EXTRACT THE RESULTS
foreach $rows as $item
{
echo "<tr><td>$item[index1]</td><td>$item[index2]</td></tr>"
}
echo "</table>";
echo "<br><br>";
}
?>
Loop on your tables.
In each table loop, you output the HTML code to display it's content.
Avoid SELECT *, specify your indexes (research "sql why avoid SELECT *")
So you loop twice. One time to go through the tables, the other to loop on the results.
so here is the new working code.
header:
<?PHP
require_once('/htdocs/_nt/mysql/data.php');
$sql = "
SELECT *
FROM dt_bookmarks";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
$conn->close();
?>
and for the table output:
<?PHP
$count = 0;
foreach($rows as $item){
if ($item['category'] == talk) {
$count++;
echo "<tr>";
echo "<td> " . $icontalk . "</td>";
echo "<td> <a href=\"" . $item['url'] . "\"'>" . $item['text'] . "</a> </td>";
echo "</tr>";
}else{
echo "";
}
}
?>

How could you use PHP and a SQL database to change HTML <h> content?

I have a webpage that displays cars from the first car in the table to the last car with a while loop.
I have the following columns: Make, Model, Price. In my syntax I have an anchor tag around the Make rows that links to the description page of the Make you click on.
I want my <h> tags to change to the Model of the corresponding Make.
I've spent over an hour trying to achieve this but all I could come up with is this:
<?php
$query = "SELECT Model FROM inventory;";
$Vtitle = $conn->query($query);
$Vtitle_ar = mysqli_fetch_assoc($Vtitle);
echo "<h1>".$Vtitle_ar['Model']."</h1>";
?>
This works to an extent.
Every anchor I click replaces the <h> tags with only the first result under the Model column in my database.
Here is my code for the the entire car inventory page
<?php
$query = "SELECT * FROM inventory;";
/* Try to query the database */
if ($result = $conn->query($query)) {
// Don't do anything if successful.
}
else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
// Create the table headers
echo "<table id='Grid' style='width: 80%'><tr>";
echo "<th style='width: 50px'>Make</th>";
echo "<th style='width: 50px'>Model</th>";
echo "<th style='width: 50px'>Asking Price</th>";
echo "</tr>\n";
$class = "odd"; // keep track of whether a row was even or odd, so we can style it later
// Loop through all the rows returned by the query, creating a table for each row
while ($result_ar = mysqli_fetch_assoc($result)) {
echo "<tr class=\"$class\">";
echo "<td><a href='viewcar.php?VIN=".$result_ar['VIN']."'>".$result_ar['Make']."<a></td>";
echo "<td>".$result_ar['Model']."</td>";
echo "<td>".$result_ar['ASKING_PRICE']."</td>";
echo "</td></tr>\n";
// if the last row was even, make the next one odd and vice-versa
if ($class=="odd") {
$class = "even";
}
else {
$class = "odd";
}
}
echo "</table>";
$conn->close();
?>
Does anyone how I can do this?
I'm new to programming and I'm trying to use this for an actual project I'm working on for a hair salon's website
Add a WHERE clause to the query.
$vin = $_GET['VIN'];
$stmt = $conn->prepare("SELECT Model FROM inventory WHERE VIN = ?");
$stmt->bind_param("s", $vin);
$stmt->execute();
$stmt->bind_result($model);
$stmt->fetch();
echo "<h1>$model</h1>";
Though not a solution resolved with the use of a where clause as given by #Barmar whilst formatting the code I did find an error within the HTML which was not immediately obvious
The line echo "</td></tr>\n"; has an extra </td> which would break the flow of the html and can have detrimental effects. Also, // Don't do anything if successful. makes no sense - if there are results then process the recordset otherwise show the error ;-)
<?php
$query = "SELECT * FROM inventory;";
if ( $result = $conn->query( $query ) ) {
echo "
<table id='Grid' style='width: 80%'>
<tr>
<th style='width: 50px'>Make</th>
<th style='width: 50px'>Model</th>
<th style='width: 50px'>Asking Price</th>
</tr>";
$i=0;
while( $result_ar = mysqli_fetch_assoc( $result ) ) {
$class = $i %2 == 0 ? 'even' : 'odd';
echo "
<tr class='$class'>
<td><a href='viewcar.php?VIN={$result_ar['VIN']}'>{$result_ar['Make']}<a></td>
<td>{$result_ar['Model']}</td>
<td>{$result_ar['ASKING_PRICE']}</td>
</tr>";
$i++;
}
echo "</table>";
} else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
$conn->close();
?>
For styling alternate table rows ( the above uses a modulus function to calculate odd/even ) you can do it with some simple CSS - such as
tr:nth-child( odd ){/* rules */}

Diplay All Records, But Distinct?

I'm trying to display all the records in tbInventory, but there are multiple duplicates on the records, specifically under the colItem column. Now what I'm trying to show are all the records in tbInventory but I want it in a way that it will only show an item once if it has a duplicate.
Now my current code displays this:
As you can see, its printing all the items with the colItem values of 'Access Point'. I only want the code to display the item 'Access Point' only once even if it has duplicates.
Now I can't simply use the DISTINCT function as I'm also using the code block for the printing of the data. Here's my current code:
$con=mysqli_connect("localhost","root","","dbDssInventory");
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL " . mysqli_connect_error();
}
$result=mysqli_query($con,"SELECT * from tbInventory ORDER BY colItem");
if($result != NULL){
while($row=mysqli_fetch_array($result))
{
echo "<table border=0 style=\"table-layout:fixed;\">";
echo "<tr>";
echo "<td align=left width=15 style=\"word-wrap:break-word;\">";
echo "<div class=\"hover_img\">";
echo " <a href=\"#\">";
echo " <img src='MAGNIFYINGGLASS.png' alt='Point' width='70%'><em>
<object data=" .$row['colImage']. ".PNG width='850%' type=\"image/png\">
<img src=\"default.png\" width='850%'>
</object>";
echo "</td>";
echo "<td align=left width=160 style=\"word-wrap:break-word;\" style=\"word-wrap:break-word;\">";
echo $row['colItem'];
echo "</td>";
$itemname= $row['colItem'];
Is there a way to execute this?
Instead of
$result=mysqli_query($con,"SELECT * from tbInventory ORDER BY colItem");
Try this:
$result=mysqli_query($con,"SELECT * from tbInventory GROUP BY colItem ORDER BY colItem");
You will get the item 'Access Point' only once even if it has duplicates. Hope it helps!

Can you store selected sql query values in the url and then retrive them with $_GET?

I'm trying to make it so that when a users clicks one of the rows,it will take them to a new page whose link is given as the value of the row they selected and then retrieve the value with $_GET["timesub"].
Anyone know how to do this?
mysql_select_db("RRRC", $con);
$result = mysql_query("SELECT * FROM mainreq WHERE roomnum=$loc");
echo "<table border='1'>
<tr>
<th> Submitted </th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td> . $row['timesub'] . </td>";
echo "</tr>";
}
echo "</table>";
Assuming that $row['timesub'] identifies a row in your data set (I doubt it), just fix your echo instruction as:
echo "<td>" . $row['timesub'] . "</td>";
Escaping the html quotes properly.
echo "<td><a href='roomdata.php?timestamp=".$row['timesub']."'>".$row['timesub']."</a></td>";
Close the outer " before the . concatenator, replace the inner " with '
A good practice is to use the row's primary key to reference your get query; but yes - this can be done.
All you have to do is store the get data into a sanitized variable, and perform the required SQL lookup / data display.
EX:
$roomnum=mysql_real_escape_string(preg_replace("/[^a-zA-Z0-9]+/", "", $_GET['roomnum']));
Now, given that "roomnum" is your primary key just look it up and display:
$result = mysql_query("SELECT * FROM mainreq WHERE roomnum='$roomnum'");
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td> . $row['timesub'] . </td>";
echo "</tr>";
}
echo "</table>";

getting two kinds of data and display it out [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 8 years ago.
Improve this question
I have a table called "profile" in mysql database
Table structure:
user | hasimg | imgurl
As you can see "hasimg" and "imgurl", normally if a user does not have an image, hasimg will be set to 0 and imgurl is set to none.
On the other hand, if a user has an image assigned then hasimg is set to 1 and imgurl will contain the link.
How can I display ones that have images (hasimg set to 1) with <img src="imgurl html tags?
How can I display ones that do not have images (hasimg set to 0) , without <img src?
I want to make a list which display users with images and user that does not have image.
Here's the code im using to echo out the data row by row
<?php
$sql = "SELECT * FROM profile ORDER BY user DSC";
$query = mysql_query($sql)or die(mysql_error());
$rows = array();
while($row = mysql_fetch_array( $query )){
$rows[] = $row;
echo "User:$row[user]<br>Image:$row[hasimg]\n";
}
?>
P/S mysql connection established.
If you want to keep your layout fancy way you can use default image.
if($hasimg == 0)
$imgurl = "default.jpg";
echo '<img src="' . $imgurl . '">';
EDIT:
Your PHP code could be like this.
$sql = "SELECT * FROM profile ORDER BY user DSC";
$result = mysql_query($sql)or die(mysql_error());
echo "<table border='1'>
<tr>
<th>Name</th>
<th>Image</th>
</tr>";
while($row = mysql_fetch_array($result))
{
$imgurl = $row['imgurl'];
if($row['hasimg'] == 0)
$imgurl = "default.jpg";
echo "<tr>";
echo "<td>" . $row['user'] . "</td>";
echo "<td><img src=\"" .$imgurl . "'\" /></td>";
echo "</tr>";
}
echo "</table>";
Two solutions:
Set a pathway to default img jpg file as default field content to field imgurl in your database.
Filter query results by adding this code just after $rows[] = $row;:
If ($row['hasimg'] == 0) $row['imgurl'] = 'default.jpg';

Categories