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)";
Related
I am a php and MySQL newbie. What I have done is created an html form with a <select> dropdown. Based on the selection from the form, it changes the $_SESSION[campaignID] variable. Changing the selection in the form is supposed to then change what displays on the page. The page consists of a forum style post that allows users to fill out a textarea and then submit it into the MySQL database into a table called "posts." On this same page I then display the contents of the "posts" table.
What I have done is in the posts MySQL table, I have added a campaignID row. Then in my campaigns table I also have a campaignID row. The campaignID in campaigns table auto increments every time a campaign is created. Then with the earlier mentioned dropdown I can select the campaign I want, and it should then show all posts with the same campaignID as the campaign I selected.
I can verify that the $_SESSION[campaignID] is changing when i select the various options. Because when I do that and then save another post, it takes the session variable campaignID and saves it properly in the posts table.
Now what I need it to do, is when I change the drop down (which then changes $_SESSION[campaignID]) I need it to display the posts that share the same campaignID as the selected campaign. I am just not able to get it to display when trying to put a variable in my INNER JOIN query. I have a feeling the info I have provided may not be enough, but not sure what else I need to include here. Help?
Code that contains the INNER JOIN query and displays the various rows of posts table
UPDATED
<?php
$con=mysqli_connect("localhost","dorians","ds2953!b67P$","aldentec");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$campaignID = $_SESSION['campaignID'];
$result = mysqli_query($con,"SELECT posts.postDate, posts.postName, posts.postEntry FROM posts INNER JOIN campaigns ON posts.campaignID=" . $campaignID);
while($row = mysqli_fetch_array($result))
{
echo "<div id='campaignPostContainer'>";
echo "<ul class='campaignPostBox'>";
echo "<p class='postInfo'>";
echo "Posted on:";
echo "<li>" . $row['postDate'] . "</li>";
echo "</p>";
echo "<p class='postInfo'>";
echo "Posted by:";
echo "<li>" . $row['postName'] . "</li>";
echo "</p>";
echo "<li class='postEntry'>" . $row['postEntry'] . "</li>";
echo "</ul>";
echo "</div>";
echo "<hr>";
}
mysqli_close($con);
?>
Without going into a use-prepared-statements rant...
You're not pulling the session variable, but assigning $campaignId to literally the string $_SESSION[campaignID].
Change your line:
$campaignID = '$_SESSION[campaignID]';
to:
$campaignID = $_SESSION['campaignID'];
Also, your query is going to generate a cross product unless you define something in your ON clause like:
SELECT posts.postDate, posts.postName, posts.postEntry FROM posts
INNER JOIN campaigns ON posts.campaignID= $campaignID
AND posts.campaignID= campaigns.id
The value should be in single quote ' so you may try this
posts.campaignID='" . $campaignID ."'"
instead of
posts.campaignID=" . $campaignID
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'];
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"
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
Hi I want to create Categories listed which are saved in my database so when user upload his images and he select the category it saves the data in database in Cat column
Now I want to show category in PHP like this
Categories Total
Animals (4)
Celebrations (2)
Locations And Travel (11)
Object or still life (1)
Transportation (9)
Here is my PHP I am succeeded to show Categories names but not total category in each category
<?php
$con=mysqli_connect("localhost","root","123","user");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"Select Cat from save_data Group By Cat ")
or die(mysql_error());
echo "<table border='1'>
<tr>
<th>Categories</th>
<th>Total</th>
</tr>";
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
echo "<tr>";
echo "<td>" . $row['Cat'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Extend the table cell:
<td colspan="2"></td>
This way it extends over another cell.
Also I notice you are mixing mysqli and mysql:
or die(mysql_error());
Try to use mysqli as objects and \Exceptions instead of errors. It's worth learning about :-)
Update:
I did not understand your question at first. Please provide your schema so we can see your table structure.
Usually you would have 2 tables, one with categories and one with data and join them with a GROUP BY (if an item can be in several categories, you would have a third table like category_has_item!):
SELECT c.category AS cat,
COUNT(i.items) AS num
FROM category c
LEFT JOIN items i
ON c.category_id = i.category_id
GROUP BY c.category
Use LEFT JOIN to display empty categories and JOIN (without LEFT) to avoid empty categories.
Change your table echo:
echo "<td>" . $row['cat'] . "</td><td>(" . $row['num'] . ")</td>";
Update:
If you only have 1 table, I strongly suggest you to read about database normalization.
Update your query:
Select Cat,COUNT(Data) AS num from save_data Group By Cat
Replace Data by your data column
and your echo line:
echo "<td>" . $row['Cat'] . "</td><td>(" . $row['num'] . ")</td>";
try to change your sql query like this
SELECT count(*) AS total_count FROM (SELECT Cat FROM save_data GROUP BY Cat HAVING COUNT(Cat) > 1) AS t