This is a code pinch from a webpage of my project. Here I want to display user selected categories and then want to display its subjects that belong to the categories. There, users could have more than one category, and it is no problem. I can print all those categories in my first while loop. The problem is when I'm trying to print subjects, they only show one row as a result, but there are more subjects in each category. Can anybody tell me what is happening?
This is my code.
Note: Both queries are working properly. I tried those using a mysql client program.
<?php
require_once ('../../includes/config.inc.php');
require_once( MYSQL1 );
$q = "SELECT institute_category.category_id, category_name
FROM institute_category
INNER JOIN category ON institute_category.category_id = category.category_id
WHERE institute_category.institute_id = $instituteId";
$r = mysqli_query( $dbc, $q);
while ( $row = mysqli_fetch_array ( $r, MYSQLI_ASSOC) ) {
$categoryId = $row['category_id'];
$category = $row['category_name'];
echo '<fieldset class="alt">
<legend><span>Category : <em style="color: red;">' . $category .
'</em></span></legend>';
$qy = "SELECT category_subject.category_id, category_subject.subject_id, subjects
FROM category_subject
INNER JOIN category ON category_subject.category_id = category.category_id
INNER JOIN subject ON category_subject.subject_id = subject.subject_id
WHERE category_subject.category_id = $categoryId";
$result = mysqli_query( $dbc, $qy);
$c = $i = 0;
echo '<table class="form_table" ><tr>';
while($row = mysqli_fetch_array( $result, MYSQLI_ASSOC )){
// if remainder is zero after 2 iterations (for 2 columns) and when $c > 0, end row and start a new row:
if( ($c % 2) == 0 && $c != 0){
echo "</tr><tr>";
}
echo '<td width="50%"><input type="checkbox" name="subject[]" value="' .
$row['category_id'] . ":" . $category . ":" . $row['subject_id'] .
":". $row['subjects'] . '" /> ' . $row['subjects'] .
'</td>' . "\n";
$c++;
} // while..
// in case you need to fill a last empty cell:
if ( ( $i % 2 ) != 0 ){
// str_repeat() will be handy when you want more than 2 columns
echo str_repeat( "<td> </td>", ( 2 - ( $i % 2 ) ) );
}
echo "</tr></table>";
}
echo '</fieldset>';
?>
Turning my comment into an answer:
Only looking at your code for a second I can see that you're using the $row variable both for the outer loop and for the inner loop. Try renaming the outer loop's $row variable to $outerRow and the inner loop's $row variable to $innerRow. This may be the first problem. This may apply to other variables, too, like for example the $result variable.
user different variable name for inner loop $result and $row like $inresult and $inrow
Because you have used a same variable $row in both of the loops, $row[] in inner loop could be taking reference of outer one and in that result set the variable you are looking for not present so that not printing anything from inner loop, please change the variable of inner or outer loop.
Related
I have this part of code:
resultrights = $conn->query("SELECT userid, page FROM pagerights WHERE userid = '" . $_SESSION['uid'] . "'");
while ($rowrightss = $resultrights->fetch_assoc()) {
echo $rowrightss['page']."<br>";
}
This works. It just echoes the numbers
1
2
3
5
Perfectly fine.
Now, I want to select a few buttons based on that numbers. They are button numbers, declared else in the DB.
Somewhere later I have this:
<?php
$i = 0;
$result = $conn->query("select pagenumber, pagetitle from pages WHERE pagenumber = '" . $_SESSION['assignedpage'] . "'");
echo "<html>";
echo "<body>";
echo '<table cellpadding="20">';
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['pagenumber'];
$name = $row['pagetitle'];
$i++;
//if this is first value in row, create new row
if ($i % 3 == 1) {
echo "<tr>";
}
echo '<td><button1 id="groteknop" class="btn-state state-start" onclick="Switchf();"><i id="knopje" class="icon icon-start"></i></button1></td>';
//if this is third value in row, end row
if ($i % 3 == 0) {
echo "</tr>";
}
}
//if the counter is not divisible by 3, we have an open row
$spacercells = 3 - ($i % 3);
if ($spacercells < 3) {
for ($j=1; $j<=$spacercells; $j++) {
echo "<td></td>";
}
echo "</tr>";
}
echo "</select>";
$conn->close();
?>
What I am trying to achieve, is instead of the pagenumber = the session value assigned page, I want to select all buttons from the result of the query before. Endresult: I want to display button 1, 2, 3, 5. This numbers are coming from the first query. So when these numbers change, and they do, because they are selected based on userid, I want to display the result of that query.
How can I get that working?
Try with this query
select pagenumber, pagetitle from pages WHERE pagenumber in
(SELECT page FROM pagerights WHERE userid = '" . $_SESSION['uid'] . "')
To me this seems a task for an inner join, which would join pagerights table with the pages table. If I understood your question correctly, then pagerights.page should match page.pagenumber.
SELECT page.pagenumber, page.pagetitle FROM pagerights
INNER JOIN page ON pagerights.page=page.pagenumber
WHERE userid=...
Substitute the user id from session in the place of ... in the query. this way you need to run only a single query.
I have two databases and tables in each. Am reading the renewal_date of DB1 table 1 and taking the renewal_date of the current month and domain_name for that record.
then am trying to retrieve the d_due_date from DB2 table2 for the domain_name selected from DB1 table1.
then i need to display domain_name, renewal_date,d_due_date in one table.
I can do this by joining the database with INNER JOIN.
what i need is to write separate select queries and display.
$sql = "select domain_name from table1 where MONTH(renewal_date) = '06'";
$result = mysqli_query($link_id,$sql);
if(!$result) die(sql_error());
$DoNM= Array();
$sql1= "select d_due_date from domains where d_domain IN ('abc.com','akaaasa.com')";
$result1 = mysqli_query($link_id1,$sql1);
if(!$result1) die(sql_error());
$DoNM1= Array();
echo '<table>';
while(($row1 = mysqli_fetch_array($result1,MYSQL_ASSOC))&&($row = mysqli_fetch_array($result,MYSQL_ASSOC))){
echo "<tr>";
echo "<td>" .$DoNM[]= $row['domain_name'] . "</td>";
echo "<td>" .$DoNM[]= $row['renewal_date'] . "</td>";
echo "<td>" .$DoNM1[]= $row1['d_due_date'] . "</td>";
echo "</tr>";
}
echo '</table><br />';
I have hardcoded the domain name in $sql1. what I want is to get that from $sql. how can I do that.
So all you need to do is process through the first query results and build the array, then convert the contents of the array to a comma delimited list
$sql = "select domain_name, renewal_date
from table1
where MONTH(renewal_date) = '06'";
$result = mysqli_query($link_id,$sql);
if(!$result) die(sql_error());
$db1= Array();
$InList = '';
while( $row = mysqli_fetch_array($result,MYSQL_ASSOC) ) {
$InList .= sprintf("'%s',", $row['domain_name']);
$db1[$row['domain_name']] = $row['renewal_date'];
}
$InList = rtrim($InList, ',');
$sql = "select d_due_date, d_name
from domains
where d_domain IN ($InList)";
$result = mysqli_query($link_id1,$sql);
if(!$result) die(sql_error());
echo '<table>';
while( $row = mysqli_fetch_array($result,MYSQL_ASSOC ){
echo '<tr>';
echo '<td>' . $row['d_name'] . '</td>';
// find the db1.renewal_date matching d_name from db1 array
echo '<td>' . $db1[$row['d_name']] . "</td>";
echo '<td>' . $row['d_due_date'] . '</td>';
echo "</tr>";
}
echo '</table><br />';
RE: Your comment
So now I have saved the data from db1 into an array you can use the get the db1.renewal_date from in the output phase. Also I added the db1.d_name to the second query so you have the key to the array containing the db1.renewal_date
RE: Using more fields from table1:
Sure, thats not a problem. This will mean that you have to store an array i.e. the $row as the data so you have the complete set of columns saved in the $db1 array.
$sql = "select domain_name, renewal_date, f3, f4
from table1
where MONTH(renewal_date) = '06'";
$result = mysqli_query($link_id,$sql);
if(!$result) die(sql_error());
$db1= Array();
$InList = '';
while( $row = mysqli_fetch_array($result,MYSQL_ASSOC) ) {
$InList .= sprintf("'%s',", $row['domain_name']);
$db1[$row['domain_name']] = $row;
}
$InList = rtrim($InList, ',');
The $db1 array will now look like this:
Array
(
[abc.com] => Array
(
[domain_name] => abc.com
[renewal_date] => 2015-06-06
[f3] => aaa
[f4] => bbb
)
[xyz.com] => Array
(
[domain_name] => xyz.com
[renewal_date] => 2015-06-07
[f3] => ccc
[f4] => ddd
)
)
So the domain name is still the KEY to each occurance of the array, but you have another array associated with the key rather than just a single string.
So to access this array you do this to use a domains specific columns.
echo '<td>' . $db1[ $row['d_name'] ] ['renewal_date'] . "</td>";
echo '<td>' . $db1[ $row['d_name'] ] ['f3'] . "</td>";
echo '<td>' . $db1[ $row['d_name'] ] ['f4'] . "</td>";
I hope that is explained well enough to help you.
First of all, you can do this in just one database with multiple tables which would be nicer and easier to use than you should be able to do something like:
SELECT domain_name,renewal_date,d_due_date
FROM table1 INNER JOIN table2
ON table2.d_name = table1.domain_name
WHERE MONTH(table1.renewal_date) = '06'";
Something like this(also see this as referance)
using where and inner join in mysql
I think that due to use of && operator in while loop. There may be one of the table's result is empty and that's why the result set may be empty.
I have 2 tables, in 1 table there are lists of all the episodes from a movie and in the other table there are the streams from the episode. Every episode got his own id so the streams are linked via the id from the episode.
But now I have a problem: I want to make a episode-list and at the same time I want to insert a link to the stream. So that means that I have to fetch 2 tables at the same time but I don't know how. This is my code
<?php
include 'connection.php';
$a = (int)$_GET['a'];
if ($result = $con->prepare("SELECT id, ep_nr, ep_title FROM anime_episode WHERE ani_id = $a"))
{
$result->execute();
$result->bind_result($eid, $nr, $title);
while ($result2 = $con->prepare("SELECT * FROM anime_stream WHERE ep_id = $eid"))
{
$result2->execute();
$result2->bind_result($eid, $etitle, $lang, $sname, $link, $uploadedby);
echo '<div id="list-box">';
echo '<table cellspacing="0">';
while ($result->fetch() && $result2->fetch())
{
echo '<tr>';
echo '<td width="50">' . $nr . '</td>' . '<td>' . $title . '</td>' . '<td>' . $link. '</td>';
echo '</tr>';
}
echo '</div>';
echo '</table>';
}
}
$con->close();
?>
As Strawberry suggests, I believe your looking to join the two table based on the foreign key and select the content of both tables, somethig like...
select
epi.*,
str.*
from
anime-episode epi
inner join
anime-stream str on epi.ani-id = str.epi-id
where
epi.ani-id = $id
This assumes that your episodes will always have at least one stream as an inner join will only return a row (with the column of both tables) when a record is found in each of the tables of the join. A Left Outer join can be used which will still return movies even if no streams exist for a given episode.
Can't find underline on my tablet!
A query something like this should do the trick.
SELECT ae.id, ae.ep_nr, ae.ep_title, as.* FROM anime_episode ae
LEFT JOIN anime_stream as ON as.ep_id = ae.id
WHERE ae.ani_id = [$arg]
How can I print my fetch rows into groups of data?
For example i have these on my database
title category
one number
two number
three number
a letter
b letter
c letter
and I wanted to print it out on a different table.
table1 table2
number letter
one a
two b
three c
here's what I've tried.
$select = "SELECT * FROM `table` ORDER BY `category`";
$result = mysql_query($select);
$current_cat = null;
while ($rows = mysql_fetch_array($result))
{
if ($rows["category"] != $current_cat)
{
$current_cat = $rows["category"];
echo "<p>$current_cat</p>";
}
echo"$rows[title]";
}
the output of these codes is like this
number
one
two
three
letter
a
b
c
but then again, I wanted it to be in separate table.
You could add an if statement to test if the $current_cat is equal to the previous loops $current_cat. Do so by adding a new variable $last_cat, setting it equal to the current iterations $current_cat at the end of the while loop. Here is an example
$select = "SELECT * FROM `table` ORDER BY `category`";
$result = mysql_query($select);
$current_cat = null;
$last_cat = null;
while ($rows = mysql_fetch_array($result)) {
if ($current_cat == null) {
// Create a table with an id name of the first table
echo "<table id='" . $rows["category"] . "'>";
// Write the first row of the table - Category Title
echo "<tr class='categoryTitle'><td>" . $rows["category"] . "</td></tr>";
}
// Set the $current_cat to current loop category value
$current_cat = $rows["category"];
if ($last_cat != null) {
if ($current_cat != $last_cat) {
// Close table from previous $current_cat
echo "</table>";
// Create new table with id name of the category
echo "<table id='" . $rows["category"] . "'>";
// Write the first row of the table - Category Title
echo "<tr class='categoryTitle'><td>" . $rows["category"] . "</td></tr>";
}
}
}
// Write new row in table with the value of the title
echo "<tr><td>" . $rows[title] . "</td></tr>";
// set the $last_cat to the value of $current_cat at the end of the loop
$last_cat = $current_cat;
}
// Close the last table after while loop ends
echo "</table>";
This will allow you to create separate tables based on the category name no matter how many categories you have and allow you to style the tables based on the category name.
in my query i want only from id 1-3 to appear in the result, not 4-6. is there any other way to do it?
beautician database table:
id_beautician name
1 a
2 b
3 c
4 d
5 e
6 f
i tried to put the code below in mysql query
for($i=4; $i<=6; $i++) :
$q.$i = $db->query("SELECT * FROM beautician WHERE id_beautician='$i'");
$r.$i = $q.$i->fetch_assoc();
//echo $i;
endfor;
but it gives me an error:
Object of class mysqli_result could
not be converted to string
Instead of doing n queries, modify SQL query to match only data you need - for example:
$query = $db->query("SELECT * FROM beautician WHERE id_beautician <= 3");
while ( $row = $query->fetch_assoc() ) {
echo $row['id'] . ' = ' . $row['name'] . '<br/>';
}
If ids are not in sequence, you can also use as below.
$query = $db->query("SELECT * FROM beautician WHERE id_beautician in (1,2,3)");
while ( $row = $query->fetch_assoc() )
{
echo $row['id'] . ' = ' . $row['name'] . '<br/>';
}
using IN in query sometimes slow down the execution, but can be used efficiently for small-size database.