Mysqli Multi Query Or A better Alternative - php

I have an appointment database and I can successfully print the data. What I want to do now is limit the appointments that are shown to the result from query 1.
I currently get two errors the first one is unexpected query and the other error is Fatal error: Function name must be a string. How would i rewite it so that both queries work? or an alternative better way to get this working
<?php
//MySqli Databse Connection
require "id.php";
require "calendarconnect.php";
//MySqli Select Query 1
$lep = $mysqli->query("SELECT lep FROM appointments WHERE ID = $contactid");
$line = mysqli_fetch_array($query1, MYSQL_ASSOC);
//MySqli Select Query 2
$query = $mysqli->query("SELECT ID, appointment, nature, doctorname, lep FROM appointments WHERE lep = $line ORDER BY appointment");
print '<table cellpadding="10" cellspacing="3" border="1" class="sortable">';
print '<tr><th>Date/Time</th><th>Nature</th><th>Doctor Name</th><th>Actions</th></tr>';
while($row = $query->fetch_assoc()) {
print '<tr>';
print "<td>" . date('m-d-y g:i A', strtotime($row['appointment'])) . "</td>";
print '<td>'.$row["nature"].'</td>';
print '<td>'.$row["doctorname"].'</td>';
print "<td>Edit | ";
print "<a href=\"appointmentdelete.php?id=" . $row['ID'] . "\"onclick=
\"return confirm('Are you sure you want to delete?')\">Delete</a></td>";
print '</tr>';
}
print '</table>';
require "freeclose.php";
?>

Its not necessary to do it with 2 Querys. So you not must transfer the result from Query 1 to the client to put in in the second.
Try this:
SELECT b.ID, b.appointment, b.nature, b.doctorname, b.lep
FROM appointments a
LEFT JOIN appointments b ON b.lep = a.lep
WHERE a.ID = $contactid
ORDER BY b.appointment;

Related

Grabbing info from two different tables, assistance

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>";
}

Show multiple table rows in a table

I have 2 tables called 0_vrs_american and 0_vrs_europe, and I need to display the rows of these tables in a single html table. So I wrote this code:
<?php
$con=mysqli_connect("localhost","aaa","bbb","my_mk7vrlist");
$result = mysqli_query($con,"SELECT 0_vrs_american.*, 0_vrs_europe.* FROM 0_vrs_american, 0_vrs_europe ORDER BY `vrs` DESC LIMIT 0 , 200");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $x . "</td>";
echo "<td>" . $row['playername'] . "</td>";
echo "<td>" . $row['contactable'] . "</td>";
echo "<td>" . $row['vrs'] . "</td>";
echo "</tr>";
$x = $x+1;
}
mysqli_close($con);
?>
I am pretty new with MySQL and so I googled about this topic and I found a syntax like the one you can see above. By the way I have no results in my page because the table is empty.
So: I must display in a HTML table the content of both sql tables, and the rows must be sorted according with the vrs (number that goes from 50000 to 99000). How could I solve my problem?
An alternative to the above is to select all the rows from those two tables as an inner select, and then order by vrs in the returned result set.
SELECT *
FROM
(
SELECT * FROM 0_vrs_american
UNION
SELECT * FROM 0_vrs_europe
) AS a
ORDER BY vrs
at first U need to define $x before the loop
then use the query like this
$result = mysqli_query($con,"SELECT 0_vrs_american.*, 0_vrs_europe.* FROM 0_vrs_american, 0_vrs_europe ORDER BY `vrs` DESC LIMIT 0 , 200") or die (__LINE__." ".mysqli_error($con));
so you will see the error and the line of the query
i just add or die (__LINE__." ".mysqli_error($con))
Separate the 2 queries and their results
merge both results into an array
sort the array as needed
output the array (generate table rows)

Fetch 2 querys at once

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]

Output distinct values in SQL column with PHP

I have a table with two collumns (shortened), NAME and CATEGORY.
I want to output the number of distinct categorys. For an examle: Sport : 5 , Houses : 10.
I use this one:
$test = mysqli_query($con,"SELECT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");
This work then I run the code in SQL Shell, but I have no clue on how to output it in PHP. I have searced Google up and down without any successfull solution.
Any help?
I want to output it in a table format.
EDIT: Here is my full code: (tablename is changed, and $con is removed)
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");
while($row = mysql_fetch_array($test)) {
echo $row['lkategori'] . ":" . $row['count'];
die("test");
}
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");
echo "<table border='1'>";
while($row = mysqli_fetch_array($test)) {
echo "<tr>";
echo "<td>" . $row['lkategori'] . "</td>";
echo "<td>" . $row['count'] . "</td>";
echo "</tr>";
}
echo "</table>";
This will output all the categories and the count returned by the sql statement into a table. Also as a sidenote you should look into PDO.
EDIT: to make sure you do get the distinct values you should use the DISTINCT keyword in your sql statement:
$test = mysqli_query($con,"SELECT DISTINCT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");
use this
while($row = mysqli_fetch_array($test)) {
echo $row['lkategori'] . ":" . $row['count'];
die("test");
}
Thanks

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