Compare 2 mysql column values from different tables - php

I have 2 tables :
accounts
lanes
lanes contains 1 column "boss_id" which is an INT between 1 and 12
accounts contains various columns including username, password and also a boss_id column
Im trying to use PHP to display ALL items from the lanes table, which is working great! But, what i need to do is also show if a user from "accounts" also shares or has the same boss_id and displays a different output :
Regular output (no matching account)
foreach ($boss_id as $boss) {
echo "Lane " . $boss . "<br>;
}
If there is a matching account show this instead
echo "Lane booked by " . $username. "<br>;
I've spent a lot of time on this, and really need some help as i cant seem to figure it out.
Any help would be awesome! If you need anymore information, please ask!
Thanks in advance
E
This is what i have so far (variables may differ in name but you should get the idea!)
$db_host = "localhost";
$db_username = "root";
$db_password = "";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "archery-booking") or die("Error " . mysqli_error());
// get ALL lanes from database table "lanes"
$sql = mysqli_query($connection, "SELECT * FROM lanes");
while($row = mysqli_fetch_array($sql)) {
$bossid[] = $row['bossid'];
}
// save each result as a variable
foreach ($bossid as $compare) {
$compare = $compare;
}
// get ALL BOOKED lanes from database table "accounts"
$sqluser = mysqli_query($connection, "SELECT * FROM accounts WHERE boss_id = '".$compare."' ");
while($row = mysqli_fetch_array($sqluser)) {
$bookedboss[] = $row['boss_id'];
}
Updates
So i have no made a couple of changes, and getting the information for both lane.boss_id and also accounts.boss_id
How ever, i still need to do the following :
If lane.boss_id doesnt have an account attached to it, then do this, if it does have an account then do that.
What would be the best way of checking this condition? I was going to use an if/else on "username" but i got an error about illegal string offsets....here's my code so far!
$db_host = "localhost";
$db_username = "root";
$db_password = "";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "archery-booking") or die("Error " . mysqli_error());
// get ALL lanes from database table "lanes"
$sql = mysqli_query($connection, "SELECT l.*, a.username FROM lanes l LEFT JOIN accounts a ON a.boss_id = l.bossid");
while($row = mysqli_fetch_array($sql)) {
$bossid[] = $row['bossid']['username'];
var_dump($bossid);
}
UPDATE 3
I can't thankyou all enough for your help, we've really made progress!! :D
I have 1 final request though and i hope you guys can help as well as you have already! :)
So, in my script i have the following :
if (isset($uname)) {
echo "<div class='col-xl-3 col-lg-3 col-md-6 col-sm-6 col-xs-6'>
<div class='card bg-normal'>
<div class='card-header day1'>
<p>Lane booked from 6.00pm</p>
</div>
<div class='card-body'>";
echo "<h2 class='lane-title taken'>Lane " . $bossid . "</h2>";
echo "<p class='lead'>Booked by " . $uname . "</p>";
echo "</div>
</div>
</div>";
} else {
echo "<div class='col-xl-3 col-lg-3 col-md-6 col-sm-6 col-xs-6'>
<div class='card bg-normal'>
<div class='card-header day1'>
<p>Lane booked from 6.00pm</p>
</div>
<div class='card-body'>";
echo "<h2 class='lane-title'>Lane " . $bossid . "</h2>";
echo "Lane Available";
echo "</div>
</div>
</div>";
}
This works great and outputs everything required, BUT....what i need is the following :
If no username, show 1 entity with label "FREE"
If username + detail = 1, show 1 entity with label "TAKEN BY $username"
IF username + detail = 1 AND 2, show 1 entity with label "TAKEN BY $username1 and $username2
At the moment, from the code above, if detail 1 AND 2 are on boss_id 5, then there are 2 entities of boss_id 5, where i only need 1 entity showing both the details 1 AND 2.
Hope this makes some sense!! :)
TIA
E

You seem to want a LEFT JOIN:
SELECT l.*, a.username
FROM lanes l
LEFT JOIN accounts a ON a.boss_id = l.boss_id
When there is a recored in accounts whose boss_id matches, this brings the corresponding username in the resultset. If there is no match, username comes as null.

Related

Display a list of categories with links [duplicate]

I have a database were the information from the database comes on to my website (code below).
On another page I have a text box were you type in a new table, it creates a new table and sends the table name to another table which stores all the tables. I want to view all the tables from that table list but have them when i click on them take me to view the other tables.
I have very little experience with databases and PHP but I'm thinking if I can store the table variable in cookies and then initiate it in another document and have it resets every time the user returns to the page which has all of the other tables they can view.
But I still don't know how to create links to that other doc which runs all the other tables.
This text below is in a file called db_results.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY id DESC LIMIT 500";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<p>". $row["firstname"]. " " . $row["lastname"] . "</p>";
}
} else {
echo "0 results";
}
$conn->close();
?>
this code views the results and is just called index.php
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
setInterval(function() {
$("#load_results").load("db_results.php");
}, 1000);
});
</script>
<div id = "load_results"></div>
the code is not setup for links yet but the links would go into last name and the viable name into first. please message me for any further questions.
You will have to change the echo to echo a link.
If it really goes into your last name field it would look something like this:
echo "<p>". $row["firstname"]. " " . $row["lastname"] . "</p>";
But it wouldbe better if you created another field in your table to insert the link into.

Display row count based on variable

I have two tables, SpeciesHuntBoats contains details of Boats, the Make, Skipper etc. and SpeciesHunt which is generated by the skipper submitting a catch report form with details of their fishing catches. showboats.php displays 5 columns, Year, Boat Name, Make, Skipper, Number Of Species Caught.
For the final column I want a display of the number of rows in SpeciesHunt where that BoatName appears (to give a leaderboard of who has entered the most catches). This is as far as I've been able to get unfortunately, any help much appreciated!
<body>
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Count Rows
$result = mysqli_query($conn, "SELECT * FROM SpeciesHunt");
$num_rows = mysqli_num_rows($result);
// Check row count of entire table works
echo "$num_rows Rows\n";
$sql = "SELECT Year, BoatName, BoatMake, Skipper FROM SpeciesHuntBoats";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Hunt Year</th><th>Boat Name</th><th>Boat Make</th><th>Skipper</th><th>Number Of Species</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Year"]. "</td><td>" . $row["BoatName"]. "</td><td>" . $row["BoatMake"]. "</td><td>" . $row["Skipper"]. "</td><td>
$num_rows</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
</body>
Table structures:
SpeciesHunt
SpeciesHuntBoats
For your tables, you should rather make use of a relationship between boats and hunts
You should research a bit into sql relationships.
Currently you are basically saving the boat name, make and skipper twice.
This is a better suggestion for the structure:
Boats:
Year
Name
Make
Skipper
Photo
Hunts:
DateCaught
Angler
Species
Notes
BoatId (This will be a reference to a certain boat record)
In this case you can do a sql query that joins the two tables
select Year, Name, Make, Skipper, count(hunts.id) from boats
join hunts on boats.id = hunts.BoatId
group by Year, Name, Make, Skipper;
What this will return is a certain boat with a total count of hunt records.
Things you can research into:
MySQL relationships
MySQL joins
MySQL aggregates

Showing me only one result?

I have two tables in my database these are:
customer
product
customer table:
customerID
sl_no(pk)
name
email
phone
product table:
product_id(pk)
sl_no(fk)
product
price
When i run this query it shows me only one result:
$sql = (" SELECT * FROM customer INNER JOIN product WHERE customer. sl_no LIKE '%$search%' OR product. sl_no LIKE '%$search%'");
Your sql query will at some point return an error of being ambiguous or column with name, product not found. I have added aliases in the SQL query. If you do not understand. You can read up from here. https://www.w3schools.com/sql/sql_alias.asp
If you
Also try using mysqli because mysql is been deprecated as of PHP
5.5.0
$servername = "yourhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = (" SELECT customer.name AS name, customer.email AS email, customer.phone AS phone, product.product AS product_name, product.price AS price FROM customer, product WHERE customer.sl_no = product.sl_no AND customer. sl_no LIKE '%$search%' OR product. sl_no LIKE '%$search%' ");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<strong>CUSTOMER</strong>";
echo "Customer Name: " . $row["name"]."<br>";
echo "Customer email: " . $row["email"]."<br>";
echo "Customer phone: " . $row["phone"]."<br>";
echo "----";
echo "<strong>PRODUCT</strong>";
echo "Product Name: " . $row["product_name"]."<br>";
echo "Product Price: " . $row["price"]."<br>";
echo "-----";
echo "----";
}
} else {
echo "0 results";
}
$conn->close();
Don't forget to first test or run query in the database via your
UI/phpmyadmin or CLI to understand what result you should expect.
Hope this helps.
You may have several issues. As we can't see the Php iteration of the results.... here's some issues with the basic select...
Missing on clause (or change your inner join to a cross join) so your meaning is clear.
The OR in the clause or doesn't make sense if it's an inner join given PK/FK nature of the field.
searching using like %var% seems like bad form. Do you know the exact values? if so use them instead of %var% since this method can't use indexes.
your where customer. sl_no has a space... this won't work.
.
$sql = ("SELECT *
FROM customer C
INNER JOIN product P
ON C.sl_no = P.SL_NO
WHERE C.sl_no = '$search'");
If you do really mean like then put the like and %'s back but this seems like bad form. and don't you need . before and after var in php. I'm not a big developer there so maybe I'm thinking of something else.

limit results from database php

I have this code that will display all of the info on my database. The problem is I want to show only about 10 of the last results. But be able to request more somehow by pressing button. Thank you for taking interest in my question.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<div id='message'> <br> ". $row["firstname"]. " " . $row["lastname"] . "<br> </div>";
}
} else {
echo "0 results";
}
$conn->close();
?>
There are two ways you could solve this
Option 1
The problem is I want to show only about 10 of the last results
One way to do it is to use the SQL Limit specifier
$sql="Select * from ORDERS LIMIT 5"
this will fetch the 5 items from your database. You can use ordering mechanisms for sorting,etc
But be able to request more somehow by pressing button.
You can use the offset specifier for this.
$sql="Select * from ORDERS LIMIT 5 OFFSET 15"
This fetches 10 records from the 16th record.You can add to the offset on each button press.
Here is some more information on this link.
Option 2
Pagination.This link should help.
use LIMIT and OFFSET clause for limit selection. link
if you want to select last 10 data, write query like this.
SELECT id, firstname, lastname FROM MyGuests ORDER BY id DESC LIMIT 10
and you should use ajax for "show more" function.

PHP MySQL data retrieve from 3 tables

There is 3 tables:
First table (oc_product_to_category):
Second table (oc_product_description):
Third table (oc_product):
I want to list product name, image, price where category_id is 59
to this div:
<div class="content" style="">
<h1>'Product image'</h1>
<h3>Product name and price</h3>
</div>
I am beginner in working with multiple tables.
Can somebody help me?
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT product_id FROM oc_product_to_category WHERE category_id='62'";
$result = $conn->query($sql);
if ($result->num_rows > 0) { // output data of each row
while($row = $result->fetch_assoc()) {
echo "<div class='content' style=''> <h1>Orbit does content now.</h1> <h3>" . $row["product_id"]. "</h3> </div>";
} }
$conn->close();
?>
UPDATE: price in: oc_product table
In my opinion this is more a question related to SQL than to PHP. In each table, you have a product_id column, so you can use this as a foreign key. The SQL should look similar to:
SELECT
pd.name, p.image
FROM
oc_product_to_category ptc
JOIN
oc_product_description pd ON ptc.product_id=pd.product_id
JOIN
oc_product p ON ptc.product_id=p.product_id
WHERE
ptc.category_id=59;
If you make this query using php, you get an array containing name and image of each row matching the given category_id.
PS: I did not find any price column.

Categories