Fetch set of images joining tables inside a while loop - php

I just register to Stack Overflow, I looked for a post like this one but what I found was a group of different posts but I'm not smart enough(yet!) to put them together to answer my question.
I like to learn programming with, let's say "real" examples after I finish my online courses or books.
What I would like to achieve
As you can see in my link is what I want to achieve. Initially I had all the data in one table but I've been reading on this site that is not the best practice to store the images paths separated by commas in just one field. So right now I have:
1 table with all the info.
1 table (so far) with a collection of pictures for my first ad.
So, my question is, I don't know how exactly do I have to join the tables and use the while loop to be able to fetch as many pictures as I need per ad, to later on, use those pictures in a Lightbox gallery...
so far I was only able to put 1 picture per ad! :S
my 1st table is structured like this
| ID | HOUSE-TYPE | CITY | TITLE | DESCRIPTION | PICS | SQRMETER | PRICE | TELPHONE | EMAIL
my 2nd table is structured like this:
| ID | PATH | TITLE | ALT |
And my code so far:
$result = mysqli_query($con,"SELECT * FROM t_test");
while($row = mysqli_fetch_array($result))
{
echo "<div class='ad'>" .
"<h2>" . "OFFER " . $row[offer] . $row[house-type] . " in " . $row[city] .
"</h2>" .
"<h1>" . $row[title] . "</h1>" .
"<p>" . $row[description] . "</p>" .
"<img src='" . $row[photo] . "'/>" .
"<p class='pics-per-ad'>" . "TOTAL PICS" . "</p>" .
"<p class='square-meters'>" . $row[sqmeter] . " metros 2" . "</p>" .
"<p class='price'>" . $row[price] . " Euros" . "</p>" .
"<p class='telephone'>" . $row[telphone] . "</p>" .
"<p class='email'>" . $row[email] . "</p>" .
"</div>";
}
mysqli_close($con);
Thanks for your time guys!

There are many solutions for what you are trying to achieve. I would suggest to keep this simple is to have another column in your pics table called linked, this would link your image to your ad.
Try and follow these steps below.
Create a column in your pic table called 'linked'
ALTER TABLE ads ADD linked VARCHAR(255)
create a foreign key relationship between your pics table and your ad's table.
(if your ad gets deleted or updated for example, it will also delete your image from the pics table)
In your code join your tables by doing something like this.
$query = '
SELECT ads.*, pics.* FROM ads
LEFT JOIN pics ON pics.linked = ads.id
';
$result = mysqli_query($con,$query);

Each ad can have multiple pics, so you need to setup a "one-to-many" relationship in your database. You do this by using foreign keys.
In the ads table, each ad has a unique ID already
In the pics table, in addition to each one having it's own unique ID, there should be an additional field for the ads_ID which it belongs to.
When you go to display ad ID x, then you query the db to get all pics with ads_ID x:
"SELECT * FROM pics WHERE ads_ID = x"

Related

How do I stop duplicate rows on table join in SQL?

Trying to join this table, so that i can change the code if the tutor ID matches the session tutor ID. But it shows multiple results in the calendar that its generating.
Below is the current PHP code, although the entries are being duplicated due to having multiple tutor ID's within the table. i'm not sure how to change this.
<?php
$sqlAssignments = "SELECT * FROM tbl_assignments LEFT JOIN tbl_tutorModules ON tbl_assignments.module_code = tbl_tutorModules.module_code"; //
$qryAssignments = mysqli_query($con, $sqlAssignments); // running the query
while($rowAssignment = mysqli_fetch_assoc($qryAssignments)){
if ($_SESSION["ID"] == $rowAssignment['tutor_id']) {
echo "{ title: '" . $rowAssignment['assignment_name'] . "', start: '" . $rowAssignment['hand_in_date'] . "', end: '" . $rowAssignment['hand_in_date'] . "', url: 'view/assignments.php?id=" . $rowAssignment['assignment_id'] . "', color: '#f1f1f1'},";
} else {
echo "{ title: '" . $rowAssignment['assignment_name'] . "', start: '" . $rowAssignment['hand_in_date'] . "', end: '" . $rowAssignment['hand_in_date'] . "', url: 'view/assignments.php?id=" . $rowAssignment['assignment_id'] . "'},";
}
}
?>
The actual results at the moment is that when the tutorModules has multiple tutors, the output duplicates calendar results.
Thanks
Edit: Tables look like this with some example data
tbl_tutorModules
con_id module_code tutor_id
2 ISYS30025 1
3 ISYS30025 2
tbl_assignments
assignment_id
module_code
assignment_name
assignment_weight
set_date
hand_in_date
hand_in_method
assignment_type
This is the current output
The expected output is for these not to be duplicated.
You want to know whether a certain tutor is involved in an assignment. So pass the tutor ID to the DBMS in order to let it find out in a query.
SELECT
assignment_id, assignment_name, hand_in_date,
case when module_code in (SELECT module_code FROM tbl_tutorModules WHERE tutor_id = ?)
then 'yes' else 'no'
end as tutor_involved
FROM tbl_assignments
ORDER BY assignment_id;
As you can see, I don't join the tables, because I'm not interested in the joined result. I merely want to look up a record in tbl_tutorModules. We use IN or EXISTS in SQL to look up records in another table.
See here how to pass parameters to the DBMS in mysqli: http://php.net/manual/en/mysqli.prepare.php

Output the contents from two mysql tables

I need some help with my PHP code. I'm trying to fetch the data from two different tables from the mysql database so I could be able to output each content.
I want to output the contents just like this:
101 BBC One S East
http://www.example.com/bsdev/UK-BBC-1
102 BBC Two
http://www.example.com/bsdev/UK-BBC-2
103 ITV
http://www.example.com/bsdev/UK-ITV-1
Here is what the output show of the contents:
101 BBC One S East
http://www.example.com/bsdev/UK-BBC-1
http://www.example.com/bsdev/UK-BBC-2
http://www.example.com/bsdev/UK-ITV-1
102 BBC Two
http://www.example.com/bsdev/UK-BBC-1
http://www.example.com/bsdev/UK-BBC-2
http://www.example.com/bsdev/UK-ITV-1
103 ITV
http://www.example.com/bsdev/UK-BBC-1
http://www.example.com/bsdev/UK-BBC-2
http://www.example.com/bsdev/UK-ITV-1
Here is the code:
$qrytable1="SELECT id, channels, links, categories FROM channels_list";
$result1 = mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
echo "<p id='channels'>".$row["id"]. " " . $row["channels"]. "</p>";
$qrytable2="SELECT id, channels, streams FROM chris_channels";
$result2 = mysql_query($qrytable2) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result2))
{
echo "<p id='streams'>".$row["streams"]. "</p>";
}
//mysql_close();
//exit;
}
mysql_close();
exit;
Can you please show me an example how I could use to get the contents from two different tables of the database to output the contents I want without looping?
You need to use joins between the tables i.e.
$qrytable1="SELECT id, channels, links, categories, streams
FROM channels_list
INNER JOIN chris_channel ON (chris_channel.channels = channel_list.channels)";
[EDIT]
Both tables have a field called id. You need to define which one you want to display/use/return. I presume it is the one from channels_list so you would need to change the query to:
$qrytable1="SELECT channels_list.id, channels, links, categories, streams
FROM channels_list
INNER JOIN chris_channel ON (chris_channel.channels = channel_list.channels)";

Create download script using php from 3 tables in mysql

I need help from you guys here.
The problem is I have to display download link from a table that connected from other tables, there are three (3) tables.
**First Table:**
file_id | file_title | file_name | file_dir
-------------------------------------------
| | |
**Second Table:**
file_id | books_id
-------------------
**Third Table:**
books_id | books_title | books_author | books_publisher
-----------------------------------------------------------
I just want to create a button that can download the file from the first table, the files was stored in a folder. I was little bit confused, why the developer staff before me that built this scripts (now the person was quit and I cannot contact him) add to three tables for uploaded files. And if I was changed the upload field, I have to changed everything.
Any clue?or link that can help me perhaps?to solve my confusedness.
Thank you for the helps from you guys here.
Sorry for my English. :)
I believe the query you're looking for is:
SELECT t1.file_title, t1.file_name, t1.file_dir,
t3.books_title, t3.books_author, t3.books_publisher
FROM first_table t1, second_table t2, third_table t3
WHERE t1.file_id=t2.file_id AND
t2.books_id=t3.books_id
This assumes the names of your tables are first_table, second_table, and third_table. Feel free to modify accordingly.
To use this result in PHP, you could do something like this:
$sql = "SELECT t1.file_title, t1.file_name, t1.file_dir, " .
" t3.books_title, t3.books_author, t3.books_publisher " .
"FROM first_table t1, second_table t2, third_table t3 " .
"WHERE t1.file_id=t2.file_id AND " .
" t2.books_id=t3.books_id";
$query_result = mysqli_query($sql);
$data = array();
while ($row = mysqli_fetch_assoc($query_result)) {
$row_data = array();
foreach ($row as $key => $value) {
$row_data[$key] = $value;
}
array_push($data, $row_data);
}
foreach($data as $item) {
$path_to_file = $item['file_dir'] . '/' . $item['file_name'];
print "<a href='$path_to_file'>" .
$item['books_title'] .
' (Author: ' . $item['books_author'] . ', ' .
' Publisher: ' . $item['books_publisher'] . ')</a>';
print '<br>';
}
Of course, the outputting of HTML is entirely for demonstration purposes - I don't know exactly what kind of formatting you need. The critical pieces to understand are:
piece the $path_to_file together based on the $item['file_dir'] and $item['file_name']
make your link (or your button, or whatever you choose to use) point to that $path_to_file.
SELECT FirstTable.file_name, FirstTable.file_dir, ThirdTable.books_title, ThirdTable.books_author, ThirdTable.books_publisher INNER JOIN SecondTable ON FirstTable.file_id = SecondTable.file_id INNER JOIN ThirdTable ON SecondTable.books_id = ThirdTable.books_id
INNER JOIN may not necessarily be the JOIN type you want to use, but this would be the general idea for grabbing data from 2 tables corresponding to a third (SecondTable) which links them.
$link = $row['file_dir'] . $row['file_name'];

While loop displaying result 3 times

Basicly I'm trying to make a simple news feed but I'm stuck at the moment as my while loop display the result 3 times, why is this? :/
<?php
$sql ="SELECT
*
FROM
news,
admins";
$result = mysql_query($sql);
if(!$result)
{
echo 'Error while selecting from database. Please contact the administration team';
} else {
while($row = mysql_fetch_assoc($result))
{
echo '
<div class="content_news">
<h1>' . $row['news_name'] . '</h1>
<p style="font-size:12px;">Posted by <b>' . $row['admin_name'] . '</b> on ' . $row['news_date'] . '
<p>' . $row['news_description'] . '</p>
read more
</div>
';
}
}
?>
If you'd like to see what I am talking about: http://freewallpaperblog.com/freshrp/
Ignore the last 2(those are static html not php)
your query selects data from 2 tables (news, admins) so it joins every row of 1st table with every row of 2nd table
SELECT * FROM news, admins
i recommend you to use following query
SELECT news.*, admins.admin_name FROM news
INNER JOIN admins ON news.admin_id = admins.id
where admin_id is your correct column name
You either have 3 admins or 3 rows of news. Your query makes a direct multiplication between tables. Try "left join" instead...
SELECT * FROM news
INNER JOIN admins ON admins.id = news.adminid
Or whatever adminid is in the news table.
Try the following query:
SELECT
*
FROM
news
Inner join admins on news.admin_id = admins.id
You made no JOIN statement in your SQL, as someone else has already commented on in your question. It would help if you posted the associated fields you're grabbing, but based on your $row keys, my best guess is the following should work for you (but I can't promise it will without knowing how your database is designed, I can only infer from the variable names):
$sql = "SELECT news.name, news.date, news.description, news.link, admins.name"
. "FROM news"
. "INNER JOIN admins"
. "ON news.name=admins.name"
References:
http://www.w3schools.com/sql/sql_join_inner.asp
http://www.w3schools.com/sql/sql_join_left.asp
http://dev.mysql.com/doc/refman/5.0/en/join.html

Multiple tables join echo with while

I'm now hopeless about this problem and that's why I'm here. I'm kind of a starter in PHP and mysql programming. I searched for a solution on the web but I wasn't succeeded. I'm working on a project what is a car repairing administration system. This is a part of it that I need.
I have two tables:
repairs (j_id /this is the primary key/, rendszam, javitas, megjegyzes, datum)
and
pictures (kep_id /this is the primary key/, j_id /it's from repairs j_id/, kepnev)
I need to display a result in a table, where I can see that which of the repairs have a picture in the pictures table, but without redundancy, so I don't want multiple repair rows that are similar to eachother, but one repair row with multiple picture columns after it.
What I have done already:
<?php
$sql = "SELECT $tbl_name2.j_id, $tbl_name2.rendszam, $tbl_name2.javitas, $tbl_name2.megjegyzes, $tbl_name2.datum, $tbl_name3.kepnev FROM $tbl_name2, $tbl_name3 WHERE $tbl_name2.j_id=$tbl_name3.j_id";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo "<tr><td>" . $row[$i] . "</td>";
echo "<td>" . $row[$i + 1] . "</td>";
echo "<td>" . $row[$i + 2] . "</td>";
echo "<td>" . $row[$i + 3] . "</td>";
echo "<td>" . $row[$i + 4] . "</td>";
echo "<td>" . $row[$i + 5] . "</td>";
}
?>
This one displays information like this:
repair id | picture
1 | fdgdfg.jpg
1 | fgdfg.jpg
1 | fghh.jpg
25 | dfg.jpg
25 | jkjk.jpg
But I don't want to have multiple repair rows but one repair row with multiple pictures after it.
I tried this:
$sql2="SELECT DISTINCT $tbl_name2.j_id, $tbl_name3.kepnev FROM $tbl_name2, $tbl_name3 WHERE $tbl_name2.j_id=$tbl_name3.j_id";
$result2=mysql_query($sql2) or die(mysql_error());
$sql="SELECT $tbl_name2.j_id, $tbl_name2.rendszam, $tbl_name2.javitas, $tbl_name2.megjegyzes, $tbl_name2.datum, $tbl_name3.kepnev FROM $tbl_name2, $tbl_name3 WHERE $tbl_name2.j_id=$tbl_name3.j_id GROUP BY j_id;
$result=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($result))
{
echo "<tr><td>".$row[$i]."</td>";
echo "<td>".$row[$i+1]."</td>";
echo "<td>".$row[$i+2]."</td>";
echo "<td>".$row[$i+3]."</td>";
echo "<td>".$row[$i+4]."</td>";
echo "<td>".$row[$i+5]."</td>";
while($sor=mysql_fetch_array($result2))
{
if($sor['j_id']==$row[$i]){
echo "<td><a href=kepek/".$sor['kepnev']." target=_blank>".$sor['kepnev']."</a></td>";
}
}
}
The sql statement differs in the group by in $sql, but this one displays the results like this:
repair id | picture
1 | fdgdfg.jpg | fgdfg.jpg | fghh.jpg
25 |
So it's just not continuing after the first repair id, not showing the repair pictures for repair id 25.
I don't know, how can I get it right. I need a table which displays information like this:
repair id | picture
1 | fdgdfg.jpg | fgdfg.jpg | fghh.jpg
25 | dfg.jpg | jkjk.jpg
Could you help me out in this?
This sounds fairly straightforward, looks like you're off to a good start.
I've done something similar in the past, and I just used a variable to keep track of the current ID being displayed and the previously displayed ID. Here's a quick code sample to outline what I mean by that.
while($row=mysql_fetch_array($result))
{
$currentID=$row[$i];
if ($currentID != $lastID) {
echo "</tr><tr><td>".$row[$i]."</td>";
} else {
echo "<td>".$row[$i]."</td>";
}
$lastID=$row[$i];
}
So, the idea is to keep track of what the last ID was. In the next row, if the ID is the same, just output <td>"variable goes here"</td> to keep it on the same column. If the ID changed, end the row and create a new row using </tr><tr>". Feel free to comment if you need more help.

Categories