how to call 2 tables from mysql database with php [duplicate] - php

This question already has answers here:
sorting by high-low price with mysql data
(2 answers)
Closed 7 years ago.
i have 2 tables
page and orders.
$ww = mysqli_query($database->connection,"SELECT * FROM `page`
WHERE `owner` = '$session->u_id'");
while($o = mysqli_fetch_array($ww))
{
$owner = $o['id'];
$result = mysqli_query($database->connection,"SELECT * FROM `orders`
WHERE `owner` = '$owner' ORDER BY id DESC");
while($row = mysqli_fetch_array($result))
{
echo "taxi =".$o['naam']."<br>";
echo $row['id']."<br>";
}
}
the output is
23
21
20
17
26
25
24
22
19
Question is How can i sort high to low like
26
25
24
23
22
21
....

You need to run just one query when selecting from orders, not one query per page (BTW, it helps if you tabulate properly, people can see this then). Even better is to just run one query using a join.
You'll need to post your table structure before we can write any query.

1) you can use inner join to write the query if id column of second table won't be null otherwise use left join
SELECT * FROM `orders` inner join page on orders.id = page.id where owner = $session->u_id;
2) you can use your first query as sub query and put it in second one like this
SELECT * FROM `orders` WHERE exists (SELECT page.id FROM `page` WHERE `owner` = '$session->u_id' and orders.id=page` WHERE `owner` = '$session->u_id' and orders.id= )ORDER BY id DESC.id ) ORDER BY orders.id DESC
Note : if any syntax error is found the forgive me :)-

Related

SQL query to get all posts from a table in the db but max 5 entrys from a specific user? [duplicate]

This question already has answers here:
Using LIMIT within GROUP BY to get N results per group?
(14 answers)
Closed 2 years ago.
I´m building a php-blog system and want to display all posts but max five from each user on the start page.
I thinking of do this with a query in the database, but I´m lost on how to do that.
The count() function I guess will come in handy, but can somebody help me
This is my function today, and I just whant to improve it to get max five posts from each user
protected function getAllPostsDB() {
$sql = "SELECT recipes.Recipe_ID, recipes.Title, recipes.Short_description, recipes.Step_by_step,
recipes.create_date, recipes.last_mod_date, recipes.Portions, recipes.imgPath, users.Username
FROM recipes
JOIN users
ON recipes.User_ID = users.User_ID
ORDER BY recipes.create_date DESC";
$stmt = $this->connect()->query($sql);
/* fetch all is already set to associative array*/
$result = $stmt->fetchAll();
return $result;`
If you are running MySQL 8.0, just use window functions:
SELECT r.Recipe_ID, r.Title, r.Short_description, r.Step_by_step,
r.create_date, r.last_mod_date, r.Portions, r.imgPath, u.Username
FROM (
SELECT r.*, ROW_NUMBER() OVER(PARTITION BY User_ID ORDER BY create_date DESC) rn
FROM recipes r
) r
INNER JOIN users ON r.User_ID = u.User_ID
WHERE r.rn <= 5
ORDER BY r.create_date DESC
This gives the last five recipes per user, as designated by column create_date. You can change the ORDER BY clause of ROW_NUMBER() to some other column or set of columns if you want another sort rule.

SUM points from table

I have table with files and their have their points/score. Iam trying to summarize those points and print it. I have a where clause for id files, but if I select random files it has same score as others like where clause isnt working.
$id is correct for each file.
This is my query:
$result = mysql_query("SELECT *,SUM(body) FROM soubory, users, hodnoti WHERE
soubory.id='".$id."' AND soubory.users_id = users.id");
hodnoti table
users_ID soubory_id body
14 44 7
15 44 9
And now, if there is no record (in table hodnoti) for soubory_id = 45 the result is same as for 44 despite of where clause.
users table
id nick
14 user1
15 user2
soubory table
id nazev users_id
44 file1 14
45 file2 14
That query should help me print this:
Who uploaded, nazev(title) of the file and then points. But if file2 has no record in table hodnoti, still has score of file1. Hope it helps.
$sql = "SELECT *, SUM(hodnoti.body) as sum FROM soubory
INNER JOIN users ON soubory.users_id = users.id
INNER JOIN hodnoti ON soubory.id = hodnoti.soubory_id
WHERE soubory.id='".$id."' ";
$result = mysql_query($sql);
This query works for me. When i set id=44 and get a result and when set id=45 and get all null value. i have attached two result image. I have just create table and insert your given data and run query on phpmyadmin sql tab query box. You can try this for check your query works or not.
Use JOIN.
$sql = "SELECT *, SUM(hodnoti.body) as sum FROM soubory
INNER JOIN users ON soubory.users_id = users.id
INNER JOIN hodnoti ON soubory.id = hodnoti.soubory_id
WHERE soubory.id='".$id."' ";
$result = mysql_query($sql);
SUGGESTION: Above is a direct answer for your question. Avoid using mysql_* statements as they are deprecated now. Learn mysqli_* or PDO and start implementing that.

how to fetch content from one table according to results from another table in mysql

I have two mysql tables with content one is called petitions
{"success":1,"petitions":[{"id":"6","name":"should he go","timestamp":"2013-10-26 03:02:44"},{"id":"3","name":"Olara Otunu should get married","timestamp":"2013-10-24 14:33:53"},{"id":"4","name":"Teachers deserve 30 not 20 salary rise","timestamp":"2013-10-24 14:33:53"},{"id":"5","name":"Prostitution should be banned","timestamp":"2013-10-24 14:33:53"},{"id":"1","name":"Has Jennifer Musisi done great work for Kampala","timestamp":"2013-10-24 14:32:58"},{"id":"2","name":"Do lecturers deserve 100% salary increase","timestamp":"2013-10-24 14:32:58"}]}
and the other table is called petition_response
{"success":1,"petition_response":[{"id":"2","petitionID":"2","yes":"0","no":"1","memberID":"14","timestamp":"2013-11-02 08:36:20"},{"id":"1","petitionID":"1","yes":"1","no":"0","memberID":"14","timestamp":"2013-11-01 21:26:02"}]}
I need to select * petitions which have no response in the petition_response. But if they have any response in the petition_response table then the memberID should not be equal to 14
I have tried this code below but its not working
$result = mysql_query("select * from petition_response where memberID='14' order by timestamp DESC", $db->connect());
while($row = mysql_fetch_assoc($result)){
$id = $row['id'];
$result2 = mysql_query("select * from petitions where id != '$id' order by timestamp DESC", $db->connect());
}
return $result2;
You're looking to effect an anti-join, for which there are three possibilities in MySQL:
Using NOT IN:
SELECT *
FROM petitions
WHERE id NOT IN (
SELECT petitionID
FROM petition_response
WHERE memberID = 14
)
Using NOT EXISTS:
SELECT *
FROM petitions p
WHERE NOT EXISTS (
SELECT *
FROM petition_response r
WHERE r.petitionID = p.id
AND r.memberID = 14
LIMIT 1
)
Using an OUTER JOIN:
SELECT p.*
FROM petitions p
LEFT OUTER JOIN petition_response r
ON r.petitionID = p.id AND r.memberID = 14
WHERE r.petitionID IS NULL
See them on sqlfiddle.
According to #Quassnoi's analysis:
Summary
MySQL can optimize all three methods to do a sort of NESTED LOOPS ANTI JOIN.
It will take each value from t_left and look it up in the index on t_right.value. In case of an index hit or an index miss, the corresponding predicate will immediately return FALSE or TRUE, respectively, and the decision to return the row from t_left or not will be made immediately without examining other rows in t_right.
However, these three methods generate three different plans which are executed by three different pieces of code. The code that executes EXISTS predicate is about 30% less efficient than those that execute index_subquery and LEFT JOIN optimized to use Not exists method.
That’s why the best way to search for missing values in MySQL is using a LEFT JOIN / IS NULL or NOT IN rather than NOT EXISTS.
$query = "
SELECT *
FROM petition_response pr
LEFT
JOIN petitions p
ON p.id = pr.id
WHERE pr.memberID = 14
AND p.id IS NULL
ORDER
BY pr.timestamp DESC;
";

Is it possible to make query result in running another query? [duplicate]

This question already has an answer here:
Using results from one MySQL query in another query in a PHP Envirnment
(1 answer)
Closed 10 years ago.
I have this query:
$aircraft_query = "SELECT COUNT(aircraft) as total, aircraft FROM db_pireps WHERE pilotid = $pilotid GROUP BY aircraft ORDER BY total DESC LIMIT 6";
$planes = DB::get_results($aircraft_query);
And using a foreach statement, I can generate rows in a table to show aircrafts flown by a pilotid. However, I'd like now the RESULT to link to another table and extract data from there, such as aircraft type, in a fullname column.
I have this: <?php echo $aircraft->fullname; ?> but that data is in a different table. So, if aircraft was 30, it would access 30th record in db_aircrafts table and take the fullname column. How can I do this? Is it even possible?
What you need is called a table JOIN (also see JOIN in MySQL manual):
SELECT
COUNT(a.aircraft) as total
, a.aircraft
, b.fullname AS aircraft_name
FROM db_pireps AS a
JOIN db_aircraft AS b
ON a.aircraft = b.id
WHERE pilotid = {$pilotid}
GROUP BY aircraft
ORDER BY total DESC
LIMIT 6
You should use SQL Joins.
SELECT COUNT(A.aircraft) as total, A.aircraft, B.fullname
FROM db_pireps A
LEFT JOIN pilot_data_table B ON A.pilotid = B.id
WHERE A.pilotid = $pilotid
GROUP BY A.aircraft ORDER BY total DESC LIMIT 6

MYSQL Order then find out order number [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
MySQL get row position in ORDER BY
I have a table of users and I want to order them by a column named crown. I then wanted to find out where they are in the list but not totally sure on how to do it. I have tried to Google it but not totally sure on what to type in. (Crown has INT input.)
So I have the first line:
mysql_query("SELECT * FROM users ORDER by crown DESC");
How would I then find out where a user is in the list while ordered by crown?
Thanks in advance.
I'd do something like this, assuming you can get the user's crown value.
SELECT `user_var_you_want`,
(SELECT COUNT(*) FROM `users` WHERE `crown` > $user_crown_value)+1 AS `position`
FROM `users`
WHERE `user_var_you_want` = $search_value
Or if you can't get their crown value:
SELECT `user_var_you_want`,
(SELECT COUNT(*) FROM `users` WHERE `crown` > (SELECT `crown` from `users` WHERE `user_var_you_want` = $search_value)+1) AS `position`
FROM `users`
WHERE `user_var_you_want` = $search_value

Categories