SQL Inner Join Issue (Could be easy fix) - php

So I am trying to populate a drop down by grabbing my playersID from the players table whilst sharing the same playersID with my Payments table.
When I put my query as below, it works fine.
$sql = "SELECT playersID FROM players";
But when I want to join the two tables together, I get an empty drop down.
<?php
include "dbconnect.php";
$sql = "SELECT players.playersID FROM players INNER JOIN Payments ON Payments.playersID = players.playersID";
if (!$result = mysql_query($sql, $conn))
{
die('Error in querying the database' . mysql_error());
}
echo "<br><select name = 'listbox' id = 'listbox' onclick = 'populate()'>";
while ($row = mysql_fetch_array($result))
{
$playersID = $row['playersID'];
$allText = "$playersID,";
echo "<option value = '$allText'> $playersID</option>";
}
echo "</select>";
mysql_close($conn); ?>
Note I have never done an INNER JOIN before, so it may be a simple issue. The aim of the code is to enter payment information into a form and save the data to the data table. I want to show the playerID in the payments table to show that particular player paid for this product.
Cheers!

It looks like you want to LEFT OUTER JOIN with the payments table instead of inner join, because the payment table does not have a payment for all players yet or for any at all.

Related

Showing two different values depending on SESSION value in INNER JOIN

I have two different tables, one named users, and another named transactions. Transactions contains wallet1, wallet2, amount. Users contains user details such as firstname, lastname, and wallet. I am trying to display the corresponding first name and last name, depending on whether or not the SESSION_wallet is equal to wallet1 or wallet2 within transactions. I tried searching for a while, and came up with a solution for showing the correct display name for the first and last name making the transfer, however, I am trying to make it display the correct value for "Transfer to:"
Here is some of my code to get a better understanding of what I mean:
MySQLi Query:
$result2 = mysqli_query($link, "SELECT * FROM transactions INNER JOIN users ON transactions.wallet1 = users.wallet WHERE transactions.wallet1 = '" . $_SESSION["wallet"] . "' OR transactions.wallet2 = '" . $_SESSION["wallet"] . "' Order by transactions.id DESC LIMIT 5 ");
PHP Code:
<?php
if(mysqli_num_rows($result2) > 0)
{
while($row = mysqli_fetch_array($result2))
{
?>
The table that needs to display the transfer from, and transfer to:
<?php
if ($_SESSION["wallet"] == $row["wallet1"]) {
echo "<td>Transfer to ".$row["firstname"]." ".$row["lastname"]."</td>";
}
else if ($_SESSION["wallet"] == $row["wallet2"]) {
echo "<td>Transfer from ".$row["firstname"]." ".$row["lastname"]."</td>";
}
?>
Right now my tables are only showing the first and last name of the user that made the Transfer, however, I need it to display the first and last name of the user that the transaction is made to as well. The else if code is working correct, but the first part is not showing the corresponding value.
You will need to JOIN your transactions table to your users table twice, once to get each users name. Then to avoid duplicate column names overwriting the results in the output array, you will need to use column aliases. Something like this should work:
$result2 = mysqli_query($link, "SELECT t.*,
u1.firstname AS w1_firstname,
u1.lastname AS w1_lastname,
u2.firstname AS w2_firstname,
u2.lastname AS w2_lastname
FROM transactions t
INNER JOIN users u1 ON t.wallet1 = u1.wallet
INNER JOIN users u2 ON t.wallet2 = u2.wallet
WHERE t.wallet1 = '{$_SESSION["wallet"]}'
OR t.wallet2 = '{$_SESSION["wallet"]}'
ORDER BY t.id DESC
LIMIT 5 ");
Then you can access each user's names as $row['w1_firstname'] etc.:
if ($_SESSION["wallet"] == $row["wallet1"]) {
echo "<td>Transfer to ".$row["w2_firstname"]." ".$row["w2_lastname"]."</td>";
}
else if ($_SESSION["wallet"] == $row["wallet2"]) {
echo "<td>Transfer from ".$row["w1_firstname"]." ".$row["w1_lastname"]."</td>";
}
Note that ideally you should use a prepared query for this, for example:
$stmt = $link->prepare("SELECT t.*,
u1.firstname AS w1_firstname,
u1.lastname AS w1_lastname,
u2.firstname AS w2_firstname,
u2.lastname AS w2_lastname
FROM transactions t
INNER JOIN users u1 ON t.wallet1 = u1.wallet
INNER JOIN users u2 ON t.wallet2 = u2.wallet
WHERE t.wallet1 = ?
OR t.wallet2 = ?
ORDER BY t.id DESC
LIMIT 5");
$stmt->bind_param('ss', $_SESSION["wallet"], $_SESSION["wallet"]);
$stmt->execute();
$result2 = $stmt->get_result();

Echo contents of JOIN SQL tables with MySQLi

I'm working on a system, and this module is supposed to echo the contents of the database.
It worked perfectly until I added some JOIN statements to it.
I've checked and tested the SQL code, and it works perfectly. What's not working is that part where I echo the content of the JOINed table.
My code looks like this:
$query = "SELECT reg_students.*, courses.*
FROM reg_students
JOIN courses ON reg_students.course_id = courses.course_id
WHERE reg_students.user_id = '".$user_id."'";
$result = mysqli_query($conn, $query);
if (mysqli_fetch_array($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
echo $row["course_name"];
echo $row["course_id"];
The course_name and course_id neither echo nor give any error messages.
UPDATE: I actually need to increase the query complexity by JOINing more tables and changing the selected columns. I need to JOIN these tables:
tutors which has columns: tutor_id, t_fname, t_othernames, email, phone number
faculty which has columns: faculty_id, faculty_name, faculty_code
courses which has columns: course_id, course_code, course_name, tutor_id, faculty_id
I want to JOIN these tables to the reg_students table in my original query so that I can filter by $user_id and I want to display: course_name, t_fname, t_othernames, email, faculty_name
I can't imagine that the user_info table is of any benefit to JOIN in, so I'm removing it as a reasonable guess. I am also assuming that your desired columns are all coming from the courses table, so I am nominating the table name with the column names in the SELECT.
For reader clarity, I like to use INNER JOIN instead of JOIN. (they are the same beast)
Casting $user_id as an integer is just a best practices that I am throwing in, just in case that variable is being fed by user-supplied/untrusted input.
You count the number of rows in the result set with mysqli_num_rows().
If you only want to access the result set data using the associative keys, generate a result set with mysqli_fetch_assoc().
When writing a query with JOINs it is often helpful to declare aliases for each table. This largely reduces code bloat and reader-strain.
Untested Code:
$query = "SELECT c.course_name, t.t_fname, t.t_othernames, t.email, f.faculty_name
FROM reg_students r
INNER JOIN courses c ON r.course_id = c.course_id
INNER JOIN faculty f ON c.faculty_id = f.faculty_id
INNER JOIN tutors t ON c.tutor_id = t.tutor_id
WHERE r.user_id = " . (int)$user_id;
if (!$result = mysqli_query($conn, $query)) {
echo "Syntax Error";
} elseif (!mysqli_num_rows($result)) {
echo "No Qualifying Rows";
} else {
while ($row = mysqli_fetch_assoc($result)) {
echo "{$row["course_name"]}<br>";
echo "{$row["t_fname"]}<br>";
echo "{$row["t_othernames"]}<br>";
echo "{$row["email"]}<br>";
echo "{$row["faculty_name"]}<br><br>";
}
}

From two tables from my database i would like to echo a column with click counts

In my database i have created two tables , the one is "categories" and the other "click_count".
The two tables have the following information : categories( cat_id, cat_name , cat_description ) and click_count(id, cat_id, cat_count). I have already written a php code which echo a table with information about categories and i have already written a php code whick calculates the click counts, so i want a php script which i can echo on the same table the information about click_count and specify the "cat_count" which contains the number about "clicks" . The following code is obviously wrong but you can get the logic.
<?php
$sql4 = "SELECT categories.cat_id,categories.cat_name,click_count.cat_id,click_count.cat_count WHERE categories.cat_id=click_count.cat_id";
$result4 = mysqli_query($conn, $sql4);
$row4 = mysqli_fetch_array($result4);
while($row4 = mysqli_fetch_assoc($result4)) {
echo '<td>'.$row4['cat_count']; }?>
The SELECT statement should contain a JOIN:
SELECT categories.cat_id, categories.cat_name, click_count.cat_id, click_count.cat_count
FROM categories
LEFT JOIN click_count
ON categories.cat_id = click_count.cat_id;
...and you can also add a WHERE clause at the end if you need it to select not all, but only the ones that fit a certain condition.

PHP:Retrieving images from a database query issues

I have read many posts but i cannot find my answer.
I am developing a food order/delivery website, which has many food cuisine categories, African, Alcohol, American... Each category is meant to have a different header image. So if the admin creates a new restaurant, when they select the restaurant cuisine, the correct header image will automatically display on the main websites products page for that said restaurant.
I have manually inputted the images into the database already, now i am trying to retrieve the database, my or die statement prints that it is not, but i have no error messages, which is confusing me.
mysqli_report(MYSQLI_REPORT_INDEX);
if (isset($_GET['rest_id'])) {
$Rest = $_GET['rest_id'];
$get_cat_img = "SELECT Cuisine_category
FROM Rest_Category,Category_img
INNER JOIN Rest_Details
ON Rest_Category.Cat_ID = Rest_Details.Cat_ID
WHERE Rest_Details.Cat_ID='$Rest'";
$results = mysqli_query($dbc, $get_cat_img) or die("query is not working");
$row=mysqli_fetch_array($results) or die ("q not working");
$img=$row['Category_img'];
echo $row['Category_img'];
echo '<img src="'.$img.'" alt="background" style="width:100%;height:300px">';
}
mysqli_close($dbc);
I think you may have just put a column name in the wrong place in your query.
If Category_img is a column name in the Rest_Category table, this is what you want to do
$get_cat_img = "SELECT Cuisine_category,Category_img
FROM Rest_Category
INNER JOIN Rest_Details ON Rest_Category.Cat_ID = Rest_Details.Cat_ID
WHERE Rest_Details.Cat_ID='$Rest'";
You can also shorten things a bit by using Alias's, it often makes the SQL code easier to read when it get past the very simple query.
$get_cat_img = "SELECT rc.Cuisine_category,rc.Category_img
FROM Rest_Category rc
INNER JOIN Rest_Details rd ON rc.Cat_ID = rd.Cat_ID
WHERE rd.Cat_ID='$Rest'";
Also modify your error reporting to actually report the real MYSQL error, it is much more usful that any message you can some up with
Like so
$results = mysqli_query($dbc, $get_cat_img);
if ( $result === false ) {
echo 'query is not working: ' . mysqli_error($dbc);
exit;
}

Not understanding the Join Function

Thanks in advance for any time you spend on my question.
I am trying to display data in a way that will display the manufacturer as a name instead of a number.
Basically when they store the data they choose a manufacturer from a drop down which is generated from a table.. IE Trogues = 1 so products stores the #1 so I know that any beer is associated with trogues is 1. Now I want to display the data but instead of having a 1 I would like to have Trogues be displayed. Where you see manufacturer in the echo code below..
I am not understanding the process logic here..
error_reporting(E_ALL);
ini_set('display_errors', 1);
$sql = "SELECT * FROM products
LEFT JOIN manufacturer
ON product.manufacturer = manufacturer.id
ORDER BY manufacturer.id, product.id";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)) {
echo "
<div class=reportclientproduct>".$row['manufacturer']." - <a href=".$row['website']." target=_blank>".$row['product']."</a></div>";
}
Have you tried the query like this:
$sql = "SELECT man.id AS manufac, products.product AS prod FROM products
LEFT JOIN manufacturer as man
ON product.manufacturer = manufacturer.id
ORDER BY manufacturer.id, product.id";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)) {
echo "
".$row['manufac']." - ".$row['prod']."
";
}
Assuming that the table products had a column named manufacturer which holds the ID of the manufacturer, and that both tables have columns name ID which hold the ID of the table item.
Also the JOIN functions may vary based on the database you use. But the aforementioned method is for mysql.

Categories