I have two tables such as below :
/* questions table */
| q_id | q_title |
| ------- | ---------------------- |
| 1 | What is your name? |
| ------- | ---------------------- |
| 2 | What is your gender? |
| ------- | ---------------------- |
| ... | |
/* options table */
| o_id | o_title | o_question_id |
| ------ | --------- | --------------- |
| 1 | George | 1 |
| ------ | --------- | --------------- |
| 2 | Sarah | 1 |
| ------ | --------- | --------------- |
| 3 | Michael | 1 |
| ------ | --------- | --------------- |
| 4 | Male | 2 |
| ------ | --------- | --------------- |
| 5 | Female | 2 |
| ------ | --------- | --------------- |
| ... | | |
How can I select from two tables as follows :
1. What is your name?
George
Sarah
Michael
2. What is your gender?
Male
Female
"JOIN" makes repetitive questions.
Where is my code wrong?
My controller :
/* controller */
$data['questions'] = $this->db->get('questions_tbl')->result();
$items_arr = array();
foreach ($data['questions'] as $option) {
$items_arr[] = $this->db->where('o_question_id', $option->q_id)->get('options_tbl')->result();
}
$data['options'] = $items_arr;
And my view :
/* view */
<?php foreach ($questions as $q) { ?>
<strong><?= $q->q_id ?>.<?= $q_title ?></strong>
<?php foreach ($options as $o) { ?>
<?php if ($o->o_question_id == $q->id) { ?>
<p><?= $o->o_title ?></p>
<?php } ?>
<?php } ?>
<?php } ?>
You will need to first select the questions, then for each question ID, select it's choices.
Below is an example:
function questions(){
$qtns = array();
$query = $this->db->get('questions_table');
foreach($query->result_array() as $one){
$one['choices'] = $this->questionChoices($one['id'];
$qtns[] = $one:
}
return $qtns;
}
function questionChoices(int $qtnID){
$this->db->where('o_questions_id', $qtnID);
$query = $this->db->get('options_table');
return $query->result_array();
}
Then from your view you can display the questions as:
<?php foreach($qtns as $one){ ?>
<strong><?= $one['q_id'] ?>.<?= $one['q_title'] ?></strong>
<?php foreach ($one['choices'] as $o) { ?>
<p><?= $o['o_title'] ?></p>
<?php } ?>
<?php } ?>
Related
I have two tables in my mySQL database:
table "animals":
| animal | name |
|:-----------|------------:|
| cat | Tom |
| dog | |
table "orders":
| id | animal |
|:-----------|------------:|
| 1 | cat |
| 2 | dog |
At first I select from the table "orders" the following data:
<?php
$pdo = Database::connect();
$sql = 'SELECT * FROM orders ORDER BY id ASC';
foreach ($pdo->query($sql) as $row) {
echo ('<td>a:'.$row['id'].'</td>');
echo ('<td>b:'.$row['animal'].'</td>');
echo ('<td>c:'.$row['animal'].'</td>');
}
Database::disconnect();
?>
Now I want to check if in my mySQL table "animal" the animal has a name. If yes print at position b the name. If there is no name print the animal:
| a:1 | b:Tom | c:cat |
| a:2 | b:dog | c:dog |
Thank you for your answers! I tried to work now with the answer of Jayo2k. I need to do a little change in my question, I found out I did a little mistake. So here I try to describe what I need as specific as possible:
table "animals":
| name | animal |
|:-----------|------------:|
| Tom | cat |
| Jerry | dog |
| Alfred | duck |
| Sam | |
| Donald | |
table "orders":
| id | animal |
|:-----------|------------:|
| 1 | cat |
| 2 | dog |
| 3 | duck |
| 4 | frog |
| 5 | pig |
With the following code from Jayo2k...
<?php
$pdo = Database::connect();
$sql = "SELECT * FROM animals, orders WHERE orders.animal = animals.animal";
foreach ($pdo->query($sql) as $row) {
echo '<tr> ';
echo('<td>a:'.$row['id'].' </td>');
echo('<td>a:'.$row['animal'].' </td>');
echo('<td>b:'.$row['name'].' </td>');
echo '</tr> ';
}
Database::disconnect();
?>
... I get this result:
| a:1 | b:cat | c:Tom |
| a:2 | b:dog | c:Jerry |
| a:3 | b:duck | c:Alfred |
But what I need is:
| a:1 | b:cat | c:Tom |
| a:2 | b:dog | c:Jerry |
| a:3 | b:duck | c:Alfred |
| a:4 | b:frog | c:frog |
| a:5 | b:pig | c:pig |
You can use LEFT JOIN, and use the IF condition to check the value is not empty, along with IFNULL, that will make null values in columns to blank.
SELECT O.id, IF(IFNULL(A.name, '') = '', A.animal, A.name) name, A.animal
FROM orders O
LEFT JOIN animals A
ON O.animal = A.animal
ORDER BY O.id DESC
What I do is (I am using PDO):
SELECT * FROM animal, orders WHERE orders.animal = animals.animal
It will select both animals and orders table and joint the animal row from orders with the animal row from animal.
you should get an array like this
[0] =>
id = 1
name = tom
animal = cat
[1] =>
id = 2
name =
animal = dog
Now up to you to do all the modification you want
my database design is like this
-- Table Reason
--------------------------
| reasonid | reasonname |
--------------------------
| 1 | reason1 |
| 2 | reason2 |
--------------------------
-- Table Student
----------------------------
| studentid | studentname |
----------------------------
| 1 | John |
| 2 | Jane |
| 3 | Hulk |
----------------------------
-- Table form
-----------------------------------
| formid | studentid | reasonid |
-----------------------------------
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 1 |
-----------------------------------
I want to show data table like :
reason1
| 1 | John |
| 2 | Hulk |
reason2
| 1 | Jane |
I have tried below code but the result is not groupBy reason
<?php $i =1;
while($rowfet = mysql_fetch_array($myselect)){ ?>
<h2><?php echo $rowfet['ReasonName']; ?></h2>
<table>
<thead>
<tr class="active">
<th>No.</th>
<th>StudentName</th>
</tr>
</thead>
<tbody>
<tr>
<td align="center"><?php echo $i; ?></td>
<td><?php echo $rowfet['STUDENTNAME']; ?></td>
</tr>
</tbody>
</table>
<?php $i++; } ?>
the result of this code is :
reason1
| 1 | John |
reason1
| 2 | Hulk |
reason2
| 3 | Jane |
You could do something like this:
outside while loop:
$lastReasonId = '';
inside while loop:
if($rowfet['reasonid'] != $lastReasonId){
// show heading
}
$lastReasonId = $rowfet['reasonid'];
But your code is far from ok. The $i++ thing is not doing anything, you should probably echo $rowfet['studentid'] there.
And you are using deprecated mysql code.
I may not use the proper subject of the problem. But here's the detail. I've got 3 tables of data 2 of them are set name and group name. The rest is data - user db. Here's the db.
set_name
+--------+-----------+
| set_id | set_title |
+--------+-----------+
| 1 | Set A |
+--------+-----------+
| 2 | Set B |
+--------+-----------+
group_db
+--------+-----------+--------+
| grp_id | grp_title | set_id |
+--------+-----------+--------+
| 1 | Grp. A | 1 |
+--------+-----------+--------+
| 2 | Grp. B | 1 |
+--------+-----------+--------+
| 3 | Grp. C | 1 |
+--------+-----------+--------+
| 4 | Grp. D | 1 |
+--------+-----------+--------+
| 5 | Grp. E | 1 |
+--------+-----------+--------+
| 6 | Grp. F | 2 |
+--------+-----------+--------+
user_db
+--------+-----------+
| usr_id | grp_id |
+--------+-----------+
| 1 | 1 |
+--------+-----------+
| 2 | 1 |
+--------+-----------+
| 3 | 2 |
+--------+-----------+
| 4 | 1 |
+--------+-----------+
| 5 | 3 |
+--------+-----------+
| 6 | 4 |
+--------+-----------+
| 7 | 5 |
+--------+-----------+
| 8 | 5 |
+--------+-----------+
| 9 | 5 |
+--------+-----------+
| 10 | 6 |
+--------+-----------+
According to the information provided above. I expect a summary table in which count all user and categorize by group and set. For example:
+-----+--------------------------------------------+--------+
| SET | Set A. | Set B. |
+-----+--------------------------------------------+--------+
|GROUP| Grp. A | Grp. B | Grp. C | Grp. D | Grp. E | Grp. F |
+-----+--------------------------------------------+--------+
| NUM | 3 | 1 | 1 | 1 | 3 | 1 |
+-----+--------------------------------------------+--------+
|TOTAL| 9 | 1 |
+-----+--------------------------------------------+--------+
And this is how I do.
<table>
<tr>
<?
$sql_set=mysqli_query($con,"SELECT *,count(group_db.grp_id) AS nGrp\n"
. "FROM set_name\n"
. "INNER JOIN group_db ON set_name.set_id=group_db.set_id\n"
. "GROUP BY set_name.set_id\n"
. "ORDER BY set_name.set_id asc");
echo "<td>SET</td>";
while($rec_set=mysqli_fetch_array($sql_set)){
echo "<td colspan=\"$rec_set[nGrp]\">$rec_set[set_title]</td>";
}
?>
</tr>
<tr>
<?
$sql_sGrp=mysqli_query($con,"SELECT * from group_db\n"
. "WHERE set_id='$rec_set[set_id]'\n"
. "ORDER BY grp_title asc");
echo "<td>GROUP</td>";
while($rec_sGrp=mysqli_fetch_array($sql_sGrp)){
echo "<td>$rec_sGrp[grp_title]</td>";
}
?>
</tr>
</table>
That's it. I don't know how to go further. Please be advice.
Ps. Should I make them all in multilevel array to make it easier?
I would do something like:
SELECT
*
FROM
user_db u
JOIN
group_db g ON u.grp_id = g.grp_id
JOIN
set_name s ON g.set_id = s.set_id
(EDIT: changed qry to this ^ which can be seen here: http://sqlfiddle.com/#!2/e749f/4)
And then in PHP:
$newArray = array();
while($rec_set=mysqli_fetch_array($sql_set)){
$newArray[$rec_set['set_title']][$rec_set['grp_title']] += 1;
}
which should give you a nice multidimensional array of the results that you can parse through however you want
And to give a table that looks like:
+-----+--------------------------------------------+--------+
| SET | Set A. | Set B. |
+-----+--------------------------------------------+--------+
|GROUP| Grp. A | Grp. B | Grp. C | Grp. D | Grp. E | Grp. F |
+-----+--------------------------------------------+--------+
| NUM | 3 | 1 | 1 | 1 | 3 | 1 |
+-----+--------------------------------------------+--------+
|TOTAL| 9 | 1 |
+-----+--------------------------------------------+--------+
I would use:
<tr>
<td>SET</td>
<?php foreach($newArray as $set => $group): ?>
<td colspan="<?=count($newArray[$set])?>"><?=$set?></td>
<?php endforeach; ?>
</tr>
<tr>
<td>GROUP</td>
<?php foreach($newArray as $set => $group): ?>
<?php foreach($group as $group_name => $amount): ?>
<td><?=$group_name?></td>
<?php endforeach; ?>
<?php endforeach; ?>
</tr>
<tr>
<td>NUMBER</td>
<?php foreach($newArray as $set => $group): ?>
<?php foreach($group as $group_name => $amount): ?>
<td><?=$amount?></td>
<?php $totals[$set] += $amount;?>
<?php endforeach; ?>
<?php endforeach; ?>
</tr>
<tr>
<td>TOTAL</td>
<?php foreach($newArray as $set => $group): ?>
<td colspan="<?=count($newArray[$set])?>"><?=$totals[$set]?></td>
<?php endforeach; ?>
</tr>
However, now that I look at how you would actually display it, if you really wanted a table that looked like you put, then a multidimensional array would probably not be the best way to loop through your data since all these loops are UGLY! (And it does not scale too well horizontally as you add more and more sets and groups). I did not check it for accuracy.
echo '<table>';
$rows = array('SET', 'GROUP', 'NUM', 'TOTAL');
$setids = array();
$grp_usercounts = array();
$set_usertotals = array();
foreach($rows as $key => $row){
echo "<tr> $rows </td>";
switch ($key){
case 0: //SET
$sql = "SELECT s.set_id, set_title, count(g.grp_id) nGrp
FROM set_name s
JOIN group_db g ON s.set_id = g.set_id
group by set_id";
$sql_set = mysqli_query($con, $sql);
while($rec_set=mysqli_fetch_array($sql_set)){
echo '<td colspan="'.$rec_set['nGrp'].'">'. rec_set['set_title'].'</td>';
$setids[$rec_set['set_id']] = $rec_set['nGrp'];
}
break;
case 1://GROUP
foreach($setids as $setid => $val){
$sql = "SELECT g.grp_id, grp_title, count(usr_id) nUsr
FROM group_db g
JOIN user_db u ON u.grp_id = g.grp_id
where set_id = $setid
group by g.grp_id order by grp_title";
$sql_set = mysqli_query($con, $sql);
$total = 0;
while($rec_set=mysqli_fetch_array($sql_set)){
echo '<td>'. $rec_set['grp_title'].'</td>';
$grp_usercounts[$rec_set['grp_id']] = $rec_set['nUsr'];
$total += $rec_set['nUsr'];
}
$set_usertotals[$setid] = $total;
}
break;
case 2://NUM
foreach($grp_usercounts as $key => $grp_usercount){
echo '<td>'. $grp_usercount .'</td>';
}
break;
case 3: //TOTAL
foreach($set_usertotals as $setid => $set_usertotal){
echo '<td colspan="'.$setids[$setid].'">'. $set_usertotal .'</td>';
}
break;
}
}
unset($setids);
unset($grp_usercounts);
unset($set_usertotals);
echo '</table>';
I have a MySql table and I want to list things by type and insert headers. What type of query would I use?
From This:
| Fluffy | Harold | cat | f | 1993-02-04 | NULL |
| Claws | Gwen | cat | m | 1994-03-17 | NULL |
| Buffy | Harold | dog | f | 1989-05-13 | NULL |
| Fang | Benny | dog | m | 1990-08-27 | NULL |
| Bowser | Diane | dog | m | 1979-08-31 | 1995-07-29 |
| Chirpy | Gwen | bird | f | 1998-09-11 | NULL |
| Whistler | Gwen | bird | f | 1997-12-09 | NULL |
| Slim | Benny | snake | m | 1996-04-29 | NULL |
| Dalli | Alli | canine | m | 2001-12-20 | NULL |
| Tara | David | canine | f | 2002-05-17 | NULL |
| Mimi | Alli | guinea pig | m | 2004-05-17 | NULL |
To this:
<h2>Cat</h2>
<ul>
<li>Fluffy</li>
<li>Claws</li>
</ul>
<h2>Dog</h2>
<li>Buffy</li>
<li>Fang</li>
<li>Bowser</li>
</ul>
etc.
Don't try to do all of this with SQL (just do a standard select query), use PHP to group the result, then present it. The best way to do this would be to have an object that will do the grouping for you, as you'll probably need it more than once. For example, your class could look something like this:
<?php
class Arrays
{
public static function group($array,$key)
{
if(NULL == $array)
return NULL;
$grouped = NULL;
foreach($array as $item)
{
$grouped[$item[$key]][] = $item;
}
return $grouped;
}
}
?>
And your use case could be something like:
<?php
$result = ...; // The result of your database query.
$grouped_by_type = Arrays::group($result,"type");
foreach($grouped_by_type as $type => $group)
{
echo "<h2>".ucwords($type)."</h2>";
echo "<ul>";
foreach($group as $animal)
{
echo "<li>".$animal['first_name']."</li>"; // Assumes the query brought back first_name...
}
echo "</ul>";
}
?>
Your first query would be:
SELECT DISTINCT type FROM table ORDER BY type ASC
With your PHP, I am sure you can get a result from this query and loop through it. Next one is to put another query inside the loop that gives you the list of animals that belong to current type:
SELECT name FROM table WHERE type='$type' ORDER BY name ASC
$type is just variable holding current type. I assumed column and table names so please change it to suit your code.
My data base looks like this.
its ordered ascending by NO#
And col2 is the start of the database NO# is basically invisible and only used as a reference as to row number
so lets say I wanted to display on a web page the text in col8, row 5. What would the php code be?
PS. the connect code is seperate and not an issue hence i did not include itI
-|NO#|col2|col3|col4|col5|col6|col7|col8|col9|col10
---------------------------------------------------
|1 | | | | | | | | | |
---------------------------------------------------
|2 | | | | | | | | | |
---------------------------------------------------
|3 | | | | | | | | | |
---------------------------------------------------
|4 | | | | | | | | | |
---------------------------------------------------
|5 | | | | | | |2012| | |
---------------------------------------------------
|6 | | | | | | | | | |
---------------------------------------------------
|7 | | | | | | | | | |
---------------------------------------------------
|8 | | | | | | | | | |
---------------------------------------------------
|9 | | | | | | | | | |
---------------------------------------------------
|10 | | | | | | | | | |
---------------------------------------------------
Here is my code but it whites out the page when I try to load it.
<?php
//selects row
$query = "SELECT * FROM `Inventory` WHERE NO# = '5'";
//select column
$col8 = $row['col8'];
// fetch the results
WHILE($row = mysql_fetch_array($query):
$row = mysql_fetch_array($result);
// display the results
<div id="year">echo "$col8";</div>
?>
I would probably do something like what's below. I have not tested this code, though.
<?php
$result = mysql_query( "SELECT `col8` FROM `Inventory` WHERE `NO#` = '5' LIMIT 1" );
$row = mysql_fetch_assoc( $result );
?>
<div id="year"><?php echo $row['col8']; ?></div>
Hopefully that'll help you out a bit.