Hello I have actually asked a similar question a while ago but only just realized I did not get an answer that solves my problem.
I have 2 tables in a MySQL DB, that are connected by the same main id, the following code is just a simplified example of the original code:
table1:
+-----------------------+
| main_id | name | type |
+-----------------------+
table2:
+----------------------------------------+
| main_id | secondary_id | color | price |
+----------------------------------------+
the result I want to achieve is to get every row of table 1, and under each one list all the linked by main id rows from table2, for example:
table1 rows:
+-------------------+
| 1 | name1 | type1 |
| 2 | name2 | type2 |
| 3 | name3 | type3 |
+-------------------+
table2 rows:
+----+------+----------+------+
| 1 | 23 | red | 500 |
| 1 | 24 | blue | 600 |
| 1 | 25 | green | 700 |
| 2 | 26 | pink | 400 |
| 2 | 27 | purple | 200 |
| 3 | 28 | white | 100 |
+----+------+----------+------+
result in display:
<h1 class="1">name1, type1</h1>
<div class="23">red,500</div>
<div class="23">red,500</div>
<div class="24">green,700</div>
<h1 class="2">name2, type2</h1>
<div class="25">pink,400</div>
<div class="26">purple,200</div>
And so on...I was using a while loop inside a while loop which wasn't giving me the required result, then I was advised to use MySQL JOIN, but when I do I get all values of the matching ids and cant display the headings only once and then list the related results under it, can someone please help me?
this is a simplified query i was using:
while($rows = $headings->fetch_array(MYSQLI_BOTH))
{
$id = $rows['id'];
$conts_q = $mysqli->query("SELECT * FROM `table2` WHERE id='$id'");
$conts_numr = $conts_q->num_rows;
if($conts_numr==0)
{
//Display empty
}
else
{
while($row2 = $conts_q->fetch_array(MYSQLI_BOTH))
{
//Get details and display
}
}
}
In your description, you use main_id, but in the code you use just id. Not sure which you're really using here - you will have to edit the code below to match your actual column names. If the database column name is actually main_id, then for instance the line with $id = $rows['id'] would have to be $rows['main_id']. Or it won't work.
while($rows = $headings->fetch_array(MYSQLI_BOTH))
{
echo '<h1 class="'.$rows['id'].'">'.$rows['name1'].', '.$rows['type'].'</h1>';
$id = $rows['id'];
$conts_q = $mysqli->query("SELECT * FROM `table2` WHERE id='$id'");
$conts_numr = $conts_q->num_rows;
if($conts_numr==0)
{
//Display empty
}
else
{
while($row2 = $conts_q->fetch_array(MYSQLI_BOTH))
{
if ($row2['id'] == $id) {
echo '<div class="'.$row2['secondary_id'].'">'.$row2['color'].', '.$row2['price'].'</div>';
}
}//while
}//else
}//while
Related
How do I combine two unrelated tables into one SQL select statement request. However, both tables need to have the Match and Against functions for full text search. I'm getting a blank response and when I do a single table SQL match and against request it works fine but not when I do two tables.
Table One: transport - only id is a primary key integer auto_increment but the rest are varchar
+----+---------+-----------+--------------+
| id | title | type | tags |
+----+---------+-----------+--------------+
| 1 | triumph | motorbike | sport, black |
+----+---------+-----------+--------------+
| 2 | bmw | car | hatchback |
+----+---------+-----------+--------------+
Table Two: automobile - - only id is a primary key integer auto_increment but the rest are varchar
+----+-----------+-----------+------------+---------+
| id | name | kind | link | listed |
+----+-----------+-----------+------------+---------+
| 1 | suzuki | motorbike | /bike/new/ | green |
+----+-----------+-----------+------------+---------+
| 2 | volkwagan | car | /car/new/ | limited |
+----+-----------+-----------+------------+---------+
I need it to print out something like this (just a note, not sure how I would need id - perhaps two columns id_automobile and id_transport to references both above tables)
+----+-----------+-----------+------------+--------------+
| id | title | type | link | tags |
+----+-----------+-----------+------------+--------------+
| 1 | suzuki | motorbike | /bike/new/ | green |
+----+-----------+-----------+------------+--------------+
| 2 | triumph | motorbike | | sport, black |
+----+-----------+-----------+------------+--------------+
| 3 | bmw | car | | hatchback |
+----+-----------+-----------+------------+--------------+
| 4 | volkwagan | car | /car/new/ | limited |
+----+-----------+-----------+------------+--------------+
My failed attempt:
<table>
<tr>
<th>Title</th>
<th>Type</th>
<th>Link</th>
<th>Tags</th>
</tr>
if(isset($_GET['search'])) {
$search = $_GET['search'];
} else {
$search = '';
}
$sql = "SELECT * FROM `transport` WHERE MATCH(title, tags) AGAINST('".$search."') CROSS JOIN `automobile` WHERE MATCH(name, listed) AGAINST('".$search."')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>".$row["title"]."</td><td>".$row["type"]."</td><td>".$row["link"]."</td><td>".$row["tags"]."</td>";
echo "</tr>";
}
} else {
echo "0 results";
}
$conn->close();
</table>
I would appreciate any help please
A UNION clause should give you the results that you need.
Just make sure that bost SELECTs, combined with UNION, have similar column sets. You can use AS to define aliases.
Something like this:
SELECT title, type, '' AS link, tags
WHERE MATCH(title, tags) AGAINST('...')
FROM transport
UNION
SELECT name AS title, kind AS type, link, listed AS tags
FROM automobile
WHERE MATCH(title, kind) AGAINST('...')
I am trying something here, I want to make a condition that allows me to fetch an info from a row in a Mysql if the page title is the same with a value from table "names"/column "lastname". Here I had made a table "names"
The "firstname" column would be unique in this table.
+---------+-----------+----------+
| id | firstname | lastname |
+---------+-----------+----------+
| 1 | John | Smith |
| 2 | Jane | Smith |
| 3 | Jimbo | Jones |
| 4 | Andy | Smith |
| 7 | Chris | Jones |
| 45 | Anna | Bell |
| 44 | Jimmy | Carr |
| 43 | Albert | Smith |
| 47 | Johnna | Doe |
+---------+-----------+----------+
If the page name is equal to "Jimbo" than display "Jones" else error text (but still showing) or so. I don't know if this way good is while I don't have any ideeas anymore.
The code that i am using so far:
<?php echo get_the_title($ID); ?>
- for fetching the title -
<?php
$result = mysql_query("SELECT lastname FROM names WHERE id = '2'");
if (!$result) {
echo 'error:bla ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 2
echo $row[1]; //
?>
For fetching the row -
In Wordpress I am using PHP code for posts and pages (I can make a shortcode).
http://codex.wordpress.org/Class_Reference/wpdb
global $wpdb;
$result = $wpdb->get_row("SELECT * FROM names WHERE id='2' ");
if($result){
echo $result->lastname;
}
My data (simplified) looks like....
------------------------
| key | id | minspld |
------------------------
| 1 | 400 | 90 |
| 2 | 400 | 40 |
| 3 | 401 | 38 |
| 4 | 401 | 90 |
| 5 | 402 | 90 |
| 6 | 402 | 89 |
| 7 | 403 | 77 |
| 8 | 403 | 15 |
| 9 | 404 | 90 |
-----------------------
I am trying to do....
For each id, add all their minspld entries together
Display them in a table like above, but each id only showing once, and the minspld column showing the total per each id.
Here's what I'm using at the moment and I'm displaying all entries separately (eg, each person shows twice)
<table><thead><tr><th>ID</th><th>Mins Played</th></tr></thead>
<tbody>
<?php
$queryget = mysql_query("SELECT * FROM mlsstats ORDER BY id ASC") or die(mysql_error());
while ($row = mysql_fetch_assoc($queryget))
{
$id = $row['id'];
$minspld = $row['minspld'];
echo "<tr>";
echo "<td>".$id."</td>";
echo "<td>".$minspld."</td>";
echo "</tr>";
}
?>
</tbody></table>
How would I write this to make each id show only once in the HTML, but with the added totals of all their minspld entries? (eg, id 400 would have 130. id 401 would have 128. etc.)
If this isn't clear, please let me know.. and thanks for any help.
Please try changing your query to:
SELECT id, SUM(minspld) AS minspld FROM mlsstats GROUP BY id ORDER BY id ASC
You dont have to use a loop for this. You can simply do this with query
Just run the query and get two columns. id and its total
SELECT
m.id,
SUM(minspld) AS TCount
FROM mytable AS m
GROUP BY m.id
I have this scenario.
I input $groupid="1";
main table
----------------------
| groupid | postid |
|---------------------|
| 1 | 1 |
| 2 | 2 |
| 1 | 3 |
$query = "SELECT postid FROM `mainl` WHERE groupid='$groupid'";
$result = mysql_query($query);
// a group of postids belonging to that groupid which should hold [1, 3] for groupid=1
while($row = mysql_fetch_array($result)) {
$postids[] = $row["postid"];
}
second table
-------------------------------------------
| postid | commentid | comment |
-------------------------------------------
| 1 | 1 | testing 1 |
| 1 | 2 | testing 2 |
| 1 | 3 | what? |
| 2 | 1 | hello |
| 2 | 2 | hello world |
| 3 | 1 | test 3 |
| 3 | 2 | begin |
| 3 | 3 | why? |
| 3 | 4 | shows |
$query = "SELECT * FROM `second`";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
if (in_array($row["postid"], $postids)) {
$comments[$row["postid"]] = $row["comment"];
But how should I take care of commented
I want the postid array to be [1,3] and my comment array to be
[commentid: comment] [1:testing1, 2: testing2, 3: what?] for postid=1
and
[1:test3, 2:begin, 3: why? 4:shows] for postid=3
how should be arrange everything such comment are associated with commentid and postid?
First I would follow rokdd suggestion and make 1 query
SELECT m.groupid , s.postid, s.commentid, s.comment FROM `main1` m JOIN `second` s USING (postid) where m.groupid = 1
Then I would make a multi-dimensional array
while ($row = mysql_fetch_array($result))
$groups[$row['groupid'][$row['postid']][$row['commentid']=$row['comment'];
then to iterate through the array
foreach($groups as $group)
foreach($group as $post)
foreach($post as $comment)
echo $comment;
This will keep track of groups also (if you ever want to select by more than 1 group.
If you don't care about groups just drop off the first part of the array.
while ($row = mysql_fetch_array($result))
$posts[$row['postid']][$row['commentid']=$row['comment'];
foreach($posts as $post)
foreach($post as $comment)
echo $comment;
I guess to use the join in sql so that you will have one statement:
SELECT * FROM second as second_tab LEFT join main as main_table ON main_table.post_id=second_table.post_id WHERE main_table.group_id="3"
Well not tested now but thats a way to solve some of your problems!
I have tables illustrated below
//reference type table
+---+-----------+---------+
|ID |Article_ID |Ref_Types|
+---+-----------+---------+
| 1 | 1 | article |
| 2 | 1 | book |
| 3 | 1 | article |
| 4 | 1 | article |
| 5 | 2 | book |
+---+-----------+---------+
//book references table
+---+-----------+--------+
|ID |Article_ID |Title |
+---+-----------+--------+
| 1 | 1 | book1 |
| 2 | 1 | book2 |
| 3 | 2 | book3 |
| 4 | 2 | book4 |
| 5 | 2 | book5 |
+---+-----------+--------+
//article references table
+---+-----------+-----------+
|ID |Article_ID |Title |
+---+-----------+-----------+
| 1 | 1 | article1 |
| 2 | 1 | article2 |
| 3 | 2 | article3 |
| 4 | 2 | article4 |
| 5 | 2 | article5 |
+---+-----------+-----------+
I have to look into first table and check the reference, of which type it is;
for each reference type, I have get reference table from related table
I have to output in order, as shown in table one.
1:
$data=array();
$sql=mysql_query("SELECT * FROM reftypes
WHERE Article_ID=1 ORDER BY ID ASC");
while($row = mysql_fetch_array($sql)){
$data[]=$row[2]; // i store in an array so that i can use later..
}
2:
foreach ($data as $ref) {
$counter=1;
switch ($ref) {
case "article":
$sqlarticle= mysql_query("SELECT Title
FROM book WHERE Article_ID=1 ORDER BY ID ASC");
echo mysql_result($sqlarticle, $counter); //i want to get only one out of book table
$counter++;
break;
...
...
But $sqlarticle does not seem to work.
I want to display as:
+-----------+----------+
|Article_ID |Reference |
+-----------+----------+
| 1 | article1 |
| 1 | book1 |
| 1 | article2 |
| 1 | article3 |
+-----------+----------+
I know it is a long question and for experts or experienced people it is very trivial, but that is where I'm stuck.
SELECT
*
FROM
reftypes R
WHERE
Article_ID=your_id
LEFT JOIN books B ON (B.Article_ID = R.Article_ID AND R.Ref_Types = 'book')
LEFT JOIN articles A ON (A.Article_ID = R.Article_ID AND R.Ref_Types = 'article')
ORDER BY
R.id ASC;
Even if the database is wrongly modeled, I think.
What about the followin model instead?
""although especially question owners should respect any kind of effort and input, -i am thankful- i can not understand why some people try to think of question's holder as well-informed or experienced as themselves, or worse comment from higher level. ""
anyway, my question was about to get values one by one, here is how i did it;
$data=array();
$sql=mysql_query("SELECT * FROM reftypes
WHERE Article_ID=1 ORDER BY ID ASC");
while($row = mysql_fetch_array($sql)){
$data[]=$row[2]; // i store in an array so that i can use later..
}
$articlecount=0;
$bookcount=0;
foreach ($data as $value) {
switch ($value) {
case "article":
$sqlarticle=mysql_query("SELECT RefArticleTitle
FROM ref_article
WHERE $article_ID=Article_ID
ORDER BY ID ASC");
$articles= mysql_result($sqlarticle, $articlecount);
echo $articles;
echo "\n";
$articlecount++;
break;
case "book":
$sqlbook=mysql_query("SELECT RefBookName
FROM ref_book
WHERE $article_ID=Article_ID
ORDER BY ID ASC");
$books= mysql_result($sqlbook, $bookcount);
echo $books;
echo "\n";
$bookcount++;
break;
...
...
as a result, i got what i required..
+-----------+----------+
|Article_ID |Reference |
+-----------+----------+
| 1 | article1 |
| 1 | book1 |
| 1 | article2 |
| 1 | article3 |
+-----------+----------+
thanks to whoever interested in the topic..
$result=mysqli_query("select ref_types from reference type");
while($row=mysqli_fetch_array($result))
{
$table=$row[0];
$result1=mysqli_query("select * from $table");
while($row1=mysqli_fetch_array($result1))
{
var_dump($row1);
}
}