No Data found Query failed in mysql - php

I have to fetch data from 3 tables that is (players, tournaments,entries, and groups) and show that data on the web page but I am not getting any of the data on the table when I use join it shows nothing while I used just a single select * from entries to get the fees data but not getting the other data when i write query using join :
i want to show the below data to the output :
Output that i want to show on page
<?php
include_once('assets/config.php');
include_once('functions.php');
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve data from the database
$sql = "SELECT tournaments.tour_name, entries.fees, players.f_name, groups.group_name
FROM entries
JOIN tournaments ON entries.tour_id = tournaments.tour_id
JOIN players ON entries.player_id = players.player_id
JOIN groups ON entries.group_id = groups.group_id;
";
$result = mysqli_query( $conn, $sql )or die( mysqli_error( $conn ) );
// Create the HTML table with border and styling
echo "<table style='border-collapse: collapse; width: 100%;'>";
echo "<thead style='background-color: #ddd;'><tr><th style='padding: 8px; border: 1px solid #ddd;'>Player</th><th style='padding: 8px; border: 1px solid #ddd;'>Tournaments</th><th style='padding: 8px; border: 1px solid #ddd;'>Group</th><th style='padding: 8px; border: 1px solid #ddd;'>Fees</th></tr></thead>";
echo "<tbody>";
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td style='padding: 8px; border: 1px solid #ddd;'>" . $row["f_name"] . "</td>";
echo "<td style='padding: 8px; border: 1px solid #ddd;'>" . $row["tour_name"] . "</td>";
echo "<td style='padding: 8px; border: 1px solid #ddd;'>" . $row["group_name"] . "</td>";
echo "<td style='padding: 8px; border: 1px solid #ddd;'>" . $row["fees"]. "</td>";
echo "</tr>";
}
} else {
echo "<tr><td colspan='4' style='padding: 8px; border: 1px solid #ddd;'>No data found.</td></tr>";
printf("Query failed: %s\n", $conn->error);
}
echo "</tbody></table>";
// Close the database connection
$conn->close();
?>
Current output
How can i query it perfectly show the ouput

SELECT entries.id, players.f_name AS Player, tournaments.tour_name AS Tournoment, groups.group_name AS Groups, entries.fees
FROM entries
INNER JOIN players ON entries.player_id = players.id
INNER JOIN tournaments ON entries.tournament_id = tournaments.id
INNER JOIN groups ON entries.group_id = groups.id;
This query selects the id and fees columns from the entries table, the f_name column from the players table, the tour_name column from the tournaments table, and the group_name column from the groups table. It then performs an inner join on each table to join the relevant rows.
Here is some example data that you can use to test the query:
-- Players table
id | f_name
----|-------
1 | John
2 | Jane
-- Tournaments table
id | tour_name
----|----------
1 | Tournament A
2 | Tournament B
-- Groups table
id | group_name
----|-----------
1 | Group A
2 | Group B
-- Entries table
id | player_id | tournament_id | group_id | fees
----|-----------|--------------|---------|-----
1 | 1 | 1 | 1 | 100
2 | 2 | 2 | 2 | 150
When you run the query with this data, the result should look like this:
id | Player | Tournoment | Groups | fees
---|--------|--------------|--------|-----
1 | John | Tournament A | Group A | 100
2 | Jane | Tournament B | Group B | 150
You can then use this result in your application to display the relevant data to the user.
i can help you better if you define your database structure, and give me feedback of this answer.

Related

How to listout the item list for same order (in food order) and show in table using php and mysql? [duplicate]

I have written code in PHP (listed below,) but face a small problem...
<html>
<head>
<title> trans </title>
<body>
<style>
table, th, td {
border: 1px solid black;
width: 700px;
margin: auto;
}
</style>
<?php
$con = mysqli_connect('localhost', 'root', '');
if(!$con)
{
die("not ok");
}
mysqli_select_db($con,"uoh");
$q1 = "SELECT * FROM student_record INNER JOIN degree_plan ON
student_record.course_number = degree_plan.course_number
INNER JOIN courses ON student_record.course_number =
courses.course_number where student_record.id = 201102887 AND degree_plan.major='COE'";
$result = mysqli_query($con , $q1 ) ;
if($result){
echo "<table>";
echo "<tr>";
echo "<th>courses</th>";
echo "<th>terms</th>";
echo "<th>grades</th>";
echo "<th>CRD</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row["code"]. "</td>";
echo "<td>" . $row["term_no"]. "</td>";
echo "<td>" . $row["grade"]. "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
</body>
</html>
When I run the code I see the following output:
---------------------------------------
| courses | terms | grades |
---------------------------------------
| CHEM 101 | 1 | A |
---------------------------------------
| ENGL 101 | 1 | C+ |
---------------------------------------
| PE 101 | 1 | B |
---------------------------------------
| PHYS 101 | 1 | F |
---------------------------------------
| ENGL 102 | 2 | B+ |
---------------------------------------
| PE 101 | 2 | B |
---------------------------------------
| PHYS 102 | 2 | D+ |
---------------------------------------
| MATH 201 | 3 | A |
---------------------------------------
| COE 200 | 3 | B |
---------------------------------------
But I do not want it like that. I want the term cells to become one, like this:
---------------------------------------
| courses | term | grade |
---------------------------------------
| CHEM 101 1 A |
| ENGL 101 C+ |
| PE 101 B |
| PHYS 101 F |
---------------------------------------
| ENGL 102 2 B+ |
| PE 101 B |
| PHYS 102 D+ |
---------------------------------------
| MATH 201 3 A |
| COE 200 B |
---------------------------------------
or in any other way that does not let term repeat, by which I mean: group the courses that have the same term together.
try this code,
$data = array();
while($row = mysqli_fetch_array($result))
{
$data[$row["term_no"]][] = array(
'code' => $row["code"],
'grade' => $row["grade"]
);
}
echo '<table width="200" border="1">';
echo "<tr>";
echo "<th>courses</th>";
echo "<th>terms</th>";
echo "<th>grades</th>";
echo "</tr>";
foreach($data as $term=>$otherrow) {
$count = 0;
foreach ($otherrow as $data) {
if($count == 0) {
echo "<tr>";
echo "<td>" . $data["code"]. "</td>";
echo '<td rowspan="'.count($otherrow).'">' . $term. '</td>';
echo "<td>" . $data["grade"]. "</td>";
echo "</tr>";
}else {
echo "<tr>";
echo "<td>" . $data["code"]. "</td>";
echo "<td>" . $data["grade"]. "</td>";
echo "</tr>";
}
$count++;
}
}
echo "</table>";

Fetch data from two SQL tables with INNER JOIN, display HTML table

I am trying to display a table which will print out a list of themes I am creating for a forum software (there are several dozen), and display their version number from another table, by using an INNER JOIN statement.
Here's the HTML table I want to print:
Theme Name Version Number
-------------------------------
Elegance 1.7.0
Smarty 1.7.4
Aria 1.8.1
etc etc
The themes and their IDs are stored in xf_style table:
--------------------------------
style_id | title
--------------------------------
1 | Elegance
2 | Smarty
3 | Aria
The theme version numbers are stored in the options table xf_style_property. There's hundreds of options in the backend system, each with an option ID (style_property_id). The "Theme Version" option I'm looking for has ID of "5145".
xf_style_property table
---------------------------------------------------------------------
style_id | style_property_id | property_label | property_value
---------------------------------------------------------------------
1 | 5144 | Logo Size | 110px
2 | 5144 | Logo Size | 145px
3 | 5144 | Logo Size | 120px
1 | 5145 | Theme Version | 1.7.0
2 | 5145 | Theme Version | 1.7.4
3 | 5145 | Theme Version | 1.8.1
There are many repeating values in this table. Basically I want to fetch the property_value for each theme where the style_property_id equals 5145, and inner join this with the xf_style table.
My full script:
<?php
$servername = "localhost";
$username = "***";
$password = "***";
$dbname = "***";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "SELECT xf_style.title, xf_style_property.property_value FROM xf_style_property WHERE property_definition_id = 5145, INNER JOIN xf_style ON xf_style_property.style_id=xf_style.style_id";
$result = $conn->query($sql) or die($conn->error);
?>
<table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
<thead>
<tr>
<th>Theme Name</th>
<th>Theme Version</th>
</tr>
</thead>
<tbody>
<?php
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row['title'] . "</td><td>" . $row['property_value'] . "</td></tr>";
}
?>
</tbody>
</table>
I've been trying a dozen different tweaks including this guide:
https://www.w3schools.com/sql/sql_join.asp
and other guides here at SE and can't seem to make it work. Any help would be appreciated from a SQL newbie.
Disclaimer: the property_label column doesn't actually exist.. I only wrote it in for reader understanding. It's already known from another table which ID represents what option label.
The where conditions are after the join
This should fix it
$sql = "SELECT xf_style.title, xf_style_property.property_value FROM xf_style_property INNER JOIN xf_style ON xf_style_property.style_id=xf_style.style_id" WHERE property_definition_id = 5145,;
Otherwise if you want to avoid repeated themes (even if they ahve diferent propety value) you can use Group By
Your query should simply be
SELECT xfs.title, xfsp.property_value
FROM xf_style_property xfsp
INNER JOIN xf_style xfs ON xfsp.style_id = xfs.style_id
WHERE xfsp.style_property_id = 5145

Select data from my three tables

I have three tables, one named album, while the other one is soundtrack and last but definitely not the least, is the artist.
Under one album is more than one track (obviously) and an artist name...
So this is how it should look like:
Desired Output:
|---------------------|
|AlbumName by Charlie |
|---------------------|
| 1. See you again |
|---------------------|
| 2. One call Away |
|---------------------|
| Album by Ed Sheeran |
|---------------------|
| 1. Perfect |
|---------------------|
| 2. Dive |
|---------------------|
And below is mysqli_fetch_array() that I used along side with while-loop to populate the <table> tag.
$query = "SELECT a.* AS Album, b.* AS Track, c.* AS Artist
FROM album a
INNER JOIN track b ON a.album_id=b.album_id
INNER JOIN artist c ON a.artist_id=c.artist_id
ORDER BY a.album_id ASC";
$result = mysqli_query($con, $query);
$c=0;
while($row = mysqli_fetch_assoc($result)) {
$album = $row['Album']." (".$row['Artist'].") ";
$track = $row['Track'];
}
The problem is, when I ran this code... I could only get this result...
|---------------------|
|AlbumName by Charlie |
|---------------------|
| 1. See you again |
|---------------------|
| 2. One call away |
|---------------------|
| 1. Perfect |
|---------------------|
| 2. Dive |
|---------------------|
It got the list of the soundtracks, including the soundtrack's ID right, however, things didn't do well on the Album Name
I want it just to look like the Desired Output. Any ideas? I've tried to search stackoverflow, but it seems it couldn't direct me on the same question, so I made my own. Please forgive (do not flag) me if it had an existing already, its just that I didn't know where to find it. And pleeeeease... I need an immediate and working answer. Thanks guys!
As for DATABASE Structure
album = {album_id, artist_id,album_title}
artist = {artist_id, artist_name}
track = {song_id, album_id, song_title}
UPDATE!
Okay, so this goes a little bit out of control. When I tried #swellar's suggestion this what happened. And when I undo it, the output remains the same.
See the result below...
|---------------------|
|AlbumName by Charlie |
|---------------------|
| 1. See you again |
|---------------------|
|AlbumName by Charlie |
|---------------------|
| 2. One Call Away |
|---------------------|
|AlbumName by Charlie |
|---------------------|
| 1. Perfect |
|---------------------|
|AlbumName by Charlie |
|---------------------|
| 2. Dive |
|---------------------|
What I want is to give each Album one or more than soundtrack but it get so messed up each time I dare to change the query. How can I sanitize the mysqli_fetch_array() for it to display the desired output?
Here is your SQL
Notice I've put 3 order by in there. First by the artist name, which would keep all artist's stuff grouped together, then by album name and then by song id.
$sql = "SELECT a.album_title AS Album,
t.song_title AS Track,
t.song_id AS ID,
n.artist_name AS Artist
FROM album AS a
INNER JOIN track AS t
ON a.album_id = t.album_id
INNER JOIN artist AS n
ON a.artist_id = n.artist_ID
ORDER BY n.artist_name ASC,
a.album_id ASC,
t.song_id ASC";
/*
That SQL will generate the following array
Array
(
[Album] => AlbumName
[Track] => See you again
[ID] => 1
[Artist] => Charlie
)
Array
(
[Album] => AlbumName
[Track] => One call Away
[ID] => 2
[Artist] => Charlie
)
Array
(
[Album] => Album
[Track] => Perfect
[ID] => 1
[Artist] => Ed Sheeran
)
Array
(
[Album] => Album
[Track] => Dive
[ID] => 2
[Artist] => Ed Sheeran
)
*/
Below is your while loop
<table>
<?php
// Some placeholders
$album = null;
while($row = mysqli_fetch_assoc($result))
{
if($row['Album'] !== $album)
{
?>
<tr>
<td style="border: 1px solid #000000; background-color: #dedede;"><?php echo $row['Album']; ?> by <?php echo $row['Artist']; ?></td>
</tr>
<tr>
<td style="border: 1px solid #000000;"><?php echo $row['ID']; ?>: <?php echo $row['Track']; ?></td>
</tr>
<?php
}
else
{
?>
<tr>
<td style="border: 1px solid #000000;"><?php echo $row['ID']; ?>: <?php echo $row['Track']; ?></td>
</tr>
<?php
}
$album = $row['Album'];
}
?>
</table>
Overall Output is:
<table>
<tr>
<td style="border: 1px solid #000000; background-color: #dedede;">AlbumName by Charlie</td>
</tr>
<tr>
<td style="border: 1px solid #000000;">1: See you again</td>
</tr>
<tr>
<td style="border: 1px solid #000000;">2: One call Away</td>
</tr>
<tr>
<td style="border: 1px solid #000000; background-color: #dedede;">Album by Ed Sheeran</td>
</tr>
<tr>
<td style="border: 1px solid #000000;">1: Perfect</td>
</tr>
<tr>
<td style="border: 1px solid #000000;">2: Dive</td>
</tr>
</table>
There are better ways to go around doing this, but not knowing your work environment, skills, requirements, other code, w/e this is the best quick and dirty solution for you to base your solution of. This works to what you requested.

MYSQL select from table and count from another

I have subjects table contains subjects details and subject_student table contains the subjects selected by students. I want to select all the the subjects details selected by more than 2 students and also get the count of students for each subject selected by more than 2 students.
Subjects table
------------------------------
ID | Name | units
------------------------------
1 | web | 1
2 | programming | 1
3 | java | 1
4 | QA | 1
------------------------------
student_subject Table
Subject table
------------------------------
student_id | subject_id | status
------------------------------
1 | 1 | current
1 | 2 | current
2 | 1 | current
2 | 3 | current
3 | 1 | current
3 | 3 | current
4 | 1 | current
5 | 5 | current
------------------------------
so the result here must select the first row of subjects table and the 4 which is the count of students selected web subject
Here is the Query:
$query= "
SELECT s.sub_ID
, s.Name
, s.units
, count(st.subject_id) as cc
from subjects as s
LEFT
JOIN students_subject as st
ON s.ID = st.subject_id
GROUP
BY st.subject_id
Having count(st.subject_id)>2)
";
when I run the code it gives me this error:
Notice: Trying to get property of non-object
here is the PHP code:
global $con,$users;
$query= "SELECT s.sub_ID,s.Name, s.units,s.dept, count(st.subject_id)as cc from subjects as s LEFT JOIN students_subject as st
ON s.ID=st.subject_id GROUP BY st.subject_id Having count(st.subject_id)>2)";
//$query="SELECT * FROM subjects;";
$result=mysqli_query($con,$query);
if ( $result->num_rows == 0 ) // User doesn't exist
echo "Subjects doesn't exist!";
else { echo "
<tr>
<th>Subjects ID</th>
<th>Title</th>
<th>Units</th>
<th>Department</th>
<th>Check</th>
</tr>";
$r=0;
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['sub_ID'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['units'] . "</td>";
echo "<td>" . $row['cc'] . "</td>";
}
Check your query for names of tables and columns Subjects(ID,Name,units), students_subject(student_id,subject_id,status):
SELECT
sb.id AS sub_ID, -- !!!
sb.Name,
sb.units,
COUNT(st.student_id) AS cc
FROM Subjects sb
JOIN students_subject st ON st.subject_id=sb.id
GROUP BY sb.id,sb.name,sb.units
HAVING COUNT(st.student_id)>2
You also can use print_r in while for test names which were returned with mysqli_fetch_array
while($row = mysqli_fetch_array($result))
{
print_r($row);
...
Here doesn't need a bracket )
$query= "... Having count(st.subject_id)>2)"; // <--
Try to delete it
$query= "... Having count(st.subject_id)>2";

Putting select count data into a Fetch Array Query row PHP

I have a script which retrieves all users with the same "dealership_id" from the "users" table, this works fine. Each user within these records has an ID (users_sales_guild_id) which is also on another table called "sales_list".
What I am trying to do is list the total amount of sales which each user has from the "sales_list" table next to the respective user
Currently it prints the logged in user's amount (John Smith , value of 5), and not each individual amount, where am I going wrong?
How I would like it to look
Name | Position | SID | Total Sales |
John Smith | Sales Consultant | 23434 | 5 | Details
Jane Smith | Sales Consultant | 34234 | 9 | Details
John Chan | Sales Manager | 43423 | 3 | Details
Jane Chan | Sales Consultant | 23344 | 7 | Details
How it looks
Name | Position | SID | Total Sales |
John Smith | Sales Consultant | 23434 | 5 | Details
Jane Smith | Sales Consultant | 34234 | 5 | Details
John Chan | Sales Manager | 43423 | 5 | Details
Jane Chan | Sales Consultant | 23344 | 5 | Details
PHP Code
$query = "SELECT `users_id`, `users_email` , `users_sales_guild_id` , `users_dealer_code_id` ,
`users_first_name` , `users_surname` , `users_dealer_name` , `users_type` , DATE_FORMAT(`registration_date`, '%d-%m-%Y')
AS `dr`
FROM `users`
WHERE `dealership_id` = '".$_SESSION['dealership_id']."'
AND (users_type = 'Sales Manager' OR users_type = 'Sales Consultant')
ORDER BY registration_date DESC";
$result = mysql_query("SELECT * FROM sales_list WHERE sales_list.users_sales_guild_id ='" . $_SESSION['users_sales_guild_id'] . "'");
$num_rows = mysql_num_rows($result);
$result = #mysql_query ($query); // Run the query.
echo '<table>
<tr>
<td align="center">Name</td>
<td align="center">Position</td>
<td align="center">ID</td>
<td align="center">Total Sales</td>
<td align="center"></td>
</tr>';
$bg = '#ffffff'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$bg = ($bg=='#e1e3e6' ? '#cdcdcf' : '#e1e3e6'); // Switch the background color.
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="center">' . $row['users_first_name'] . ' ' . $row['users_surname'] . ' </td>';
echo '<td align="center">' . $row['users_type'] . '</td>';
echo '<td align="center">' . $row['users_sales_guild_id'] . '</td>';
echo '<td align="center">' . $num_rows . '</td>';
echo '<td align="center"><a href="sm-sales-ind-2.php?smid=' . $row['users_id'] . '">Details</td>';
}
echo '</table>';
mysql_free_result ($result); // Free up the resources.
mysql_close(); // Close the database connection.
?>
You'd have to add a subquery or join to your sql, something similar to:
Join:
SELECT name, COUNT(sales_list.*)
FROM salesman
JOIN sales_list ON salesman.id = sales_list.salesman_id
GROUP salesman.id
Subquery:
SELECT
name,
(SELECT COUNT(*) FROM sales_list
WHERE salesmen.id = sales_list.salesman.id) as sales_count
FROM salesmen
Then you can use $row['sales_count'] in the output
The $num_rows refers to the number of rows returned, it doesn't contain any specific counts of sales per user

Categories