Taking a deep breath, really don't know how to combine 2 tables from my MySQL,
I will show you the tables which I've and the rows which needed to be combinated.
Table called post:
As you see cat means Category, which category it is (see below category table nameID is same as cat here)
For example my page www.site.com/category.php?nameid=NAMEID(table category)&id=ID(table post) Need to be combined so if I go to ?nameid=1&id8 the page should be blanc or giving an error since id=8 is category 2 and not 1.
// BEGIN OF SHOWING CONTENT PAGE
if (isset($_GET['id'])){
$naamID = mysql_real_escape_string($_GET['nameID']);
$id = mysql_real_escape_string($_GET['id']);
$idnext = $id + 1;
$gn = (" SELECT * FROM category WHERE nameID='".$naamID."'") or die(mysql_error());
$go = (" SELECT * FROM post WHERE id='".$id."'") or die(mysql_error());
$gnn = mysql_query($gn) or die(mysql_error());
$goo = mysql_query($go) or die(mysql_error());
$gnnn = mysql_fetch_array($gnn);
$gooo = mysql_fetch_array($goo);
if(empty($gooo['youtube'])){
} else {
?> <h2> <?php echo htmlspecialchars($gooo["title"]); ?> </h2><br />
<?php
echo '<iframe width="560" height="315" src="//www.youtube.com/embed/'.$gooo["youtube"].'" frameborder="0" allowfullscreen></iframe><br />';
}
if(empty($gooo['pic'])){
} else {
?> <h2> <?php echo htmlspecialchars($gooo["title"]); ?> </h2><br />
<?php
echo '<img src="'.$gooo["pic"].'"/>';
}
}
?>
SELECT table1.keyid FROM table1
UNION
SELECT table2.keyid FROM table2
i wish this example help you ,try to understand how to combine 2 tables
I think i don't understand need of passing categid, as post id itself looks like primary key, so you must able to fetch particular post record, and can retrieve name of that category which is linked with requested post using something like(you just need to pass post id in parameter)
SELECT youtube,title,c.name,pic FROM post p
INNER JOIN categories c
ON c.nameid=p.cat
WHERE p.id=2
If you are trying to get requested post record along with all posts from requested category than you can write query like
SELECT youtube,title,c.name,pic
FROM post
INNER JOIN categories c
ON c.nameid=p.cat
WHERE (p.id=8 or cat=2)
Hope this will help!
Thanks
Suresh
Update:
Based on what I understood, following code snippet may solve your problem
$row = mysql_query("SELECT p.cat, c.nameID FROM post p INNER JOIN category c ON p.cat = c.nameID WHERE p.cat = '".$id."' AND c.nameID = '".$naamID."' LIMIT 1");
if(mysql_num_rows($row)==0)
{
echo("This post doesn't exist on this category")
}
Update 2:
<?if (isset($_GET['id']))
{
$naamID = mysql_real_escape_string($_GET['nameID']);
$id = mysql_real_escape_string($_GET['id']);
$row1 = mysql_query("SELECT p.cat, c.nameID FROM post p INNER JOIN category c ON p.cat = c.nameID WHERE p.cat = '".$id."' AND c.nameID = '".$naamID."' LIMIT 1");
if(mysql_num_rows($row1)==0)
{
echo("This post doesn't exist on this category");
}
else
{
$idnext = $id + 1;
$gn = (" SELECT * FROM category WHERE nameID='".$naamID."'") or die(mysql_error());
$go = (" SELECT * FROM post WHERE id='".$id."'") or die(mysql_error());
$gnn = mysql_query($gn) or die(mysql_error());
$goo = mysql_query($go) or die(mysql_error());
$gnnn = mysql_fetch_array($gnn);
$gooo = mysql_fetch_array($goo);
/*--------------your other display code when data is available-------------*/
}
}
?>
Related
I have one table with categories and another table with linkrecords for each category and the table structure looks like this:
categories:
id (int)
name (varchar)
links:
id (int)
link (varchar)
fk_cat_id (int)
Here is how I do now, but know that it is a no go with a query within a query:
$query = "SELECT * FROM categories";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$catid = $row['cat_id'];
echo 'CatName: '.$row['name'];
echo '<ul>';
$query2 = "SELECT * FROM links WHERE fk_cat_id = $catid";
if ($result2 = $mysqli->query($query2)) {
while ($row2 = $result2->fetch_assoc()) {
echo '<li>'.$row2['link'].'</li>';
}
}
echo '</ul>';
}
}
I guess I have to go to some JOIN method, but not sure how!
Following query will be used to retrieve links with relation to link categories.
Also, It is a good practice to specify fields name in query to retrieve specific columns only instead of *.
SELECT links.id AS link_id, links.link, links.fk_cat_id, categories.name
FROM links
JOIN categories ON categories.id = links.fk_cat_id;
I've got two tables, one called category, which has the rows id and name, and another called placecategory, which has the tables id, place_id and category_id. I need to inner join these two to echo out the names of the categories where the placecategory.place_id is equal to a $GET[ID].
I've got this so far, but it echo's out nothing.
<?php
include('includes/connectdb.php');
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$qry = 'SELECT id, name FROM category
INNER JOIN placecategory
ON category.id = placecategory.category_id
WHERE placecategory.place_id = '.$id.'';
$result = mysqli_query($dbc,$qry);
while ($row = mysqli_fetch_array($result))
{
echo ''.$row['name'].'';
};
?>
This wont fix your query, but it will display the error generated by the incorrect query. Its a start.
I cannot solve the query issue without a better understanding of your schema.
<?php
include('includes/connectdb.php');
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$qry = 'SELECT id, name
FROM category
INNER JOIN placecategory ON category.id = placecategory.category_id
WHERE placecategory.place_id = '.$id;
$result = mysqli_query($dbc,$qry);
// test the status before continuing
if ( ! $result ) {
echo mysqli_error($dbc);
exit;
}
while ($row = mysqli_fetch_array($result))
{
echo $row['name'];
}
?>
I am using a code something like below to get data from the second table by matching the id of first table. Code is working well, but I know it slow down the performance, I am a new bee. Please help me to do the same by an easy and correct way.
<?php
$result1 = mysql_query("SELECT * FROM table1 ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ))
{
$tab1_id = $row1['tab1_id'];
echo $row['tab1_col1'] . "-";
$result2 = mysql_query("SELECT * FROM table2 WHERE tab2_col1='$tab1_id' ") or die(mysql_error());
while( $row2 = mysql_fetch_array( $result2 ))
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
}
?>
You can join the two tables and process the result in a single loop. You will need some extra logic to check if the id of table1 changes, because you'll only want to output this value when there's a different id:
<?php
// Join the tables and make sure to order by the id of table1.
$result1 = mysql_query("
SELECT
*
FROM
table1 t1
LEFT JOIN table2 t2 ON t2.col1 = t1.id
ORDER BY
t1.id") or die(mysql_error());
// A variable to remember the previous id on each iteration.
$previous_tab1_id = null;
while($row = mysql_fetch_array( $result1 ))
{
$tab1_id = $row['tab1_id'];
// Only output the 'header' if there is a different id for table1.
if ($tab1_id !== $previous_tab1_id)
{
$previous_tab1_id = $tab1_id;
echo $row['tab1_col1'] . "-";
}
// Only output details if there are details. There will still be a record
// for table1 if there are no details in table2, because of the LEFT JOIN
// If you don't want that, you can use INNER JOIN instead, and you won't need
// the 'if' below.
if ($row['tab2_col1'] !== null) {
echo $row['tab2_col2'] . "-";
echo $row['tab2_col3'] . "</br>";
}
}
Instead of having 2 while loops, what you can do is join the 2 tables and then iterate over the result.
If you're not sure what join is look here: https://dev.mysql.com/doc/refman/5.1/de/join.html
Also here is a fairly simple query written using join: Join Query Example
You can use this. One relation with two tables:
<?php
$result1 = mysql_query("SELECT tab2_col2, tab2_col3 FROM table1, table2 where tab2_col1 = tab1_id ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ),)
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
?>
Like Sushant said, it would be better to use one JOIN or simpler something like that:
SELECT * FROM table1, table2 WHERE `table1`.`id` = `table2`.`id
this is probably going to require something very basic but I can't find an answer to do this in the way I want it to work. What I have is a mysql table of articles and a table of favourites where if you like an article the information is logged. So I need to select all of the articles that I like from one table and then all of the articles from another and display them all as a feed, which I have done. The part I need help with is saying, if I like one of the posts, do not display the like button (Alternatively if I haven't yet liked it, show the button). Can anyone please point me in the right direction with this? Here's the code I have but it only shows the last one I Liked:
<?php
$check_like_sql = "SELECT * FROM posts WHERE type = 'Like' && poster = '$yourid'";
$check_like_res = mysqli_query($con, $check_like_sql) or die (mysqli_error());
if(mysqli_affected_rows($con)>0){
while($likes = mysqli_fetch_array($check_like_res)){
$yourlike = $likes['media'];
}
}
?>
<?php
$get_posts_sql = "SELECT posts.*, members.username, members.avatar, fans.connection FROM posts LEFT JOIN members ON members.id = posts.poster LEFT JOIN fans ON fans.fan = '$yourid' WHERE posts.poster = fans.connection ORDER BY date DESC";
$get_posts_res = mysqli_query($con, $get_posts_sql) or die (mysqli_error());
if(mysqli_affected_rows($con)>0){
while($posts = mysqli_fetch_assoc($get_posts_res)){
$postid = $posts['id'];
etc
etc
if($yourlike == $postid){
$likethis = "Unlike . ";
}
else if($posttype == "Like"){
$likethis = "";
}
else{
$likethis = "Like . ";
}
$post .= "";
}
}
?>
You can left outer join from your articles table to your liked_articles table.
select a.*,
case when la.liked_article_id is null then 'Not Liked Yet' else 'Already Liked' as LikedStatus
from articles a
left outer join liked_articles la
on a.id = la.article_id
and #userId = la.user_id;
This may not be syntactically correct for MYSQL but you get the gist.
I have two tables in my database:
1) blog_table
2) content
In blog_table I have values called postID that may or may not match up to values called id in the table content. I am wanting to know how I can write a while loop or foreach loop that will cycle through content table and perform one action if the id equals the value of postID in the blog_table and perform a different action if it doesn't.
Right now I can only get id = postID
$blog_table = $_REQUEST['blog_table'];
$getblogtable = mysql_query("SELECT * FROM content WHERE type = '5' AND blogID = '{$_REQUEST['id']}' ORDER BY `order` ASC");
while ($row = mysql_fetch_assoc($getblogtable))
{
$getblogposts1 = mysql_query("SELECT postID FROM `$blog_table`");
while ($row1 = mysql_fetch_assoc($getblogposts1))
{
if( $row1['postID'] == $row['id']) {
echo "do something<br>";
}else{
echo "do something else<br>";
}
} echo "<p></p>";
}
[Edit based on OP's comments and revised question]
$getblogposts = mysql_query("SELECT * FROM content WHERE type = '5' AND blogID = '{$_REQUEST['id']}' ORDER BY `order` ASC");
while ($row = mysql_fetch_assoc($getblogposts))
{
$matches = mysql_query("SELECT * FROM $blog_table WHERE postID = $row['id']");
if (mysql_num_rows($matches) > 0)
{
// do something
}
else
{
// do something else
}
}
Regarding a different design, I can't say for sure that it's necessary, but I don't like running a loop of queries like this. I think one query should be enough to get everything you need in this case. Maybe if you describe your application, we could find a better query or more appropriate design.
Just providing an easier to see solution for you to your problem.
I suggest using inner joins which will solve the issue at hand.
For example, Something like:
SELECT * FROM content AS C INNER JOIN $blog_table AS B on B.postID = C.id
Here is a great introduction to joins (inner, left, right, full):
http://www.w3schools.com/sql/sql_join.asp
$blog_table = $_REQUEST['blog_table'];
$getblogtable = mysql_query("SELECT postID FROM `$blog_table`");
while ($row = mysql_fetch_assoc($getblogtable))
{
$postID = $row['postID'];
$getblogposts1 = mysql_query("SELECT * FROM content WHERE id = '$postID' ORDER BY `order` ASC");
while ($row1 = mysql_fetch_assoc($getblogposts1))
{
// if( $row1[id] == $postId )
// do something
// else
// do something else
}
}