retrieving data from two databases - php

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.

Related

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

Display name instead ID from another table

I'm facing a problem to display a name on a table, only the id is displayed I have tried some inner join queries without luck i got 2 tables
Table 1 = empresas
Here is where all the data lives:
the number 9 in u_tip corresponds to the ID of the data that is in tipoempresas table
Table 2 = tipoempresas
I want to display the name of the type not the ID
I'm using this code to display the data in a html table
$result = mysqli_query($conn,"SELECT * FROM empresas");
$i = 0;
while($row = $result->fetch_assoc())
{
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
You are already there you just need to use join statement and specify the column you want to display
$result = mysqli_query($conn,"SELECT * FROM empresas AS e INNER JOIN tipoempresas AS t ON t.id = e.u_tip");
$i = 0;
while($row = $result->fetch_assoc())
{
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value['Nombre'] . "</td>"; //SPECIFY THE COLUMN YOU WANT TO DISPLAY
}
echo "</tr>";

Mysql, select together, not separately

In mysql I want to display matched information with values... But the code I use select information separately and I get a bad result. What I want is to wrap the "select" functions together so they both look for specific information in mysql database.
Here's the code I use:
$name = explode(',',$name); //splits search
$query = "SELECT * FROM lucky WHERE name LIKE '%" . implode("%' AND name LIKE '%", $name) . "%'";
$sname = explode(',',$sname); //splits search
$query = "SELECT * FROM lucky WHERE sname LIKE '%" . implode("%' AND sname LIKE '%", $sname) . "%'";
$result = $mysqli->query($query);
while($row = $result->fetch_assoc()) {
echo "<table id='box'>";
echo "<tr;>";
echo "<td id='text''>Name:</td><td id='haha'>" . $row['name']. "</td>";
echo "<td id='text'>Second Name:</td><td id='haha'>" . $row['sname'] . "</td>";
echo "</tr;>";
echo "</table>";
} else { echo "No mathed information" ; }
Thanks in advance :)
UPADATE
Thanks to Spencer for his help!!!
Here's the code that I use now. Please use this to select matched information from the database!!!
$query = SELECT *
FROM lucky
WHERE name LIKE '$name'
AND sname LIKE '$sname'
$result = $mysqli->query($query);
while($row = $result->fetch_assoc()) {
echo "<table id='box'>";
echo "<tr;>";
echo "<td id='text''>Name:</td><td id='haha'>" . $row['name']. "</td>";
echo "<td id='text'>Second Name:</td><td id='haha'>" . $row['sname'] . "</td>";
echo "</tr;>";
echo "</table>";
} else { echo "No mathed information" ; }
If your $sname string contains the value "jack,jill", then the query would only return rows that have a name column value that contains both of those strings, for example: 'jack and jill' and 'jillojellojacko' would match. But the query will not return rows where the name column contains 'jack' but doesn't contain 'jill'.
If your intent is to search for rows that have either of the values matching, for example
$name = 'fee,fi,fo'
$sname = 'fum'
That is, any rows where name column contains either 'fee', or 'fi', or 'fo', or sname column contains 'fum', you could use a query of the form:
SELECT t.*
FROM lucky t
WHERE t.name LIKE '%fee%'
OR t.name LIKE '%fi%'
OR t.name LIKE '%fo%'
OR t.sname LIKE '%fum%'
If you replace all those ORs with ANDs, then a row will need to satisfy all of those predicates to be returned. If you want a combination of AND and OR, then use parens to specify the order of precedence...

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]

PHP while-loop not working with mysql_result

I have a Physician Query:
// Primary Physician Query
$qPhysician = mysql_query("SELECT * FROM physicians ORDER BY lastName ASC, firstName ASC");
$rowPhysician = mysql_fetch_array($qPhysician);
// State Query for Physician
$idStatePhysician = $rowPhysician['idstate'];
$qStatePhysician = mysql_query("SELECT * FROM states WHERE idstate=$idStatePhysician");
$rowStatePhysician = mysql_fetch_array($qStatePhysician);
// City Query for Physician
$idCityPhysician = $rowPhysician['idcity'];
$qCityPhysician = mysql_query("SELECT * FROM cities WHERE idcities=$idCityPhysician");
$rowCityPhysician = mysql_fetch_array($qCityPhysician);
I have a while loop to display all physicians row to a table:
$num = mysql_num_rows($qPhysician);
$i=0;
while($i < $num)
{
$idphysicians = $rowPhysician['idphysicians'];
if ($i % 2 == 0){
echo "<tr class='even' onclick=\"DoNav('physicianUpdate.php?idphysicians=$idphysicians');\">";
}
else{
echo "<tr class='odd' onclick=\"DoNav('physicianUpdate.php?idphysicians=$idphysicians');\">";
}
echo "<td>" . mysql_result($qPhysician,$i,"lastName") . "</td>";
echo "<td>" . mysql_result($qPhysician,$i,"firstName") . "</td>";
echo "<td>";
if(isset($rowPhysician['idcity'])){echo mysql_result($qCityPhysician,$i,"name");} else{}
echo "</td>";
$i++;
}
My problem is: I have 3 rows of data from my physicians table. Each has a value for 'idcity' reflecting the idnumber from my City table. However, the 1st row of Data displays the idcity=Name properly, but the 2nd and 3rd row gave an error:
Warning: mysql_result() [function.mysql-result]: Unable to jump to row 1 on MySQL result index 7 in C:\wamp\www\iPOC\physicians.php on line 55
Also, if I have a blank value for idcity on one of the row, it also generates an error.
Please help! Thanks in advance!
The problem is that you're using mysql_result() with a one-way result. The correct fix is to use one of the mysql_fetch_*() functions instead, checking the returned value in your while loop.
while($row = mysql_fetch_array($qPhysician)) {
...
}
Something like this would probably work better:
$qCityPhysician = mysql_query("SELECT * FROM cities WHERE idcities=$idCityPhysician");
$qCityPhysicians = array();
while($row = mysql_fetch_array($qCityPhysician)) {
$qCityPhysicians[$row['idcity']] = $row['name'];
}
$qPhysician = mysql_query("SELECT * FROM physicians ORDER BY lastName ASC, firstName ASC");
$i=0;
while($row = mysql_fetch_array($qPhysician)) {
if ($i % 2 == 0) {
echo "<tr>";
echo "<td>" . $row['lastName'] . "</td>";
echo "<td>" . $row['firstName'] . "</td>";
echo "<td>";
if(isset($row['idcity'])) {
echo $qCityPhysicians[$row['idcity']];
}
echo "</td>";
$i++;
}
}

Categories