i have three table with same value of columns. example: say i have three table "table1", "table2", "table3" and each columns has "id", "title", "description", "category", "date", "thumbnail", "admin". now i'm trying to get all data from those three table. but there is a think, i want to check with if statement. if table1 not match with id, check table2. if table2 not match with id, check table3 and at last show the data. please check my below code, i'm trying to get data from those three table:
<?php
include('config/database.php');
$id=$_GET['single'];
$query=mysqli_query($conn,"select * from table1, table2, table3 where id='$id' ");
while($row=mysqli_fetch_array($query)){
$title=$row['title'];
$date=$row['date'];
$admin=$row['admin'];
$thumbnail=$row['thumbnail'];
$description=$row['description'];
$category=$row['category'];
}
?>
please help me to get all data from those three table with if statement
it will be better to understand if you post an answer. thank you in advance.
Use a UNION of 3 queries.
$sql = "
SELECT * FROM (
SELECT 1 AS tnum, * FROM table1 WHERE id = ?
UNION ALL
SELECT 2 AS tnum, * FROM table2 WHERE id = ?
UNION ALL
SELECT 3 AS tnum, * FROM table3 WHERE id = ?
) AS x
ORDER BY tnum
LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param('iii', $id, $id, $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($row) {
$title = $row['title']
$date=$row['date'];
$admin=$row['admin'];
$thumbnail=$row['thumbnail'];
$description=$row['description'];
$category=$row['category'];
}
Adding the tnum column to the result orders them so the table1 data is preferred, then table2, finally table3.
Related
I have this code
$query = mysqli_query($con, "SELECT id, dateAdded as date FROM table1 UNION SELECT id, dateSeen as date FROM table2 ORDER BY date DESC");
While($sql = mysqli_fetch_array($query)){
$id = $sql['id'];
}
Please how can i detect from which table an $id originated. For instance if outputted I get something like this
1, 2, 1, 3, 2, 4, 3, 4, 5, 6
So how can I know from which table each id came from because I have other informations I want to retrieve from each separate table using a function, Example
$title = table_query('title', $table, $id);
$name = table_query('name', $table, $id);
You can't really do this. What you can do is add data in your query:
$query = mysqli_query($con, "SELECT id, dateAdded as date, 'table1' AS tblname FROM table1 UNION SELECT id, dateSeen as date, 'table2' AS tblname FROM table2 ORDER BY date DESC");
while($sql = mysqli_fetch_array($query)){
$id = $sql['id'];
$tbl = $sql['tblname']; // this variable will store the name of the table.
}
For each query, the string table1 | table2 will be added as the 3rd column, and you can use it in your code.
This question already has answers here:
SQL query return data from multiple tables
(6 answers)
Closed 6 years ago.
I have two tables in a DB (table_1 and table_2), Each of them has a mutual column called Name.
I am currently using the following code to import some data (Name,status) only from table_1:
/* database section start */
$mysqli = new mysqli("z","z","z","z");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* database section end */
// Choose Relevant items, and turn them into an array
$item_array = array(
'item1',
'item2',
'item3'
);
//implode items, turn into string
$item_implode = join("','", $item_array);
//declare an overall array for result
$product = array();
$result = $mysqli->query("SELECT Name, Status as status from table_1 where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");
while($row = $result->fetch_assoc()) {
$product_name = $row['Name'];
// find all keys in $item_array which value is the products
$keys = array_keys($item_array, $product_name);
foreach ($keys as $key) {
// add values for these keys
$product[$key + 1]["Name"] = $row['Name'];
$product[$key + 1]["status"] = $row['status'];//
}
}
What should I add to this code if I want to import data from table_2 as well (e.g., columns named color, date_added)?
My objective is to have these keys:
$product[$x]["Name"]
$product[$x]["status"]
$product[$x]["color"]
$product[$x]["date_added"]
EDIT:
That long thread doesn't answer my question. The code isn't similar to the code I'm using, and I want to know how to apply the UNION exactly in this concrete case.
I've tried using:
$result = $mysqli->query
("(SELECT Name, status as status from table_1 )
UNION
(SELECT Name, color as color from table_2 )
where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");
while($row = $result->fetch_assoc()) {
But I get fatal error on the last line.
EDIT2:
Still getting an error:
$result = $mysqli->query
("(SELECT Name, status as statu table_1 where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode') )
UNION (SELECT color from table_2 where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode') );");
while($row = $result->fetch_assoc()) {
$result = $mysqli->query("SELECT table_1.Name, table_1.Status,table_2.color,table_2.date_added from table_1 inner join table_2 on table_1.Name=table_2.Name where table_1.Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");
(SELECT Name, Status as status FROM table_1 t1)
UNION
(SELECT color, date_added FROM table_2 t2)
Change your query, and try to use: INNER JOIN table_2
I can`t make the query for you, because I don't have your data...
Build your Query with a join.
$query="SELECT t1.Name, t1.Status as status, t2.color, t2.date_added) from "
."table_1 t1 "
."LEFT JOIN table_2 t2 ON t2.Name "
."where t1.Name IN ('$item_implode') "
."AND t2.Name = t1.Name "
."ORDER BY FIELD (t1.Name, '$item_implode');";
table1:
id (autoincrement)
username
category
table2:
id (autoincrement)
itemname
category
I have 2 queries.
1 query one shows categories that a user (logged in) belongs to:
$sql = "SELECT * FROM table1 WHERE '$login_session' = username";
I can list each record:
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "category: " . $row["category"]. "<br>";
}
That works fine.
My 2nd query is dependent on the 1st query. I need to list all records from table2 where category belongs to in array category in previous query.
$sql2 = "SELECT * FROM table2 WHERE category = I DO NOT KNOW WHAT TO PUT HERE";
How do I write $sql2?
One method uses in:
SELECT *
FROM table2
WHERE category IN (SELECT category FROM table1 WHERE '$login_session' = username");
You can use IN()
$sql = 'SELECT * FROM table2 WHERE category IN ('"' . implode('","', $arrayOfCategories).'"')'
I want to fetch value Rows from single table.I want to fetch sub_id for specific id.
I achieved my require ment in 2 query.I want to do it in single query.I want to display result as Event,order history,Eent Ticket,calander
$sql="select * from table1 where roles like %admin% and sub_id='0'"
$sql1=mysql_query($sql);
while($fet=mysql_fetch_assoc($sql1))
{
$id=$fet['id'];
$query="select page_name from table1 where sub_id= '$id'";
.. ..
}
Use a JOIN
SELECT t1.id, t1.sub_id, t1.page_name, t2.page_name AS parent_page
FROM table1 AS t1
JOIN table1 AS t2 ON t1.sub_id = t2.id
WHERE t2.roles like '%admin%' AND t2.sub_id = '0';
DEMO
use this
$sql="select sub_id from table1 where id='".$id."' ";
After this, use results of this as below
$sql= "select * from table1 where roles like %admin% and sub_id in($ids)";
You dont need another query to get the value of page_name just use $fet['page_name']; you already get the data of page_name in your first query.
$sub_id = $fet['sub_id'];//
echo $sub_id;//
$page_name = $fet['page_name'];//You can get and use the value of page_name here
UPDATED
if you want Event,Order History,Event Ticket and Calander
then change your where to sub_id = '2' ordered by id ascending.
$sql="select * from table1 where roles like %admin% and sub_id='2' order by id asc"
$sql1=mysql_query($sql);
while($fet=mysql_fetch_assoc($sql1))
{
echo $fet['page_name'].'<br/>';//display the page_name
}
You can also use the single query for getting page_name:
SELECT page_name FROM table1
WHERE roles LIKE %admin%
AND sub_id = 2
you can get Event,Order History,Event Ticket,Calendar as:
$sql="SELECT page_name FROM table1
WHERE roles LIKE %admin%
AND sub_id = 2";
$sql1=mysql_query($sql);
$records = array();
while($fet=mysql_fetch_assoc($sql1))
{
$records[] = $fet['page_name'];
}
echo implode(",",$records); // Event,Order History,Event Ticket,Calendar
UPDATE 1:
use sub_id = 2 for getting all page_name related to Event MAnagement
Side note:
I suggest you to use mysqli_* or PDO, instead of mysql_* because mysql_* is deprecated in not available in PHP 7.
$sql="select sub_id from table1 where id='".$id."' ";
if thats what you want.
I need to display in alphabetical order a list of name and surname (order by surname).
The problem is I can't do a ORDER BY in SQL query because I retrieve my users ID in one table and retrieve the informations in another table.
My PHP code:
$sql = "select id FROM $table_name";
$result = $wpdb->get_results($sql);
foreach ($result as $record) {
$id = $record->id;
$sql2 = "select field_name, field_val FROM $table_name2 where sub_id = $id";
$result2 = $wpdb->get_results($sql2);
foreach ($result2 as $record2) {
if($record2->field_name == "Nom :") {
$surname = ucfirst(stripslashes($record2->field_val));
}
if($record2->field_name == "Prénom :") {
$name = ucfirst(stripslashes($record2->field_val));
}
}
echo $name . " " . $surname . "<br/>";
}
Here the architecture of the second table:
f_id sub_id field_name field_val
127 19 Prénom : Philippe
128 19 Nom : Nailloux
129 20 Prénom : John
130 20 Nom : Drumond
Have you an idea how I can display my list ordered by surname alphabetically?
Thanks.
You can do the trick by using this SQL query :
SELECT t1.id AS user_id,
t2.field_val AS surname,
t3.field_val AS name
FROM $table_name t1
JOIN $table_name2 AS t2
ON ( t2.sub_id = t1.id
AND t2.field_name = 'Nom :' )
JOIN $table_name2 AS t3
ON ( t3.sub_id = t1.id
AND t3.field_name = 'Prénom :' )
ORDER BY t2.field_val
The query will return all the infos needed (user_id, surname and name) ordered by surname.
Use subqueries!
In your example, let's say you have 100 users.
In first query you get your users ids, then for each user you query database for one's data. That's 101 queries for a simple operation! What if you have 10 visits per seconds? That's more than 1000 queries.
There are many strategies (subquery, join, two queries with in () in second one) but in this case consider that:
SELECT
field_name, field_val
FROM
$table_name2
WHERE
sub_id IN(
SELECT
id
FROM
$table_name
) as sq1
ORDER BY field_val ASC;
Also consider using PHP PDO, or at least proper escaping of data you put in queries.