Trouble with Queries and JOINS - php

The main page I am using is called the Project Details Page which when you select a project number on the form will query the subform for any records pertaining to that project number and display them in this page named the (TasksSubform).
This page called (TasksSubform) uses a php file called mysqli_connect.php to obtain a database connection and assigns that connection to $dbc in the mysqli_connect.php file.
This page then query’s table 1 named 'CommonTasks', and starts displaying the data row by row in a table on the page using
while($row = $result->fetch_assoc())
Currently one of the columns in the record being displayed is named “AssignedTo” which produces the unique ID number in the Employees table instead of the text value of the employees name associated with the ID number. So, I need to be able to list the records in the CommonTasks Table using Fetch then, when it tries to display the value in the “AssignedTo” column within the Common Tasks Table, it must lookup the ID in the Employees table which equals the same value in the Common Tasks Table, and replace the number value of the Assigned To Field with the text value in the Employees table.
COMMONTASKS
EMPLOYEES
* Add
* AssignedTo
* Attachments
* Cost
* CostInDays
* Description
* DueDate
* EmployeeID
* ID
* PercentComplete
* Priority
* StartDate
* SubmissionDate
* Title * ID
* Address
* BusinessPhone
* City
* Company
* CountryRegion
* EmailAddress
* FaxNumber
* FirstName
* HomePhone
* JobTitle
* LastName
* MobilePhone
* Notes
* StateProvince
* WebPage
* ZIPPostal Code
This is what I have. Yet, all it is producing is a blank in the Assigned To field on the php page.
enter image description here
I am a novice to php and mysql.
This is probably something simple which I am overlooking.
Yet, I have been troubleshooting various methods for the past few days, and just cant seem to figure out what I am doing wrong.
<?php
// Get a connection for the database
require_once('../mysqli_connect.php');
// Create a query for the database
$sql = "SELECT * FROM `CommonTasks`";
$employee = "SELECT ID, LastName, LastName FROM Employees JOIN CommonTasks ON Employees.ID=CommonTasks.AssignedTo";
$emp = "SELECT LastName, FirstName FROM Employees JOIN CommonTasks WHERE Employees.ID = CommonTasks.AssignedTo LIMIT 1";
$emp1 = "SELECT id as LastName, FirstName FROM Employees WHERE ID = CommonTasks.AssignedTo LIMIT 1";
// Get a response from the database by sending the connection
// and the query
$result1 = #mysqli_query($dbc, $sql);
$result2 = #mysqli_query($dbc, $emp);
$result = $dbc->query($sql);
$link = "commntasks-insertdata.php"
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Common Tasks-subform</title>
<meta name="viewport"charset="utf-8" content="width=device-width, initial-scale=1.0">
</head>
<body>
<?php
echo " <table border='1' #6a8fba>
<caption>SUBFORM - Common Tasks</caption>
<tr>
<th>Job Title</th>
<th>Due Date</th>
<th>Start Date</th>
<th>Cost</th>
<th>Priority</th>
<th>Percent Complete</th>
<th>Assigned To</th>
<th>Description</th>
</tr>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><a href= $link > $row[Title] </a></td>";
echo "<td>". $row['DueDate'] . "</td>";
echo "<td>". $row['StartDate'] . "</td> " ;
echo "<td>". $row['Cost'] . "</td>";
echo "<td>". $row['Priority'] . "</td>";
echo "<td>". $row['PercentComplete'] . "</td> " ;
echo "<td>". $row ['SELECT LastName, FirstName FROM Employees JOIN CommonTasks WHERE Employees.ID = $_GET[AssignedTo] LIMIT 1'] . "</td>";
echo "<td>". $row['Description'] . "</td> " ;
echo "</tr>";
}
}
echo "</table>";
?>
</body>

Currently, the results are being produced by this line
$result = $dbc->query($sql);
The following line will not execute a mysql query.
echo "<td>". $row ['SELECT LastName, FirstName FROM Employees JOIN CommonTasks WHERE Employees.ID = $_GET[AssignedTo] LIMIT 1'] . "</td>";
As written, you are trying to find a row value in $result that does not exist. You need to call the second query within the first while loop and pass the value of $_GET[AssignedTo] which is probably $row[AssignedTo]
Something like this
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><a href= $link > $row[Title] </a></td>";
echo "<td>". $row['DueDate'] . "</td>";
echo "<td>". $row['StartDate'] . "</td> " ;
echo "<td>". $row['Cost'] . "</td>";
echo "<td>". $row['Priority'] . "</td>";
echo "<td>". $row['PercentComplete'] . "</td> " ;
$emp = "SELECT LastName, FirstName FROM Employees JOIN CommonTasks WHERE Employees.ID = '$row[AssignedTo]' LIMIT 1";
$result2 = #mysqli_query($dbc, $emp);
$row2 = $result2->fetch_assoc();
echo "<td>". $row2 ['Firstname'] . " ". $row2 ['Lastname'] . "</td>";
echo "<td>". $row['Description'] . "</td> " ;
echo "</tr>";
}

So, Here are my revisions to your example:
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><a href= $link > $row[Title] </a></td>";
echo "<td>". $row['DueDate'] . "</td>";
echo "<td>". $row['StartDate'] . "</td> " ;
echo "<td>". $row['Cost'] . "</td>";
echo "<td>". $row['Priority'] . "</td>";
echo "<td>". $row['PercentComplete'] . "</td> " ;
$emp = "SELECT LastName, FirstName FROM Employees JOIN CommonTasks WHERE Employees.ID = '$row[AssignedTo]'";
$result2 = #mysqli_query($dbc, $emp);
$row2 = $result2->fetch_assoc();
echo "<td>". $row2['LastName']," , ",$row2[FirstName] . "</td>";
echo "<td>". $row['Description'] . "</td> " ;
echo "</tr>";
}
}
echo "</table>";
?>
Which produces this: Results of modified code
Thank you so much for your Help!
Since I am converting an Access Database to mySQL and recreating all of the queries, forms, and reports.... I am sure I will have an overwhelming amount of questions in the near future.
Eric

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

PHP Extracting MYSQL Value Issue

I have 2 tables: users and transactions
In users I have: userid, name, email
And in transactions I have: id, idsender, idreceiver
I want to make a log-table showing all the transactions and I want them to be displayed like: Transaction ID - SENDER'S NAME - RECEIVER'S NAME
I tried like this but it doesn't seem to work, at "Receiver" it doesn't show anything .. :
echo "<table>";
echo "<tr>";
echo "<th>Transaction ID</th>";
echo "<th>Sender</th>";
echo "<th>Receiver</th>";
echo "</tr>";
$resultuser = mysqli_query($conn, "SELECT * FROM users");
$rowuser=mysqli_fetch_array($resultuser);
$resulttrans = mysqli_query($conn, "SELECT * FROM transactions");
$rowtrans=mysqli_fetch_array($resulttrans);
$ress=mysqli_query($conn, "SELECT * FROM transactions");
while($row=mysqli_fetch_array($ress)){
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>"." same as receiver"."</td>";
$receiver=mysqli_query($conn, "SELECT name FROM users WHERE userid='" . $rowtrans['idreceiver'] . "'");
$receivername = mysqli_fetch_array($receiver);
echo "<td>". $receivername ."</td>";
echo "</tr>";
}
Don't use two queries. Join the two tables in one query:
$ress = mysqli_query("SELECT t.id, u1.name AS sendername, u2.name AS receivername
FROM transactions AS t
JOIN users AS u1 ON u1.userid = t.idsender
JOIN users AS u2 ON u2.userid = t.idreceiver");
while ($row = mysqli_fetch_assoc($ress)) {
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>" . $row['sendername'] ."</td>";
echo "<td>" . $row['receivername'] . "</td>";
echo "</tr>";
}
You are echoing from fetched array in $receivername = mysqli_fetch_array($receiver);
you should do echo "<td>". $receivername['name'] ."</td>";
Note:
Fetched array from mysqli_fetch_array() can be echoed using indexes by number $receivername[0] or by string $receivername['name'], that is where you are missing here.

It is expected to get all the row from mysql but getting first one

I am trying to get all values shown in a table from mysql but getting one .
I want to get the rows of the mysql table at in the last table mentioned in the code
////////Here is a desc of no use --- blah for just posting this question / as i am getting an error msg for giving more details information about this question /////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Here is the code:
$sql = 'SELECT
item_added
FROM
products_added
ORDER BY id';
$results = mysqli_query($conn, $sql);
if(mysqli_num_rows($results) < 1){
echo "No items";
}else{
$new_sql = 'SELECT
item_added,
quantity,
amount,
sum(amount) as items_total
FROM
products_added
where `username` = "'.mysqli_real_escape_string($conn, $_SERVER["REMOTE_ADDR"]).'"
ORDER BY id';
$resu = mysqli_query($conn, $new_sql);
}
?>
<table>
<thead>
<tr>
<td>Item</td>
<td>Qyt</td>
<td>Price</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($resu)){
echo "<tr>";
echo "<td>" . $row['item_added'] . "</td>";
echo "<td>" . $row['quantity'] . "</td>";
echo "<td>" . $row['amount'] . "</td>";
echo "<td><a class=\"remove-from-cart\" href=\"\"><i class=\"fa fa-times\"></i></a></td>";
echo "</tr>";
}
?>
</tbody>
</table>
It looks like its because you're using an aggregate function SUM() without a GROUP BY. In the $new_sql query, try adding "GROUP BY item_added" right before "ORDER BY id".

In php-sql, I want to re-search within the first search result table.

In php-sql, I want to re-search within the first search result table.
This is the captured picture executed by my php-mysql code.
I want to use the button "Search below result" to gain the detailed result from the first search result table.
Then, "Search in below result" form action is another php code which has to hold the first result, and have the sql code that is as like
select uid, contents from datatable where contents like '%re-search word%'
and uid in (select uid from datatable where contents like '%first-search word%')
but I have a question and don't know how uid works.
How can i produce uid?
What is uid?
Where is uid information?
How can i use uid as like above the sql code?
Below is my first-search php code
<?php
$q = $_GET['q'];
$con = mysqli_connect('localhost','root','autoset','my_db');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM persons WHERE FirstName = '".$q."' ;
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
and How can i re-use the first-search word variable in the another php code?
Another php code is designed as like below
<?php
$q = $_GET['q'];
$p = $_GET['LastName'];
$con = mysqli_connect('localhost','root','autoset','my_db');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT uid, * FROM persons WHERE LastName = '".$p."' and select **uid** in (select uid from datatable where FirstName='".$q."') ;
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Above code, I think uid is important to recall the first search result.
But How can i get uid and set uid in php code or html code??
Please help me!
Q1: How can i produce uid?
A1: It should be a column in your table you created in mysql. Your create table statement would have looked something like:
CREATE TABLE persons (
uid INT(10) NOT NULL AUTO_INCREMENT,
FirstName CHAR(30) NOT NULL,
LastName CHAR(30) NOT NULL,
Age INT(3),
Hometown CHAR(40),
Job CHAR(40),
PRIMARY KEY (uid)
);
Q2: How can i produce uid?
A2: You won't have to. The AUTO_INCREMENT field will create itself for you when you insert an entry. doco for auto-increment here
Q3: What is uid?
A3: It likely stands for "user identification" which is a number unique to a user. No other user may have that number in their "uid" field.
Q4: Where is uid information?
A4: It's in your table
Q5: How can i use uid as like above the sql code?
A5: Providing that you created it in your "create table" statement like I mentioned in A1 then you should be able to access uid with the query you presented above but should look more like:
SELECT uid FROM persons WHERE LastName = '".$p."' AND FirstName ='".$q."';
OR if you want to run a test query with a name you know is in your database then something like below:
SELECT uid FROM persons WHERE LastName = 'timmy' AND FirstName ='tom';

sorting row data in table PHP?

i have a table being echo'd from a single query to a table in our database and i get it to echo out the following table;
http://www.skulldogs.com/dev/testview.php
i want it to sort the "yellow" rows under the correct green rows where the "mainToon" name matches for example:
high voltege
--REAL MCCOY
--Cpt Hook
riazall
-- Valeside
my code to echo the above page is;
<?php
$result = mysql_query("SELECT * FROM `members`");
echo "<table border='1'>
<tr>
<th>Character ID</th>
<th>Name</th>
<th>MainToon</th>
<th>toonCategory</th>
</tr>";
while ($row = mysql_fetch_array($result)) {
$characterID = $row['characterID'];
$name = $row['name'];
$startDateTime = $row['startDateTime'];
$logonDateTime = $row['logonDateTime'];
$logoffDateTime = $row['logoffDateTime'];
$location = $row['location'];
$role = $row['role'];
$vouchedBy = $row['vouchedBy'];
$positionHeld = $row['positionHeld'];
$remarks = $row['remarks'];
$afkNotice = $row['afkNotice'];
$toonCategory = $row['toonCategory'];
$mainToon = $row['mainToon'];
$watch = $row['watch'];
if ($toonCategory == 'Main Toon') {
echo "<tr bgcolor='#00FF00'>"; }
else {
echo "<tr bgcolor='#FFFF00'>"; }
echo "<td>" . $characterID . "</td>";
echo "<td>" . $name . "</td>";
echo "<td>" . $mainToon . "</td>";
echo "<td>" . $toonCategory . "</td>";
echo "</tr>";
}
echo "</table>";
?>
at the moment i am not echo the other data until i can figure out how to display this table accordingly. can it be done this way?
this is how i want to display the table;
http://www.skulldogs.com/dev/mockup.php
Add an ORDER BY clause to your sql:
SELECT * FROM `members` ORDER BY toonCategory;
If there are other values above and below "Main Toon", You can order by a boolean:
SELECT * FROM `members` ORDER BY toonCategory = 'Main Toon' DESC;
EDIT:
Now I see what you are after as you have put up the example, try:
SELECT * FROM `members` ORDER BY CONCAT(MainToon, Name);
if the blank spaces are empty strings or:
SELECT * FROM `members` ORDER BY COALESCE(MainToon, Name) DESC, Name;
if the blank rows are null.
Try SELECT * FROM members ORDER BY toonCategory;

Categories