PHP and Multiple DB Selects - php

I've got two tables from which I need to extract information, but the data from the second table depends on the information I get from the first one. Is there an easy way to handle this?
<?php
mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('stadium') or die(mysql_error());
$result = mysql_query("SELECT * FROM events");
$result2 = mysql_query("SELECT name FROM competitions WHERE id='$row[competition_id]' ");
while($row = mysql_fetch_array($result)) {
echo "<tr id=\"" . $row['id'] . "\"> \n<td>" . $row['name'] . "</td>";
echo "<td>" . $row['competition_id'] . "</td>";
echo "<td>" . $row['date'] . "</td></tr>";
}
?>

Use a JOIN.
SELECT e.*, c.name as competition_name FROM events e LEFT JOIN competitions c on c.id = e.competition_id

Related

How to use a selection to generate an sql query

I need to use the selection from and HTML select element as one of the variables in my sql query. Meaning if the user selects "Iphone" from the list, I want to query to be something like select * where name = Iphone.
I do not know how to go about this, thank you.
This code creates the select based on the query:
<option disabled selected value> -- Select a forum -- </option>
<?php
$con = mysqli_connect("host","user","pass","db");
if (!$con) {
die('Connection failed: ' . mysqli_connect_error() . '<br>');
}
$productName='SELECT p.name
FROM product as p
JOIN ownedproducts as o on o.productID = p.productID
WHERE usersID =2;';
$result=mysqli_query($con, $productName);
while ($row = mysqli_fetch_assoc($result)) {
unset($id);
$id = $row['name'];
echo '<option value="'.$id.'">'.$id.'</option>';
}
</select>
I would like to take what the user selects, including multiple selections, and build a table based on that something like this where the AND p.name = selected is replaced with what would actually work in this case. I think javascript is the way to go but I do not know enough.
<?php
$query1 = $db->query('SELECT p.productID, p.name, p.company, o.prodtype AS Type
FROM ownedproducts AS o
JOIN product as p ON p.productID = o.productID
WHERE o.usersID = 2
AND p.name = selected');
while ($row = $query1->fetch())
{
if . $row['name'] . = selected:
echo "<tr id=" . $row['productID'] . ">";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['Type'] . "</td>";
echo "</tr>";
}
?>
Edited for more detail.
Thanks in advance
Though, I am not sure what are you asking for but select statement for exact match will be like below=>
select * from tablename where name='Iphone';
or if you want partial match then you can use wildcard(%) and like operator given below =>
select * from tablename where name like '%Iphone%';

Trying to join different table from different database in the localhost, Used MYSQL

Explanations:
First of all im new in the database field, i got system from my boss, my boss ask me to create dashboard based on the data from database, but some data need to join other table in different database. In my case i need to fetch data at column score from table rank in 4 different database which is "virtualexam, virtualexam1, virtualexam2, virtualexam3,"
. I had try and search but i cant display the data into the table, your advice and recommendation really appreciate it.. Thank you for you kindness
Error picture
click here
Database Table Picture *Dummy data
db.virtualexam
db.virtualexam1
db.virtualexam2
db,virtualexam3
my query
<?php
$sql = "SELECT virtualexam.rank.id, virtualexam.rank.username,
virtualexam.rank.score AS score, virtualexam1.rank.score AS 'score1', virtualexam2.rank.score AS 'score2', virtualexam3.rank.score AS 'score3'
SUM(virtualexam.rank.score + virtualexam1.rank.score + virtualexam2.rank.score + virtualexam3.rank.score ) AS 'total'
FROM virtualexam.rank
JOIN virtualexam1.rank ON virtualexam.rank.username = virtualexam1.rank.username,
JOIN virtualexam2.rank ON virtualexam1.rank.username = virtualexam2.rank.username,
JOIN virtualexam3.rank ON virtualexam2.rank.username = virtualexam3.rank.username
GROUP BY id ";
$result = $conn->query($sql);
?>
display in the table
<tbody>
<?php
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['score'] . "</td>";
echo "<td>" . $row['score1'] . "</td>";
echo "<td>" . $row['score2'] . "</td>";
echo "<td>" . $row['score3'] . "</td>";
echo "<td>" . $row['total'] . "</td>";
echo "</tr>";
}
?>
</tbody>
$sql = "SELECT virtualexam.rank.id, virtualexam.rank.username,
virtualexam.rank.score AS score, virtualexam1.rank.score AS 'score1', virtualexam2.rank.score AS 'score2', virtualexam3.rank.score AS 'score3',
SUM(virtualexam.rank.score + virtualexam1.rank.score + virtualexam2.rank.score + virtualexam3.rank.score ) AS 'total'
FROM virtualexam.rank
JOIN virtualexam1.rank ON (virtualexam.rank.username = virtualexam1.rank.username)
JOIN virtualexam2.rank ON (virtualexam2.rank.username = virtualexam1.rank.username)
JOIN virtualexam3.rank ON (virtualexam3.rank.username = virtualexam2.rank.username)
GROUP BY virtualexam.rank.username";

How do i loop through but replace missing data with blanks in table

I am trying to display a table to show all the subjects the first student takes, then all the progress grades the student has made in that subject.
However, a student may not have a grade in a certain column so i need to place a blank or 'no grade' in place of it.
Instead i get them stacked side by side...
As you can see below '7(Pc3)' in English should be in the 'PC3' column and 'PC2' should say no grade or blank.... If possible -
Thanks
I have the loop working to fetch the students, plus the loop working to fetch all the subjects for that student.
And can display all the grades - but they don't line up with the right column
while ($res = $result->fetch_assoc()) {
echo "<tr><td>" . $res['subname'] . "</td>";
$result2 = mysqli_query($mysqli, "SELECT *
FROM grades
JOIN gradesets ON grades.gradeset_id = gradesets.id
WHERE grades.student_id = {$row['id']}
AND grades.subject_id = {$res['id']}
ORDER BY grades.gradeset_id ") or die($mysqli->error);
while ($res2 = $result2->fetch_assoc()) {
echo "<td>" . $res2['grade'] . "</td>";
//echo "<td>" . $res2['gradeset_id'] . "</td>";
//print_r($res2);
$resset = $res2['gradeset'];
$resset2 = substr($resset, -1);
//print_r($resset);
//print_r($resset2);
}
}
So i can echo out the right grades, but need to test they match up in the right columns... Here is the full code if needed...
$student = $mysqli->query("SELECT * FROM student");
echo "<center>";
echo "<h2>Data Wall</h2>";
echo "<h3>PHP</h3>";
echo "<hr/>";
while ($row = $student->fetch_assoc()) {
echo "<table border='1'>
<tr>
<th>ID</th>
<th>STUDENT</th>
<th>HOUSE</th>
</tr><br>";
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['stuname'] . "</td>";
echo "<td>" . $row['house'] . "</td>";
echo "</tr><br><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>";
echo "<tr><th>SUBJECTS</th><th>PC1</th><th>PC2</th><th>PC3</th><th>PC4</th></tr>";
$result = mysqli_query($mysqli, "SELECT subjects.id,subjects.subname
FROM student
JOIN grades ON student.id = grades.student_id
JOIN subjects ON subjects.id = grades.subject_id
WHERE student.id = {$row['id']}
GROUP BY subjects.subname ORDER BY subjects.id ") or die($mysqli->error);
while ($res = $result->fetch_assoc()) {
echo "<tr><td>" . $res['subname'] . "</td>";
$result2 = mysqli_query($mysqli, "SELECT *
FROM grades
JOIN gradesets ON grades.gradeset_id = gradesets.id
WHERE grades.student_id = {$row['id']}
AND grades.subject_id = {$res['id']}
ORDER BY grades.gradeset_id ") or die($mysqli->error);
while ($res2 = $result2->fetch_assoc()) {
echo "<td>" . $res2['grade'] . "</td>";
//echo "<td>" . $res2['gradeset_id'] . "</td>";
//print_r($res2);
$resset = $res2['gradeset'];
$resset2 = substr($resset, -1);
//print_r($resset);
//print_r($resset2);
}
}
}
echo "</tr>";
echo "</table>";
echo "</center>";
$mysqli->close();
?>
Since PHP 5.3 you can use Elvis operator - ?:
And since PHP 7 you are able to use Null Coalescing Operator - ??
Either of these you can use to display some other information if you row is empty. For example (PHP 7+):
echo "<td>" . ($res2['grade'] ?? 'No grade') . "</td>";
Would result to either a grade, or No grade text if string is empty or false.
Hope this helps!
In your inner query, you're doing an INNER JOIN, which selects only those rows that have a match in the gradeset table. It looks like you want a LEFT OUTER JOIN, so that you get null placeholders where there is no match:
SELECT *
FROM grades
LEFT JOIN gradesets ON grades.gradeset_id = gradesets.id
WHERE grades.student_id = {$row['id']}
AND grades.subject_id = {$res['id']}
ORDER BY grades.gradeset_id
This way, in your query result, instead of getting:
4 (PC1)
7 (PC3)
6 (PC4)
You'll get:
4 (PC1)
null
7 (PC3)
6 (PC4)
You could build an array of empty grades and then replace them with any data from the query. Like so:
$grades = [1 => '', 2 => '', 3 => '', 4 => ''];
while ($res2 = $result2->fetch_assoc()) {
$grades[$res2['gradeset']] = $res2['grade'];
}
foreach ($grades as $grade) {
echo "<td>" . $grade . "</td>";
}

getting a result of a table Mysqli left join

So what i want is the following. I have 3 tables: first i will explain in english what i want for final result:
let me explain all in english:
table 1 is REGISTERED_MEMBERS
table 2 is OPEN CLASSES
table 3 i want who appplied and to which class they applied and show that in a table when date is selected from a dropdown list!
This is how it should show at the end:
table = razpisani_tecaji with (ID_TECAJA, DATE, STATUS, ST_ODPRTIH_MEST)
table = registrirani_clani wtih (ID_TECAJNIKA,IME,PRIIMEK, EMAIL)
table = prijave_na_tecaj with (ID_TECAJNIKA, ID_TECAJA, PLACILO)
now in HTML i have a dropdown list populated with dates (this works ok) from table 1.
<form>
<select name="dates" onchange="showUser(this.value)">
<option value="" selected="selected">Izberi datum za pregled</option>;
<?php
$con = mysqli_connect('localhost','root','','viverius_education');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = mysqli_query($con, "SELECT ID_TECAJA, DATUM FROM razpisani_tecaji");
while ($row = $sql->fetch_assoc()){
echo "<option value='" . $row['ID_TECAJA'] . "'>" . $row['DATUM'] . "</option>";
}
?>
Here a ID is saved to a variable q which is then send to php via JS. This all works. Now what i would like is for user to select a date and get a results from 3. table only to show IME from linked to ID_TECAJNIKA and PLACILO linked to ID_TECAJNIKA.
THis is what i have in PHP so far:
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','viverius_education');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT razpisani_tecaji.ID_TECAJA, registrirani_clani._ID_TECAJNIKA FROM prijave_na_tecaj
LEFT JOIN razpisani_tecaji ON prijave_na_tecaj.ID_TECAJA = razpisani_tecaji.ID_TECAJA
LEFT JOIN registrirani_clani ON prijave_na_tecaj.ID_TECAJNIKA = registrirani_clani.ID_TECAJNIKA";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Ime</th>
<th>Placilo</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['ID_TECAJNIKA'] . "</td>";
echo "<td>" . $row['PLACILO'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
$sql="select registrirani_clani., prijave_na_tecaj.,razpisani_tecaji.*
from registrirani_clani
left join prijave_na_tecaj on registrirani_clani.ID_TECAJNIKA = prijave_na_tecaj.ID_TECAJNIKA
left join razpisani_tecaji ON razpisani_tecaji.ID_TECAJA = prijave_na_tecaj.ID_TECAJA
where razpisani_tecaji.ID_TECAJA = '".$q."'";

php mysql select from columns from 2 tables Join

I have two tables.
visitors_details, with id,scanner_id,time columns
and visitors_info with scanner_id, name,surname columns
I want to get back
id,name,surname,time in a table
i have written this but is not working
$result = mysql_query("SELECT visitors_details.id AS id,
visitors_info.name AS name, visitors_info.surname AS surname, visitors_details.time
AS time FROM visitors_details AS d LEFT JOIN visitors_info AS i ON
d.scanner_id=i.scanner_id ");
echo "<table border='1'>
<tr>
<th>id</th>
<th>name</th>
<th>surname</th>
<th>Time</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['surname'] . "</td>";
echo "<td>" . $row['time'] . "</td>";
echo "</tr>";
}
echo "</table>";
any ideas??
Its better to enable some debugging for your code like this:
<?php
error_reporting(E_ALL);
$sql = "
SELECT d.id AS id, i.name AS name, i.surname AS surname, d.time AS time
FROM visitors_details AS d
LEFT JOIN visitors_info AS i ON d.scanner_id=i.scanner_id
";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
try this query
$result = mysql_query("SELECT d.id , i.name , i.surname , d.time
FROM visitors_details AS d LEFT JOIN visitors_info AS i
ON d.scanner_id=i.scanner_id ");
Add this to catch errors. saves a lot of time:
if(!$result) {
echo mysql_error();
}

Categories