I have two tables:
Table 1
contacts
id
email
name
lastname
postcode
straat
huisnr
woonplaats
klantnummer
bsn
land
debiteurnummer
Table 2
contacts_group
id
mail
group_name
How can I select and order this 2 tables in one query. I've tried union and left join, but did not work.
$result = mysqli_query($database->connection,
"SELECT *
FROM contacts
WHERE owner = '$session->username'
ORDER BY name ASC ,bedrijfsnaam ASC")
or die(mysqli_error());
while($roww = mysqli_fetch_array($result)){
echo $roww['email'];
echo $roww['name'];
}
Table contacts_group:
$result = mysqli_query($database->connection,
"SELECT *
FROM contacts_group
WHERE owner = '$session->username'
ORDER BY group_name ASC")
or die(mysqli_error());
while($roww = mysqli_fetch_array($result)){
echo $roww['mail'];
echo $roww['group_name'];
}
Escape your variables. You should not put the php variable unescaped in sql query. You can suffer from sql injections.
If you want to join two tables by foregin key you can do:
SELECT * FROM contacts, JOIN contacts_group ON contacts_group.id = contacts.group_id
WHERE contacts.owner = '$session->username' ORDER BY contacts.name
But you are missing group_id in contacts table or some foregin key to connect two tables.
Before do it read this topic, after try to use mysql join construction
Related
I was trying to fetch data from multiple tables in the Database and to Fetch data I tried using UNION ALL ... but I wasn't able to work on it.
$sqll = "SELECT * FROM msr_bills WHERE mobile='94825XXXX' UNION ALL
SELECT * FROM hirisave_bills WHERE mobile='94825XXXX'";
$sql = mysqli_query($conn,$sqll);
while($row = mysqli_fetch_array($sql)){
echo $row['name'];
echo $row['mobile'];
}
I am getting this error:
The used SELECT statements have a different number of columns
Maybe try to use LEFT JOIN like this:
$sqll = "SELECT * FROM `msr_bills` mb LEFT JOIN `hirisave_bills` hb ON hb.`mobile` = mb.`mobile` WHERE mb.`mobile` = '94825XXXX'";
You have all columns from two tables or nulls from hirisave_bills if there is no such mobile number.
you have diferent number of columns in your tables. try to select same number of columns
For example:
$sqll = "SELECT id, mobile FROM msr_bills WHERE mobile='94825XXXX' UNION ALL SELECT id, mobile FROM hirisave_bills WHERE mobile='94825XXXX'";
I develop a chat system where students and staff can exchange different messages. I have developed a database where we have five tables: the staff table, the student, the message and two mapping tables the staff_message and stu_message. These tables contain only the student/staff id and the message id.
My problem is that I cannot order the messages. I mean that I cannot figure out how can I make one SQL statement that will return all messages and be ordered by for example the ID. The code that I have made is this:
$qu = mysqli_query($con,"SELECT * FROM stu_message");
while($row7 = mysqli_fetch_assoc($qu)){
$que = mysqli_query($con, "SELECT * FROM student WHERE studentid =".$row7['stu_id']);
while($row8 = mysqli_fetch_assoc($que)) {
$username = $row8['username'];
}
$query3 = mysqli_query($con, "SELECT * FROM message WHERE id=".$row7['mid']);
while($row6 = mysqli_fetch_assoc($query3)) {
echo $row6['date']."<strong> ".$username."</strong> ".$row6['text']."<br>";
}
}
$query2 = mysqli_query($con, "SELECT * FROM staff_message");
while($row3 = mysqli_fetch_assoc($query2)){
$query = mysqli_query($con, "SELECT * FROM staff WHERE id =".$row3['staff_id']);
while($row5 = mysqli_fetch_assoc($query)) {
$username = $row5['username'];
}
$query3 = mysqli_query($con, "SELECT * FROM message WHERE id=".$row3['m_id']);
while($row6 = mysqli_fetch_assoc($query3)) {
echo $row6['date']."<strong> ".$username."</strong> ".$row6['text']."<br>";
}
}
?>
The result is different from that I want. To be more specific first are shown the messages from the students and then from the staff. My question is, is there any query that it can combine basically all these four tables in one and all messages will be shown in correct order? for example by the id?
Thank you in advance!
First, use JOIN to get the username corresponding to the stu_id or staff_id, and the text of the message, rather than separate queries.
Then use UNION to combine both queries into a single query, which you can then order with ORDER BY.
SELECT u.id, u.text, u.username
FROM (
SELECT s.username, m.text, m.id
FROM message AS m
JOIN stu_message AS sm ON m.id = sm.mid
JOIN student AS s ON s.id = sm.stu_id
UNION ALL
SELECT s.username, m.text, m.id
FROM message AS m
JOIN staff_message AS sm ON m.id = sm.m_id
JOIN staff AS s ON s.id = sm.staff_id
) AS u
ORDER BY u.id
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
one variable row inside another variable row
I have script something like -
$sql = "SELECT * FROM `users`"
$q = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($q);
$sql1 = "SELECT * FROM `other_table`";
$q1 = mysql_query($sql1) or die(mysql_error());
$row1 = mysql_fetch_array($q1);
$item = $row1[$row['username']];
How can I set one variable row inside another, since it don't work. Basically, I need to select username, and then select column with user username from other table, in which is written user points.
I was thinking about adding -
$sql = "SELECT * FROM `users`"
$q = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($q);
$sql1 = "SELECT `".$row['username']."` FROM `other_table` WHERE `uid` = 1";
$q1 = mysql_query($sql1) or die(mysql_error());
$row1 = mysql_fetch_array($q1);
$item = $row1[xxxxxxxxxx]; // DONT KNOW HOW TO DEFINE IT, so it takes out found variable (there is only one).
I have question already, but not with full info, and I don't know how to delete it :(!
Here is my table -
Users
'id'--'name'
'1'--'Bil'
'2'--'Conor'
'3'--'Ilian'
Other_table (which holds points for users)
'id'--'Bil'--'Conor'--'Ilian'
'1'--'2'--'3'--'55'
Don't ask, why I don't hold the points in the same table, since if I could, I would do that ;)!
It sounds like you need to redesign the tables to start with, I would suggest a table structure like this:
Table Users
ID | Name
Table Points
UserID | Points
This way you can add a foreign key constraint between the tables and then do a simple join query like:
SELECT U.Name, P.Points FROM Users AS U INNER JOIN Points AS P ON U.ID = P.UserID
Then your php code would look like:
$sql = "SELECT U.Name, P.Points FROM Users AS U INNER JOIN Points AS P ON U.ID = P.UserID";
$q = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($q);
Here are the create table queries for you:
CREATE TABLE Users (ID INT NOT NULL AUTO_INCREMENT,
Name VARCHAR(50) NOT NULL, PRIMARY KEY (ID))
CREATE TABLE Points (UserID INT NOT NULL, Points INT,
FOREIGN KEY(UserID) REFERENCES Users(ID) ON UPDATE CASCADE ON DELETE CASCADE)
EDIT:
This should allow you to get the value (NOTE: untested as I don't have a php/mysql instance to mess with currently), but for a more robust solution you really should look into redesigning your table schema.
$userName = $row['username'];
$sql1 = "SELECT [". $userName ."] FROM other_table WHERE [uid] = 1";
$q1 = mysql_query($sql1) or die(mysql_error());
$row1 = mysql_fetch_array($q1);
$item = $row1[$userName];
SELECT users.id, users.name, other_table.points FROM users LEFT JOIN other_table ON other_table.name=users.name
<?php
include('includes/config.php');
$topi = $_GET['id']; //id of url
mysql_select_db("ban", $con);
$query = "SELECT * FROM `basic` WHERE id = '$topi' LIMIT 0, 30";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
$aa = $row['item'];
$cc = $row['moreinfo'];
$dd = $row['contactinfo'];
$ff = $row['id'];
In this script, I get information from the table basic, but I want to retrieve data from another table named users. How can I retrieve data from two tables at once?
users table consists of following columns:
email
username
ID
You need to JOIN the two tables on a common value, called a foreign key. Once you've posted the structure of the users table as requested in the comments, I can provide a more complete example.
EDIT: See example. This calls explicit column names instead of SELECT *.
$query = "SELECT
basic.id,
basic.item,
basic.moreinfo,
basic.contactinfo,
users.email,
users.username
FROM basic JOIN users ON basic.id = users.id
WHERE id = '$topi'
LIMIT 0 , 30";
You would use a JOIN onto the other table.
$query = "SELECT *
FROM basic b
JOIN users u ON b.user_id = u.user_id
WHERE id = '$topi'
LIMIT 0, 30";
Something like that, but based on your fields.
Please Note: the ON clause specifies what you will be looking for a match on.
I have a script designed to print out values of students who have accrued more than 3 tardies. I want this script to print out both the student name, and the amount of times they've been tardy, but so far I've been only able to print out their names with the following script:
$sql = "select DISTINCT StudentID,classid,date from attendance_main where status = 'Tardy' AND classid like '%ADV%'";
$result = mysql_query($sql) or die (mysql_error());
while($row=mysql_fetch_array($result)) {
$studentid = $row['StudentID'];
$sql2 = "select distinct StudentID,classid,date from attendance_main where StudentID = '$studentid' AND status = 'Tardy' AND classid like '%ADV%'";
$result2 = mysql_query($sql2) or die (mysql_error());
while($row2=mysql_fetch_array($result2)) {
$tardycount = mysql_num_rows($result2);
$studentid = $row2['StudentID'];
if($tardycount >= 3) {
$sql3 = "select * from students where rfid = '$studentid'";
$result3 = mysql_query($sql3) or die (mysql_error());
while($row3=mysql_fetch_array($result3)) {
$fname[] = $row3['fname'];
}
}
}
}
$newdata = array_unique($fname);
foreach ($newdata as $value) {
echo $value;
}
I can't think of how to intuitively do this. Keeping it all in the while loop didn't work (I had multiple results coming up for the same students despite requesting unique entries) so using array_unique was the only method I could think of.
Thanks for any help!
Something like this:
SELECT
attendance_main.StudentID,
students.fname,
COUNT(attendance_main.*) AS `times_tardy`
FROM
attendance_main
INNER JOIN
students
ON
attendance_main.StudentID = students.rfid
WHERE
attendance_main.status = 'Tardy'
AND
attendance_main.classid like '%ADV%'
GROUP BY
attendance_main.StudentID
HAVING
`times_tardy` > 3
Joining the two tables gets you the tardy count and student's name in one query, and the GROUP BY and HAVING clause that get you only the students with more than 3 tardy entries.
You can (and should) do almost everything in SQL. It should look something like this.
select StudentID, classid, date count(*)
from attendance_main
where status = 'Tardy' AND classid like '%ADV%'"
left join student on student.rfid = attendance_main.StudentId
group by StudentId
having count(*) > 3;
Here's how it works.
select the results you want to work with:
select StudentID, classid, date count(*)
from attendance_main
where status = 'Tardy' AND classid like '%ADV%'"
Join the students to your result set on the common id
left join student on student.rfid = attendance_main.StudentId
group everything by student. We use count(*) to get the number of items. We know we're only dealing with tardies because of the where clause in the select.
group by StudentId
limit the results to only tardies above 3 with the having claues (this is like a where clause for the group by)
having count(*) > 3;