PHP & mysql display data from multiple table - php

I have two table which contain have data like as mentioned below:
Table1
TID Name
1 Salman
2 ABC
3 XYZ
Table2
SID STID SUBJECT
1 1 English
2 1 Math
3 2 Physics
4 2 Math
Table1 TID foreign key in Table2 STID. I want to collect data from two table and display in PHP as mentioned below:
Name Subject1 Subject2
Salman English Math
ABC Physic Math

there is my suggestion algorithm
$mysqli = new mysqli("HOST", "USER NAME", "USER PASS", "YOUR DATABASE");
$result = $mysqli->query("SELECT * FROM table1");
while ($row = $result->fetch_assoc()){
$TID = $row['TID'];
$Name = $row['Name'];
$result2 = $mysqli->query("SELECT * FROM table2 where `TTID` = $TID");
echo "$Name \t";
while ($row2 = $result2->fetch_assoc()){
$SUBJECT = $row2['SUBJECT'];
echo "$SUBJECT \t";
}
echo '<br/>';
}
$mysqli->close();

If you know the maximum number of subjects that can be assigned to a student,
Please check this query
SELECT A.Name ,
(SELECT subject from Table2 where STID = A.TID limit 0,1 ) as SUBJECT1,
(SELECT subject from Table2 where STID = A.TID limit 1,1 ) as SUBJECT2
FROM Table1 A

Related

Fetch rows and check if has same value

I'm very new to coding and trying to learn PHP and MYSQL. What I'm trying to do is, grouping the same CustomerID querys in the same table while making an echo. At the moment, my code echos all the querys seperated. I have a table like
ID CustomerID DATE Company
1 1 2018-11-19 A
2 1 2018-11-19 A
3 2 2018-11-19 B
4 3 2018-11-19 C
5 4 2018-11-19 D
6 4 2018-11-19 D
My code
$query = "SELECT `customers`.ID, `customers`.customerid, `customers`.date
FROM `customers` WHERE month(DATE)= month(CURRENT_DATE()) AND YEAR(DATE) = YEAR(CURRENT_DATE());
$result = $mysqli->query($query);
while($resultquery = $result->fetch_array())
{
$queryresult[] = $resultquery;
}
if (!empty($queryresult)) {
foreach($queryresult as $queryresults)
{
$id = $queryresults['id'];
$customerid = $queryresults['customerid'];
$date = $queryresults['date'];
?>
Then I echo it and the result is
Company Name: A
ID CustomerID DATE
1 1 2018-11-19
Company Name: A
ID CustomerID DATE
2 1 2018-11-19
Company Name: B
ID CustomerID DATE
3 2 2018-11-19
Company Name: C
ID CustomerID DATE
4 3 2018-11-19
<?php }} ?>
Etc..
But what I want is to compare customerID's and if there is more than one with same id, echo them as a group in the table.
Company Name: A
ID CustomerID DATE
1 1 2018-11-19
2 1 2018-11-19
Company Name: B
ID CustomerID DATE
3 2 2018-11-19
Company Name: C
ID CustomerID DATE
4 3 2018-11-19
I made an sql query with GROUP_CONCAT and used SEPARATOR '|') to group the result, it works but I dont think its the best to achieve this, so please help. Thank you
Map your data in a key-value array with Company as key (include company in the query:
$query = "SELECT customers.ID, customers.customerid, customers.date, company
FROM customers WHERE month(DATE)= month(CURRENT_DATE()) AND YEAR(DATE) = YEAR(CURRENT_DATE())";
$query = "SELECT `customers`.ID, `customers`.customerid, `customers`.date
FROM `customers` WHERE month(DATE)= month(CURRENT_DATE()) AND YEAR(DATE) = YEAR(CURRENT_DATE());
Then simplify the data collection using a key to group items:
$result = $mysqli->query($query);
$queryresult = [];
while($resultquery = $result->fetch_array())
{
$company = $resultquery['company'];
if (array_key_exists($company,$queryresult){
#$queryresult[$company] = [];
}
#$queryresult[$company][] = $resultquery;
}
An then you can present the information using foreach:
foreach($queryresult as $company => $items){
// header by company
echo "Company Name: $company \n";
echo "ID CustomerID DATE\n";
foreach($items as $item){
// items in company
echo "{$item['id']} {$item['customerid']} {$item['date']}\n";
}
}

How to displays total count of instructors for each department ? SQL Query

Here is the department table
department_id | department_name
1 computers
2 maths
3 physics
4 mba
Here is instructor table
instructor_id | department_id | name
1 1 abc
2 2 manu
3 2 raju
4 3 jaya
5 4 man
From above code how to displays total count of instructors for each department?
what will be the query?
Please help.
I'm doing it in codeigniter.
select d.department_id, count(*) as num_instructors
from departments d
inner join instructors i on i.department_id = d.department_id
group by d.department_id;
You may try to conceptualize from my solution below and see if it can help,
To avoid complication you could just go direct
<?php
//connection
$link = mysqli_connect("localhost","root","","database_name") or die("Couldn't make connection.");
$computer_department_id = //the value
$query = mysqli_query($link, "SELECT department_id FROM instructure_table WHERE department_id='$computer_department_id')");
$total = mysqli_num_rows($query);
echo $total; //this one will display the total number of instructors in computer department
?>
Or if you like
<?php
//connection
$link = mysqli_connect("localhost","root","","database_name") or die("Couldn't make connection.");
$computer_department = //the value
$query = mysqli_query($link, "SELECT department_id
FROM instructure_table AS t
WHERE EXISTS (SELECT department_id
FROM department_table AS d
WHERE d.department_id = t.department_id AND department_id='$computer_department')");
$total = mysqli_num_rows($query);
echo $total; //this one will display the total number of instructors in computer department
?>
So if you place the query in the department line s
department_id | department_name
1 computers //the query
2 maths //the query
3 physics //the query
4 mba //the query
Even if the query for department is in a repeating region it would still work for you. regards
SELECT COUNT(i.instructor_id) as `instructor_count`, d.department_name
FROM instructor AS i
JOIN department ON d.department_id = i.department_id
GROUP BY i.department_id"

Mysql query array

I have two tables:
1 - hotels[id,name,extras] ( name of hotels with column extras which I've select for each one)
2 - extras[id,name] ( here's the extras of hotel like wifi,tv,swim... )
$name = $_GET['name'];
$hotels_q = mysql_query("SELECT * FROM `hotels` WHERE `name`='$name'") or die (mysql_error());
$hotels_row = mysql_fetch_array($hotels_q);
$id = $hotels_row['id'];
$extras = explode(",", $hotels_row['extras']);
$ekstras_q = mysql_query("SELECT * FROM `extras` order by id") or die(mysql_error());
While($ekstras_row = mysql_fetch_array($ekstri_q)){
$eid = $ekstras_row['id'];
$ename = $ekstri_row ['name'];
echo '<ul><li><input type="checkbox" name="extras['.$eid.'][]" value="'.$ename.'"';
if (in_array($eid, $ekstras)) echo'checked';
echo'/>'.$ename.'</li></ul>';
Problem is here extras_q displays all entries with checked ones from table, but I want only to display only checked items!
Since you're storing your extra IDs in one column as a comma separated string, I think you should be able to do this by not exploding that value, and then using the CSV string as an IN criteria in your second query.
//...
$extras = $hotels_row['extras']; // don't explode
// Use IN with the $extras CSV here
$ekstras_q = mysql_query("SELECT * FROM `extras`
WHERE id IN ($extras) ORDER BY id") or die(mysql_error());
If you are able to modify your database, you can instead create a many-to-many relationship between hotels and extras by adding a table to join those two items together instead of using a CSV column as you currently are. This can make it easier to write queries to select the related records.
If you add a third table hotel_extras with columns hotel_id and extra_id, you can insert one row for each extra that each hotel has. For example, if the hotel with id 1 has several different extras, its entries in that table would look like this:
table: hotel_extras
_______________________
| hotel_id | extra_id |
=======================
| 1 | 1 |
| 1 | 3 |
| 1 | 4 |
-----------------------
Here is an example using PDO of how you could query data from a setup like that:
$sql = "SELECT e.id, e.name
FROM hotels h
INNER JOIN hotel_extras he ON h.id = he.hotel_id
INNER JOIN extras e ON he.extra_id = e.id
WHERE h.`name` = ?";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(1, $_GET['name']);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$eid = $row['id'];
$ename = $row['name'];
'<li><input type="checkbox" name="extras['.$eid.'][]" value="'.$ename.'" checked/>'.$ename.'</li>';
}

Get next and previous records within the same query

I'm having this PDO query to call data from a MySQL.
$sql = "SELECT itemName FROM furniture WHERE itemID = :item";
While calling for this particular itemName, is it possible to get the next and previous itemNames by using its itemID within this same query itself without having to write a new query to get the next and previous itemNames?
e.g.
if
itemID | itemName
___________________________
553 | Mahogani Black Chair
554 | Teak Round Table
555 | Thulang Relaxing Chair
556 | Teak Relaxing Chair
$sql = "SELECT itemName FROM furniture WHERE itemID = :item";
$stmt = $connect->prepare($sql);
$stmt->execute(array(':item'=>"554"));
$rslt = $stmt->fetchAll(PDO::FETCH_ASSOC);
I'm looking away of getting Teak Round Table and Mahogani Black Chair and Thulang Relaxing Chair
Please use this code:
(SELECT itemName FROM furniture WHERE itemID < 554 order by itemID desc limit 1)
UNION
(SELECT itemName FROM furniture WHERE itemID >= 554 order by itemID asc limit 2)
For Example code :
MyTable:
================
id Store_name
================
1 English
2 French
3 Tamil
4 Uk
5 US
<?php
$con = mysqli_connect("localhost","root","ramki","ramki");
$sql = "(SELECT store_name FROM store WHERE id < 2 order by id desc limit 1)
UNION
(SELECT store_name FROM store WHERE id >= 2 order by id asc limit 2)";
$query = mysqli_query($con,$sql);
while ($row = mysqli_fetch_assoc($query)) {
echo $row['store_name'];
echo "<br>";
}
?>
$sql = "SELECT itemName FROM furniture WHERE itemID IN (:item-1, :item, :item+1) ORDER BY itemID";
For iterating the results, you can also use PDO fetch() function to get each row.

Not select only first row in column

functions.php
function getfriendone($id, $field){
$query = mysql_query("SELECT `$field` FROM `friends` WHERE `user_one`='$id'");
$run = mysql_fetch_array($query);
return $run[$field];
}
function getfriendtwo($id, $field){
$query = mysql_query("SELECT `$field` FROM `friends` WHERE `user_two`='$id'");
$run = mysql_fetch_array($query);
return $run[$field];
}
index.php
$fetch_friends = $_SESSION['user_id'];
$two = getfriendone($fetch_friends, 'user_two');
$three = getfriendtwo($fetch_friends, 'user_one');
$result = mysql_query("SELECT * FROM posts WHERE id IN ('$two', '$three')");
echo $two." | ".$three;
Table (friends) for getfriend function
ID user_one user_two
1 1 2
2 1 3
3 4 1
Table (posts) for $result
ID TEXT NAME
1 Hello Bob
1 Hello Bob
2 Hello Mark
What i wanna do here is echo all the rows that has integer 1 in it in both user_one and user_two. In my chase, only ID 1 and 3 will be echoed here. It picks the first match and echos only that one. It works as it should, but only with the first match in the column
If i read properly:
SELECT *
FROM posts s
WHERE
EXISTS
(SELECT 1 FROM posts s2 WHERE s.id = s2.user_one) OR
(SELECT 1 FROM posts s2 WHERE s.id = s2.user_two)
Will extract the data you need
SQLFiddle -> http://sqlfiddle.com/#!2/9ae070/3/0

Categories