I am new to PHP and I just cannot figure out my code. I am using MySQL and PHP.
table: person
PK: personID
Other fields: lastName, firstName, hireDate, imgName
table: validMajors
PK: majorAbbrev
Other Fields: majorDesc
(Junction) table: personMajors
personID, majorAbbrev
When I run my code (using NATURAL JOIN) it will display the image, last&first name, and hire date. Which is great! But I need it to display their majors as well (I would like the majorAbbrev to be displayed). It also does not display people who are in the person table but are not in the personMajors table, which is an issue because we have staff members in the person table (who do not have a major since they are not a student)
Here is my code:
<table align="center">
<?php
$connection = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME);
if ( mysqli_connect_errno() ) {
die( mysqli_connect_error() );
}
$sql = "SELECT * FROM person NATURAL JOIN personMajors ORDER BY lastName";
if ($result = mysqli_query($connection, $sql)) {
// loop through the data
$columns=4;
$i = 0;
while($row = mysqli_fetch_assoc($result))
{
if($i % $columns ==0){
echo "<tr>";
}
echo "<td class='staffImage badgeText frameImage displayInLine'>" . "<img src='images/staff/".$row['imgName'].".jpg'>". "<br>".
"<strong>" . $row['firstName'] . "</strong>" ." ".
"<strong>" . $row['lastName'] . "</strong>" . "<br>" .
"Hire Date: ".$row['hireDate'] ."</td>";
"Major: " .$row['majorAbbrev'] ."</td>"; //Does not display
if($i % $columns == ($columns - 1)){
echo "</tr>";
}
$i++;
}
// release the memory used by the result set
mysqli_free_result($result);
}
// close the database connection
mysqli_close($connection);
?>
</table>
Any ideas/solution will be greatly appreciated!
Because you are not concatenating your php properly. You ended (;) your echo after displaying the $row["lastName"].
You can try these to join the three tables:
SELECT * FROM person
LEFT JOIN personMajors ON person.personID = personMajors.personID
LEFT JOIN validMajors ON personMajors.majorAbbrev = validMajors.majorAbbrev
Or you can define what columns to call in your query:
SELECT person.personID,
person.lastName,
person.firstName,
person.hireDate,
person.imgName,
validMajors.majorAbbrev,
validMajors.majorDesc
FROM person
LEFT JOIN personMajors ON person.personID = personMajors.personID
LEFT JOIN validMajors ON personMajors.majorAbbrev = validMajors.majorAbbrev
Then you can call the results with the way you are calling it right now (cleaner version):
echo '<td class="staffImage badgeText frameImage displayInLine">
<img src="images/staff/'.$row["imgName"].'.jpg"><br>
<strong>'.$row["firstName"].'</strong>
<strong>'.$row["lastName"].'</strong><br>
Hire Date: '.$row["hireDate"].'
Major: '.$row["majorAbbrev"].'
</td>';
(Second try): Is the person to major relationship one to one or one to many?
OK, this SELECT Statement should work:
SELECT person.*, validMajors.* FROM person AS p, validMajors AS vm, personMajors AS pm WHERE p.personID = pm.personID AND pm.majorAbbrev = vm.majorAbbrev
Related
I'm trying to create an HTML table using PHP and MySQL. I have 2 MySQL tables, named coffees, and suppliers, seen here:
Coffees:
Suppliers:
In my HTML table, I wish to display the coffee name, supplier name, and total.
My problem however, is that in order to display the supplier name, I must use the SUP_ID field from the coffees table to reference SUP_NAME from the suppliers table.
My final output aims to be something along the lines of this:
My code is the following:
<?php
$connection_var = new mysqli("server", "user", "pw", "db");
if (mysqli_connect_errno()) {
printf("Connection failed: s\n", mysqli_connect_errno());
exit();
}
$coffees = "SELECT * from coffees";
$suppliers = "SELECT * from suppliers";
$coffeesArr = mysqli_fetch_array($coffees);
$supplierArr = mysqli_fetch_array($suppliers)
echo("<br>");
echo("<table border='1'>");
echo("<tr><td>COF_NAME</td><td>SUPPLIER NAME</td><td>TOTAL</td></tr>");
foreach($resultArr as $row) {
echo("<tr>");
echo("<td>" . $row['COF_NAME'] . "</td><td>" . /* Supplier name (from 2nd table) */ . "</td><td>" . $row['TOTAL'] . "</td><td>");
echo"</tr>");
}
mysqli_close($connection_var);
?>
As seen above, I can easily reference the COF_NAME and TOTAL fields from the first table, however I am at a loss at how to reference the SUP_NAME field from my 2nd MySQL table, as it would require me to use the SUP_ID field from the first table. I would greatly appreciate if someone could guide me on how to achieve this.
A simple INNER JOIN is needed:
select c.cof_name,
s.sup_name,
c.total
from coffees c
inner join suppliers s on c.sup_id=c.sup_id;
Lear more about MySQL
alias
Check MySQL different types of joins:
What is the difference between "INNER JOIN" and "OUTER JOIN"?
https://dev.mysql.com/doc/refman/8.0/en/join.html
you can make an INNER JOIN so it joins both tables
<?php
$connection_var = new mysqli("server", "user", "pass", "db");
if (mysqli_connect_errno()) {
printf("Connection failed: s\n", mysqli_connect_errno());
exit();
}
$sql = "SELECT c.cof_name, s.sup_name, c.total FROM COFFEES c INNER JOIN suppliers s ON c.cof_id=s.sup_id";
$result = mysqli_query($connection_var, $sql) or die(mysqli_error($connection_var));
echo("<br>");
echo("<table border='1'>");
echo("<tr><th>COF_NAME</th><th>SUPPLIER NAME</th><th>TOTAL</th></tr>");;
while($row = mysqli_fetch_array($result ,MYSQLI_ASSOC)) {
echo("<tr>");
echo("<td>" . $row['cof_name'] . "</td><td>" . $row['sup_name'] . "</td><td>" . $row['total'] . "</td>");
echo("</tr>");
}
mysqli_close($connection_var);
?>
Image of the table
For more MySQL documentation about the joins: https://dev.mysql.com/doc/refman/8.0/en/join.html
I am trying to make a members page. For the rank it shows numbers so I made another table that has the rank id (1,2,3 etc) and added a name to it also.
Here is my code.
<?php
$getCoB = mysql_query("SELECT * FROM `members`
WHERE `CoB` = '1' && `user_state` = '1' ORDER BY `id`");
$id = ($getCoB['rank']);
$rankInfo = mysql_query("SELECT * FROM `ranks` WHERE `id` = '".$id."'");?>
<h2 class="title">Council of Balance members</h2>
<style>tr:nth-of-type(odd) { background-color:#F0F0F0;}</style>
<div style='padding:5px;'>
<?php
if(mysql_num_rows($getCoB) == 0)
{
echo "There are no Council of Balance members.";
} else {
echo "<table cellpadding=20 width=100%>";
while($row = mysql_fetch_assoc($getCoB))
{
echo "<tr><td style='background-color:transparent;'><b>". $row['name']
. "</b></td><td>Rank: ".$rankInfo['name']." <br/> Role: ". $row['role']."</td>";
}
echo "</table>";
}
?>
The problem is rankInfo['name'] is not showing up. I tried to do something on this line while($row = mysql_fetch_assoc($getCoB)) and tried to make it something like this while($row = mysql_fetch_assoc($getCoB)) || while($rank = mysql_fetch_assoc($rankInfo) and changed this part <td>Rank: ". $rankInfo['name'] . " to this <td>Rank: ". $rank['name'] . " but I end up with an error. If I leave it like it is, it just shows Rank: without the name I added into my database.
You can combine your two queries into one using an inner join.
<?php
$getCoB = mysql_query("SELECT m.name as member_name, m.role, r.name as rank_name
FROM `members` as m INNER JOIN `ranks` as r ON m.rank = r.id
WHERE `CoB` = '1' && `user_state` = '1' ORDER BY m.id");
?>
Because of how INNER JOIN works, this will only display members who have corresponding records in the ranks table. If there are some members that you want to display that have no rank record, use LEFT JOIN instead.
Then when you echo out the data, be sure to refer to the item you have fetched ($row) each time. In your code, you are referring to $rankInfo['name'], where $rankInfo is not a variable, but a mysql query from which no rows have been fetched.
while($row = mysql_fetch_assoc($getCoB)) {
echo "<tr><td style='background-color:transparent;'><b>". $row['member_name']
. "</b></td><td>Rank: ". $row['rank_name'] . " <br/> Role: " . $row['role'] . "</td>";
}
<?php
//db connection goes here
$arr=array('12:30:00','01:30:01','02:30:01','03:30:01','04:30:01','05:30:01','06:30:01','07:30:01');
$arr1=array('01:30:00','02:30:00','03:30:00','04:30:00','05:30:00','06:30:00','07:30:00','08:30:00');
$cnt=count($arr);
for($i=0;$i<$cnt;$i++){
$sql="SELECT count(*) FROM report WHERE DATE_FORMAT(dt,'%H:%m:%i') BETWEEN $arr[$i] AND $arr1[$i]";
}
//fetching in while and echo
this is my script that i am trying which will generate report counting number of user and number of application from two different table report and report1.
the report will be like
Time count Logged In user Count-Apps
12:30:00-01:30:00
01:30:01-02:30:00
02:30:01 -03:30:00
03:30:01-04:30:00
04:30:01-05:30:00
05:30:01-06:30:00
06:30:01-07:30:00
07:30:01-08:30:00
08:30:01-09:30:00
report table for counting number of user
user datetimeuser(datetime)
a 12:30:00
b 01:30:00
c 01:30:01
d 02:30:00
report1 table for counting number of apps
user datetimeuser(datetime)
a 12:30:00
b 01:30:00
c 01:30:01
d 02:30:00
previously i have done a script which does the work but its slowing the server as my script will be placed in cron job firing in 1 hour interval and fetching the result
previous.php
$time_ranges = array(
array('12:30:00','01:30:00'),
array('01:30:01', '02:30:00'),
array('02:30:01', '03:30:00'),
array('03:30:01', '04:30:00'),
array('04:30:01', '05:30:00'),
array('05:30:01', '06:30:00'),
array('06:30:01', '07:30:00'),
array('07:30:01', '08:30:00'),
array('08:30:01', '09:30:00'),
);
$sql="SELECT sub0.TimeRange, sub0.number, COUNT(*) AS countapps
FROM
(
SELECT
CASE
";
foreach ($time_ranges as $r) {
$sql .= "
WHEN DATE_FORMAT(dt,'%H:%i:%s') BETWEEN '$r[0]' and '$r[1]'
THEN STR_TO_DATE(CONCAT(CURDATE(), ' ', '$r[0]'), '%Y-%m-%d %H:%i:%s') ";
}
$sql .= "
ELSE NULL
END AS StartRange,
CASE ";
foreach ($time_ranges as $r) {
$sql .= "
WHEN DATE_FORMAT(dt,'%H:%i:%s') BETWEEN '$r[0]' and '$r[1]'
THEN STR_TO_DATE(CONCAT(CURDATE(), ' ', '$r[1]'), '%Y-%m-%d %H:%i:%s') ";
}
$sql .= "
ELSE NULL
END AS EndRange,
CASE ";
foreach ($time_ranges as $r) {
$sql .= "
WHEN DATE_FORMAT(dt,'%H:%i:%s') BETWEEN '$r[0]' and '$r[1]'
THEN '$r[0]-$r[1]' ";
}
$sql .= "
ELSE NULL
END AS TimeRange,
COUNT(*) as number
FROM report
WHERE DATE_FORMAT(dt,'%Y:%m:%d')=DATE(CURDATE())
GROUP BY StartRange, EndRange, TimeRange
HAVING TimeRange IS NOT NULL
) sub0
LEFT OUTER JOIN report1
ON report1.dt BETWEEN sub0.StartRange AND sub0.EndRange
GROUP BY sub0.TimeRange, sub0.number";
$query=mysql_query($sql);
echo'<html>
<head>
<title>Count User Info TimeWise</title>
</head>
<h1>Count User</h1>
<table border="3" cellspacing="2">
<tr>
<th>range</th>
<th>count</th>
<th>Apps Count</th>';
while($row = mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>" . $row['TimeRange'] . "</td>";
echo "<td>" . $row['number'] . "</td>";
echo "<td>" . $row['countapps'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "</html>";
?>
i want to make the mysql query shorter and more precise by taking only two array and looping it.but could not really make it.please help.how can i do this taking two array and then counting(array) and for loop it and count statement in mysql
$arr=array('12:30:00','01:30:01','02:30:01','03:30:01','04:30:01','05:30:01','06:30:01','07:30:01');
$arr1=array('01:30:00','02:30:00','03:30:00','04:30:00','05:30:00','06:30:00','07:30:00','08:30:00');
$cnt=count($arr);
for($i=0;$i<$cnt;$i++){
$sql="SELECT count(*) AS test FROM report WHERE DATE_FORMAT(dt,'%H:%m:%i') BETWEEN $arr[$i] AND $arr1[$i]";
Possibly dynamically build up a select to return the times and then join that against you report table:-
$numbers = array();
foreach($arr AS $key=>$value)
{
$numbers[] = "SELECT '".$arr[$key]."' AS StartRange, '".$arr1[$key]."' AS EndRange ";
}
$dates_select = "(".implode(" UNION ",$numbers).") sub0";
$sql="SELECT sub0.StartRange, sub0.EndRange, count(report.dt)
FROM $dates_select
LEFT OUTER JOIN report
ON DATE_FORMAT(report.dt,'%H:%m:%i') BETWEEN sub0.StartRange AND sub0.EndRange
GROUP BY sub0.StartRange, sub0.EndRange";
I have a inner join statment which is working 90% as it is displaying what I need it to display but unfortunately it is not displaying to the right user logged in. It is being displayed to whoever logs into my system. Here is the code:
<?php
$result = mysql_query("SELECT * FROM Agendas INNER JOIN Meetings ON Meetings.secretary WHERE Agendas.approval = 'disapproved' AND secretary = '". $_SESSION['username']."'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'You Have No New Messages';
} else {
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><br/>" .'Title: '. $info['title']." </td>";
echo "<td><br/>" .'Approved: '. $info['approval']. "</td>";
echo "<td><br/>" .'Reason: '. $info['reason']."</td>";
echo "<hr>";
}
}
echo "</tr>";
echo "</table>";
?>
my database tables look like this:
Meetings: meeting_id, title, chairperson, secretary, tof, occurances, action
Agendas: agenda_id, subject, duration, meeting_id, approval, reason.
thanks soo much for any help :)
i think you're doing something wrong in the join clause. how about this:
$result = mysql_query("SELECT * FROM Agendas INNER JOIN Meetings ON Agendas.meeting_id = Meetings.meeting_id WHERE Agendas.approval = 'disapproved' AND secretary = '". $_SESSION['username']."'")
or die(mysql_error());
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
}
}
?>