PHP, While loop not showing results - php

i am new to PHP and mysql, I am trying to build a table. However, I have a very interesting bug that i can't fix.
code:
//Initializing mysql queries
//-----------------------SELECTING GOALS------------
$sql= "SELECT * FROM goals";
$records = mysql_query($sql);
//-----------------------SELECTING SERVICES---------
$sql2= "SELECT * FROM services";
$records2 = mysql_query($sql2);
//----------------SELECTING THE JUNCTION----------
$sql3 = "SELECT services.sid AS sid, services.name, objectives.oid
FROM services, objectives, servo
WHERE servo.s_id = services.id AND servo.obj_id = objectives.id";
$records3 = mysql_query($sql3);
$sql4 = "SELECT oid, gid, statement, GROUP_CONCAT(DISTINCT gid) AS GOID
FROM goals, objectives, obgoals
WHERE obgoals.go_id = goals.id AND obgoals.ob_id = objectives.id
GROUP BY oid";
$records4 = mysql_query($sql4);
<?php
while ($product = mysql_fetch_assoc($records2)) {
echo "<tr>";
$sid = $product['sid'];
$service = $product['name'];
echo "<td><a href='objectives.php?sid=" . $sid . "&service=" . $service . "'>" . $product['sid'] . "</a> </td>";
echo "<td>".$product['name']."</td>";
echo "<td>";
while ($g4services = mysql_fetch_assoc($records)) {
echo $g4services['gid'];
}
echo"</td>" ;
}
?>
Basically, my table has 30 rows and 3 columns, the last column is supposed to print out values from a database, this part is done by this piece of code
while ($g4services = mysql_fetch_assoc($records)) {
echo $g4services['gid'];
}
However, instead of printing the results for each row, it only prints the results for the first row, basically the first while loop runs and creates the the table with the 30 rows, but the second while loop only prints values on first row only. Essentially this is happening:
|SID|Name Of Service| Objectives|
-------------------------------
|S1| Service 1 | make the best cars|
|s2| Service 2 | |
|s3| Service 3 | |
|s4| Service 5 | |
|s5| Service 5 | |
.....
.....
....
|s30| Service30 | |
for some reason, my objectives column is not populated by the while loop, it only works for the first row. If someone can help me work the while loop to print the values for every row, it will be huge help. I will greatly appreciate it. Thanks.

The problem is that you're reading all the results of $records during the first iteration of the outer while loop. On future iterations, there are no more rows left, so the inner while loop completes immediately.
You can read those results once into a variable outside the loop, and then show that variable during the loop:
$all_g4services = '';
while ($g4services = mysql_fetch_assoc($records)) {
$all_g4services .= $g4services['gid'];
}
while ($product = mysql_fetch_assoc($records2)) {
echo "<tr>";
$sid = $product['sid'];
$service = $product['name'];
echo "<td><a href='objectives.php?sid=" . $sid . "&service=" . $service . "'>" . $product['sid'] . "</a> </td>";
echo "<td>".$product['name']."</td>";
echo "<td>$all_g4services;</td>" ;
}

Your second while loop is not required. It is runnning for each row. Remove it. Then for each row you have to find the entry that matches and echo only that.
echo $g4services['gid']
I dont know how to correct it for you as I dont know the relationship between the two.

Related

PHP Mysql query multiple items

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.

retrieving data from two databases

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.

MySQL Table Correlation

I'm kinda a noob so I don't know if this is actually possible.
I have two field in my MySQL database that I want to correlate:
Level int(11)
Rank enum('Hobo','Shippai','NoLifer',Troublemaker','gangster') (and so it continues.)
I want so that level 1=Hobo, level 2=Shippai etc. etc.
Currently it looks like this:
Level: {$ir['level']}
And want it to look like this on the website:
Rank: Hobo
Thanks in advance for any help...
Edit:
Here's the code for the table:
";
$exp=(int)($ir['exp']/$ir['exp_needed']*100);
print "
Name: {$ir['username']}Crystals: {$cm}
Level: {$ir['level']}
Exp: {$exp}%
Money: $fm
Gang: ";
$qs=$db->query("SELECT * FROM gangs WHERE gangID={$ir['gang']}");
$rs=$db->fetch_row($qs);
if(!$db->num_rows($qs) )
{
print "No Gang";
}
else
{
print" {$rs['gangNAME']} ";
}
print "
Property: {$ir['hNAME']}
Days Old: {$ir['daysold']}
Health: {$ir['hp']}/{$ir['maxhp']}
Energy: {$ir['energy']}/{$ir['maxenergy']}
Brave: {$ir['brave']}/{$ir['maxbrave']}
Will: {$ir['will']}/{$ir['maxwill']}
";
Create a new table called rank_define inside have, id(int, primary key, auto increment), name(char20), add your named ranks so it looks like this:
id | name
1 | Hobo
2 | Shippai
In your code
$user_id = 1; // or whatever the users rank is
$query = mysql_query("SELECT `name` FROM rank_define WHERE id='$user_id'");
This will return a result set so you will want to do:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "rank: " . $row['name']; // will output rank: Hobo
}
I think this is what you mean, is it for a user account or something different? This is assuming no account and you are just searching for a result.
If it were to be part of a user account system you would want a table for users eg: id (auto inc, primary key, int), name, rank, (etc..)
In rank their rank is inserted from the rank_define table, so 1 = hobo, 2 = shippai etc. Then you would query that table
Updated answer:
Okay so you have the while loop.while ($row = mysql_fetch_array($query, MYSQL_NUM)) {.
It will go something like this:
<table>
<?php
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>Name: " . $row['name'] . "</td>"; // will output their name / account whatever
echo "<td>Rank: " . $row['rank'] . "</td>"; // will output their rank
echo "</tr>";
}
?>
</table>

php-sql groups data with the same category

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.

PHP: table structure

I'm developing a website that has some audio courses, each course can have multiple lessons. I want to display each course in its own table with its different lessons.
This is my SQL statement:
Table: courses
id, title
Table: lessons
id, cid (course id), title, date, file
$sql = "SELECT lessons.*, courses.title AS course FROM lessons INNER JOIN courses ON courses.id = lessons.cid GROUP BY lessons.id ORDER BY lessons.id" ;
Can someone help me with the PHP code?
This is the I code I have written:
mysql_select_db($database_config, $config);
mysql_query("set names utf8");
$sql = "SELECT lessons.*, courses.title AS course FROM lessons INNER JOIN courses ON courses.id = lessons.cid GROUP BY lessons.id ORDER BY lessons.id" ;
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<p><span class='heading1'>" . $row['course'] . "</span> </p> ";
echo "<p class='datum'>Posted onder <a href='*'>*</a>, latest update on " . strftime("%A %d %B %Y %H:%M", strtotime($row['date']));
}
echo "</p>";
echo "<class id='text'>";
echo "<p>...</p>";
echo "<table border: none cellpadding='1' cellspacing='1'>";
echo "<tr>";
echo "<th>Nr.</th>";
echo "<th width='450'>Lesso</th>";
echo "<th>Date</th>";
echo "<th>Download</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['nr'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . strftime("%d/%m/%Y", strtotime($row['date'])) . "</td>";
echo "<td><a href='audio/" . rawurlencode($row['file']) . "'>MP3</a></td>";
echo "</tr>";
echo "</table>";
echo "<br>";
}
?>
One thing that comes to mind is you're starting with lessons and pulling the course details over with it. That means you're going to have a new row per lesson with a joined course. You may want to sort by course (so they're grouped) then (in PHP) keep a tally of "current course". When the course changes, switch to new heading paragraph, table, etc.
Pseudo code:
$currentCourse = null; // intitialize the course
$query = your select sorted by course;
while ($row in $query)
{
if ($currentCourse != $row['course'])
{
if (!is_null($currentCourse))
{
// there was a course before it, close the current one
}
// begin setting up heading1, table beginning, etc.
$currentCourse = $row['course']; // set this as the active course
}
// dump the current row as a table entry
}
// close the table (same code as in the second if statement)
You close the while loop on line 8 of your code block. Remove that '}' on line 8.
Also the HTML element doesn't exists!
I think I know what's your problem. You need a while loop that loops al the "courses" and in that loop you execute a second query where you select the lessons where the course_id is equal to the current course id you're looping. A little dummy code for you.
<?php
while($row = mysql_fetch_assoc(mysql_query("SELECT * FROM courses"))) {
//display the course
while($row2 = mysql_fetch_assoc(mysql_query("SELECT * FROM lessons WHERE course_id=" . $row['id']))) {
//display the lessons of that course
}
}
?>

Categories