PHP/MySQL Echo from multiple tables - php

For a schoolproject we have to make a website that interacts with a myphp database. We want to pull data from two different tables in the database, but when we try to echo the data, only data from the first table is shown.
Out two tables are: TICKET and VISITOR
This is our code:
include 'login.php';
$sql = mysql_query("SELECT * FROM TICKET VISITOR ",$mysql)
or die("The query failed!");
mysql_close($mysql)
or die("Closing the connection failed!");
if (!$sql) {
echo 'Could not run query: ' . mysql_error();
exit;
}
echo "<br/>";
while ($row = mysql_fetch_row($sql)) {
echo $row[0];
echo " ";
echo $row[1];
echo " ";
echo $row[2];
echo "<br/>";
}

basically the comments say it already: you can use joins for this task. However I think what you need is a proper introduction into the options and what it all means, so let me try help you there:
First question: What is your problem? If you want to get data from two tables indepedently then what you have two do is to make to separate queries. You more or less run this:
//first run this query
$sql = mysql_query("SELECT * FROM TICKET ",$mysql)
//Run the query and process the data
//then run this query
$sql = mysql_query("SELECT * FROM VISITOR ",$mysql)
//Process this data, too
What you probably actually want to do is to get data from ONE table based on data from ANOTHER table. For example you want to get some data about users and in one table you have their email address and their street address and in the other table you have their name. So you JOIN both tables together based on some information (key) they both contain. So then you go from
TABLE 1: id | email | address
TABLE 2: id | firstname | lastname
To this form:
NEW TABLE: id | email | address | firstname | lastname
There are different kinds of joins. The code for this could look something link this:
$sql = mysql_query("SELECT table1.id, table1.email, table1.address, table2.firstname, table2.lastname FROM TABLE1 LEFT JOIN TABLE2 ON (table1.id = table2.id)",$mysql)
As said before joins are common and properly explained elsewhere. I find this a good tutorial but of course the mentioned documentation (https://dev.mysql.com/doc/refman/5.7/en/join.html) also explained it maybe a bit more condensed.

Option 1 join
SELECT * FROM TICKET INNER JOIN VISITOR ON NAME;
NAME here is a column name maybe id
Option 2 UNION
SELECT * FROM TICKET UNION SELECT * FROM VISITOR;

As per your code just insert comma (,) after first table. See below -
$sql = mysql_query("SELECT * FROM TICKET, VISITOR ",$mysql)
or die("The query failed!");
Also you can use the inner join if any foreign key used on second table.
Use also union.

Related

Get value from a table through an ID from another table

So basically I have a table : "task":
- id - morada -
- 1 - 1 -
And a "moradas" table:
- ID - Morada - CodPostal
- 1 - Street 1th - 1523
I want through task.Address from the task table get the Address and Postal Code from the moradas table. Right now I'm only showing the int number of the address in the trip table.
<td><?php echo $fetch['address']?></td>
The query I have now is this
$query = $conn->query("SELECT * FROM `task` WHERE status != 'Done' ORDER BY `id` ASC");
How do I get the values from the Address table with that int and show them in that echo?
You can user INNER JOIN for joining the two tables and get data from them.
INNER JOIN is used in this context assuming that each address id from database Trip corresponds to the actual address from database table: address.
SELECT T.Trip, A.Address, A.Postal_Code FROM Trip T
INNER JOIN address A ON T.Address = A.Address_ID
Note:
Your specified field names contain spaces.
I have added underscores instead of spaces in them.
Please put proper field names here.
Reference:
EDIT:
Updated Query as per updated question:
SELECT T.id, A.Morada, A.CodPostal FROM task T
INNER JOIN moradas A ON T.morada = A.ID
Updated according to your tables and columns.
If you want address and postal code where your task.id and moradas.id value matches, then you should join two tables and get address and postal code from moradas table -
Try this :-
$sql = "SELECT
task.id,
CONCAT(
moradas.`Morada`,
' ',
moradas.`CodPostal`
) AS address
FROM
task
LEFT JOIN moradas
ON (task.id = moradas.id)
WHERE task.`status` != 'Done'
ORDER BY task.id ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Address : " . $row["address"]."<br>";
}
} else {
echo "0 results returned";
}
$conn->close();
I assume that status column is in your task table
This query will show your address and postal code as one column address. If you want those into saperate columns, you can skip concat and select Morada and CodPostal separately.
Follow this scheme always as I will show you regarding your table names
If you have big data in MySQL like name. Postal code Id. And suppose you have addresses in another table witch related to another tracking services as example
$ret = mysql_query("select t2.id, t2.name, t2.phone, t1.address From t2 Left join t1 on t2.id = t1.id where t2.id = $id ")
// $id = is variable you get from php request like $_GET and id table should have index in MySQL then do the following
echo'<table>'
While ($row = mysql_fetch_assoc($ret) {
echo"<td>" .$row["addresse"]."<td>";
// repeat this for all retrieved data
}
echo '</table>'
Now you will have table in php output with all data in the query.
If query returns one record so table will have one result
If query have 10000 records as result so table will have 10000
You may put limit in query to retrieve 100 result per request

how to search all the tables of the database using php mysqli and display the answer

i am just beginning to learn mysqli and php ...so i am a novice.
i am trying to build a site for babynames.
i have a database of babynames in phpmyadmin. having tables country1, country2, country3....and so on. all the tables have the same columns id, name, meaning, gender and alphabet.
i print the names table using the following code using PHP and MYSQLI
$sql1="SELECT id,name, meaning, alpha, gender FROM $country WHERE gender='$gender' AND alpha='$alpha' $limit";
$query=mysqli_query($con,$sql1);
while($rows=mysqli_fetch_array($query)){
echo "<td><a href='meaning-of.php?name=$rows[name]'>".$rows['name']."</a></td>";
echo "<td>".$rows['meaning']."</td>";
echo "<td>".$rows['gender']."</td></tr>";
}
the name column is linked to meaning-of.php?name=$rows[name]
Now i want a code in PHP and MYSQLI to search all the tables(say 100 tables) of the database "babynames" for a particular name and display the same name and meaning please.
if the name exists more than once in the tables than all the names should be displayed along with their respective meanings please.
how do i search all the tables for a particular name and display using PHP and MYSQLI please.
i want to search the database by passing only the name variable into the address bar like this http://localhost/meaning-of.php?name=John or http://localhost/meaning-of.php?name=samson and find the meaning by searching all the tables of the database based on only the name please.like if the name is set than getting the name by $name=$_GET["name"]; and then search the whole database tables and display the meaning
is there a code something like this
SELECT *(all columns) FROM * (all the tables or the database name or all the databases) WHERE name=$name;
Please help. Thank You in advance please.
Keep all your data in a single table, adding a field country to distinguish the country.
This is the only proper answer to this question.
You can use UNION clause to get results from multiple select statements mysql doc
(SELECT * FROM county1 WHERE name=$name)
UNION
(SELECT * FROM county2 WHERE name=$name);
You can query all table names from information_schema
SELECT table_name FROM information_schema.tables
WHERE table_name LIKE "country%"
AND table_schema = "<name_of_country_database>";
So the full solution would be something like this:
$tables_sql = "SELECT table_name FROM information_schema.tables WHERE table_name LIKE 'country%' AND table_schema = 'babynames'";
$tables_query = mysqli_query($con,$tables_sql);
$sql1 = '';
while ($table = mysqli_fetch_array($tables_query)) {
if ($sql1 != '') {
$sql1 .= ' UNION ';
}
$sql1.= " (SELECT name, meaning FROM " . $table['table_name'] . " WHERE name='$name') ";
}
$query=mysqli_query($con,$sql1);
while($rows=mysqli_fetch_array($query)){
echo "<tr>";
echo "<td>".$rows['name']."</td>";
echo "<td>".$rows['meaning']."</td>";
echo "</tr>";
}

Combine data from two MySQL tables and echo results using PHP

I want to combine data from two MySQL tables and echo results using PHP. The first table is called TEST1 and has two fields(name, info1). The second table is called TEST2 and has also two fields(surname, info2). I would like to select name and surname where info1 = info2 and print name and surname in the same row using PHP. The code I have written so far is this but I don't think it's totally correct for both of the tasks I want it to to do.
$sql = "SELECT name, surname FROM TEST1, TEST2 WHERE info1 = info2";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo " - Name: " . $row["name"]. " - Surname: " . $row["surname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
So for example lets say that TEST1 has at name, info1 [(John,112233),(Luke,112244), (Ariana,112255)] and TEST2 has at surname, info2 [(Lala,112255), (Zara,112233), (Azon,112267), (Esora,112248)]. So I want it to display when I visit the webpage:
Name: John - Surname: Zara
Name: Ariana - Surname: Lala
or
Name: Ariana - Surname: Lala
Name: John - Surname: Zara
name, surname, info1, info2 are VARCHAR(64). There seem to be similar quetions but they aren't easy to understand especially for PHP and MySQL beginners who can't understand more advanced scripts cause they are specific to the asker's problem. So I tried to do it general in order to help more people and not just me. Could you please help me? Thanks in advance.
First of all the info data, if stored this way is becoming redundant and consuming more space in your database. If you have several names and surnames pointing to different persons, you just may take one particular name and surname or their id's in a different table and store the info corresponding to that person there.
Table1 = {tableOneId, firstName}
Table2 = {tableTwoId, lastName}
Table3 = {tableThreeId, tableOneId, tableTwoId, info}
This way you can store variety name and surname only once at a time and the information for each person redundantly. Now join these tables to get the desired information.
Select * from `table1`
inner join `table3` on `table1`.`tableOneId` = `table3`.`tableOneId`
inner join `table2` on `table3`.`tableTwoId` = `table2`.`tableTwoId`
Now you can select the name and surname the way you are doing from the result set.
I would add "tableOneId" (or whatever you like) as foreign key to second table that equals to the Id of the first - which will make it primary key. And as I understand that's the basic principle of relational databases.
So structure:
Table1 = {Id, firstName, info}
Table2 = {Id, lastName, info, tableOneId}
Assuming that firstName and lastName always refers to one unique person and you needed to divide this information to two different tables for some reason, you can implement this strategy to have unique identifier as Id in one table and tableOneId to second, to select unique data for one person from both tables.
And query could be something like this:
Select * from `table1`, `table2` where `table1`.`Id` = `table2`.`tableOneId`;

mysql_fetch_array and mysql_query return nothing on a call from two different tables

I have two tables books and users. books has a column id and users has a column called book_id. users table is populated by info about users who bought books from the store including the column book_id which referees to the id from books table.
My questions is, I have been trying to do this but with no success.
$query = mysql_query("SELECT * FROM books, users WHERE books.id='$id' OR users.id='$id' ");
while($row = mysql_fetch_array($query)){
$info .= $row[0] . " " . $row[1] . "<br/>";
}
echo $info;
Table books has some data but users is empty and I am getting nothing as an output!!! What am I missing??
Additional attempts:
SELECT * FROM books, users WHERE books.id='$id' returns empty results
SELECT * FROM books WHERE books.id='$id' returns 5 rows
You're missing the correct JOIN.
Table books has some data but users is empty and I am getting nothing as an output
Since users table contains no records you need to use LEFT | RIGHT or FULL join to get the result set, depending on what you're trying to accomplish.
Therefore try to change your query to
SELECT *
FROM books b LEFT JOIN
users u ON b.id=u.book_id
WHERE ...
Here is SQLFiddle

sql using LIKE clause : php

I'm trying to generate a list of events that a user is attending. All I'm trying to do is search through columns and comparing the userid to the names stored in each column using LIKE.
Right now I have two different events stored in my database for testing, each with a unique eventID. The userid i'm signed in with is attending both of these events, however it's only displaying the eventID1 twice instead of eventID1 and eventID2.
The usernames are stored in a column called acceptedInvites separated by "~". So right now it shows "1~2" for the userid's attending. Can I just use %like% to pull these events?
$userid = $_SESSION['userid'];
echo "<h2>My Events</h2>";
$myEvents = mysql_query("select eventID from events where acceptedInvites LIKE '%$userid%' ");
$fetch = mysql_fetch_array($myEvents);
foreach($fetch as $eventsAttending){
echo $eventsAttending['eventID'];
}
My output is just 11 when it should be 12
Change your table setup, into a many-to-many setup (many users can attend one event, and one user can attend many events):
users
- id (pk, ai)
- name
- embarrassing_personal_habits
events
- id (pk, ai)
- location
- start_time
users_to_events
- user_id ]-|
|- Joint pk
- event id ]-|
Now you just use joins:
SELECT u.*
FROM users u
JOIN users_to_events u2e
ON u.id = u2e.id
JOIN events e
ON u2e.event_id = e.id
WHERE u.id = 11
I'm a bit confused by your description, but I think the issue is that mysql_fetch_array just returns one row at a time and your code is currently set up in a way that seems to assume $fetch is filled with an array of all the results. You need to continuously be calling mysql_fetch_array for that to happen.
Instead of
$fetch = mysql_fetch_array($myEvents);
foreach($fetch as $eventsAttending){
echo $eventsAttending['eventID'];
}
You could have
while ($row = mysql_fetch_array($myEvents)) {
echo $row['eventID'];
}
This would cycle through the various rows of events in the table.
Instead of using foreach(), use while() like this:
$myEvents = mysql_query("SELECT `eventID` FROM `events` WHERE `acceptedInvites` LIKE '".$userid."'");
while ($fetch = mysql_fetch_array($myEvents))
{
echo $fetch['eventID'];
}
It will create a loop like foreach() but simpler...
P.S. When you make a MySQL Query, use backticks [ ` ] to ensure that the string is not confused with MySQL functions (LIKE,SELECT, etc.).

Categories