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
Related
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.
I am creating a query and I used the LEFT JOIN to join two tables. But I'm having trouble in getting the fb_id value from the table, it gives me an empty result. Here is my code:
$sql = "SELECT * FROM tblfeedback a LEFT JOIN tblreply b ON a.fb_id = b.fb_id WHERE a.fb_status = 1 ORDER BY a.fb_id DESC";
$res = $con->query($sql);
....
....
The query above would give me a result like this :
I think that's why I don't get the fb_id value is because the last column is null. How do I get the value of fb_id from the first column? Thanks. I am really having trouble with this. I hope someone can enlightened my mind.
You should give an alias to the column in the parent table, because the column names are the same in both tables. When fetch_assoc() fills in $row['fb_id'], it gets the last one in the result row, which can be NULL because it comes from the second table.
SELECT a.fb_id AS a_id, a.*, b.*
FROM tblfeedback a
LEFT JOIN tblreply b ON a.fb_id = b.fb_id
WHERE a.fb_status = 1
ORDER BY a_id DESC
Then you can access $row['a_id'] to get this column.
More generally, I recommend against using SELECT *. Just select the columns you actually need. So you can select a.fb_id without selecting b.fb_id, and it will always be filled in.
Because you are using a left join, the 2 rows in your result set image are the rows from tblfeedback whose fb_id were not found in tblreply. We know this is true because all the tblreply columns in the result set are null.
With that said, its not real clear what you are asking for. If you are asking how you access the tblfeedback.fd_id column from your query via php, you can use the fetch_array method and use the 0 index.
$sql = "SELECT * FROM tblfeedback a LEFT JOIN tblreply b ON a.fb_id = b.fb_id WHERE a.fb_status = 1 ORDER BY a.fb_id DESC";
$res = $con->query($sql);
while($row = $res->fetch_array()) {
echo "fb_id: " . $row[0] . "<br>";
}
I have to select data from multiple tables based on single key value. I have one table called maintable where I will get all the ids from, and i have another 10 tables in the same database which have maintable.id as a foreign key. Now I have to retrieve data from the 10 tables where maintable.id matches in one single table.
The code I have tried is:
$sql = select id from maintable;
$runsql = mysql_query($sql);
while($sqlRow = mysql_fetch_array($runsql ,MYSQL_ASSOC)) {
for($i=1;$i<=10(This is another table count);$i++) {
$servSql = "select * from table.$i where ref_id = ".$sqlRow['id'];
$runServerSql = mysql_query($servSql);
while($serverRow = mysql_fetch_array($runServSql,MYSQL_ASSOC)) {
}
}
}
Try something like this in a join:
SELECT * FROM maintable m
INNER JOIN othertable o
ON m.id = o.id
That will select from both tables using an inner join ON the id column. You may want to look up a basic SQL tutorial to learn the basic types of joins you can use. Good luck!
I have two tables, one is a user log which stores the user by number
timestamp / user_id / transaction_id / amount
the other is a user table which has the users number and their full name
user_id / fullname
I want to select the entire user log and display it, but instead of displaying their number, display their full name from the other table, but I can't get it working. I keep modifying the sql and breaking it. Is there a way to accomplish this with php postgresql or should I use a function?
I keep getting an error that user_id is integer and the fullname is not
Please assist.
$query = "SELECT * FROM user_log
INNER JOIN user_staff
ON user_log.user_id=user_staff.user_name
ORDER BY user_log_id DESC LIMIT 200;";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", $myrow['timestamp'], htmlspecialchars($myrow['user_id']), htmlspecialchars($myrow['transaction_id']), htmlspecialchars($myrow['amount']));
}
?>
Use this query:
SELECT "timestamp", fullname, transaction_id, amount
FROM user_log
JOIN users USING (user_id)
Note that "timestamp" is a SQL reserved word and you should not use it for a column name. If you must use it, put it in double quotes.
Perhaps something like:
SELECT user_log.timestamp, users.fullname, user_log.transaction_id, user_log.amount
FROM user_log
INNER JOIN users
ON users.user_id=user_log.user_id
ORDER BY user_log_id
DESC LIMIT 200;
You can read up on SQL Joins here: http://www.w3schools.com/sql/sql_join.asp
I am trying to add data into 3 table using PHP, atm I can only view the results of the tables that are joined .
RESULTS QUERY
$sql = mysql_query("SELECT PART_ID, PART_DESC, SERIAL_NUM, PART.RACK_NUM, PART.PART_TYPE_ID, PART_TYPE_DESC, LOCATION
FROM PART
INNER JOIN PART_TYPE ON PART.PART_TYPE_ID = PART_TYPE.PART_TYPE_ID
INNER JOIN RACK ON RACK.RACK_NUM = PART.RACK_NUM
This will get all the rows from the PART table, and for each of the rows we find, match that row to a row in the PART_TYPE table (the condition being that they have the same PART_TYPE_ID). If no match between the PART and PART_TYPE tables can be found for a given row in the PART table, that row will not be included in the result.
My Insert Query This is where im having trouble
How do I add the data to the PART_ID, PART_TYPE and RACK tables?
<?php
// Parse the form data and add inventory item to the system
if (isset($_POST['PART_ID'])) {
$id = mysql_real_escape_string($_POST['PART_ID']);
$PART_DESC = mysql_real_escape_string($_POST['PART_DESC']);
$SERIAL_NUM = mysql_real_escape_string($_POST['SERIAL_NUM']);
$RACK_NUM = mysql_real_escape_string($_POST['RACK_NUM']);
$PART_TYPE_ID = mysql_real_escape_string($_POST['PART_TYPE_ID']);
$LOCATION = mysql_real_escape_string($_POST['LOCATION']);
$PART_TYPE_DESC = mysql_real_escape_string($_POST['PART_TYPE_DESC']);
// See if that product name is an identical match to another product in the system
$sql = mysql_query("SELECT PART_ID FROM PART WHERE PART_ID='$id' LIMIT 1");
$productMatch = mysql_num_rows($sql); // count the output amount
if ($productMatch > 0) {
echo 'Sorry you tried to place a duplicate "Product Name" into the system, click here';
exit();
}
// Add this product into the database now
**$sql = mysql_query("INSERT INTO PART (PART_ID, PART_DESC, SERIAL_NUM, RACK_NUM, PART_TYPE_ID)
VALUES('$id','$PART_DESC','$SERIAL_NUM','$RACK_NUM','$PART_TYPE_ID')") or die (mysql_error());**
header("location: inventory_list.php");
exit();
}
?>
Micheal if I understood your problem you just need to do 2 other SQL INSERT to add data in the other table
$sql = mysql_query("INSERT INTO PART (PART_ID, PART_DESC, SERIAL_NUM, RACK_NUM, PART_TYPE_ID)
VALUES('$id','$PART_DESC','$SERIAL_NUM','$RACK_NUM','$PART_TYPE_ID')") or die (mysql_error());
$currentID = mysql_inserted_id();
$sql2 = mysql_query("INSERT INTO PART_TYPE [..]");
$sql3 = mysql_query("INSERT INTO RACK [..]");
You can use $currentID if you need the ID of the last record inersted into PART
But still I strongly suggest you to learn PDO http://php.net/pdo for sql
your table management is wrong, you never use arrows just to show that you are joining it with that table from this table, but rather from the key in first table to foreign key in the second table, that's what i would start from, maybe a better idea would be to join them using JOIN look up in google how joins are working, that may be the cause...
I agree with #yes123, that is the correct way to insert into tables, if you have a program called heidisql then use it, because there is a window to run your queries... that way to test if it is properly written also use mysql_error.
Debug, debug, and one more time debug your code.
Your tables are not correctly designed.
Try this table structures .
In your base table Part. -
The columns in this should be:
Part_id
part_desc
serial_num
The part_type should have following columns:
part_type_id
part_type_desc
part_id -> foreign key to the parent table
The rack table should be:
Rack_num
location
part_id -> foreign key to the parent table.
So your select query to get all the part related information would be:
$sql="select * from part join part_type pt on tp.part_id=part.part_id join Rack_num rn on rn.part_id=part.part_id";
With this structure the data remains normalized. And is flexible, so if the parts are on multiple racks you just go to the rack table and add and new rack number and the part id.