Select data from table using data from another table - php

I have 2 tables, one is called companies (with columns: title, finance, address, phone....) and the other is called investments (with columns: title, budget....).
The title value is same in both tables example: google inc as title is stored in both tables.
All I want to do is display data from table "investments" to a page called companies-profile using title as key.
companies-profile page shows data based on id that I get from another page (where all companies are displayed).
I use this code:
<?php
$var1 = "SELECT title
FROM companies
WHERE idcompanies='$ID'";
$result2 = mysqli_query($conn, "SELECT budget
FROM n4399
WHERE title='{$var1}'")
or die(mysqli_error($conn));
$row2 = mysqli_fetch_array($result2);
echo $row2['budget'];
?>
$conn is declared and database conection is ok
i m getting:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '2'" at line 1
2 is the id that is selected by the user
Using xamp

You could use a single query
SELECT budget
FROM companies
INNER JOIN n4399 ON companies.Title=n4399.title
WHERE companies.id = ?
and using a proper prepared statement and binding
$stmt = $conn->prepare("SELECT budget
FROM companies
INNER JOIN n4399 ON companies.Title=n4399.title
WHERE companies.id = ?");
$stmt->bind_param("i", $ID);
$stmt->execute();
//
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
echo $row['budget'];
}

You are trying to execute the following sql sentence:
SELECT budget
FROM n4399
WHERE title='SELECT title
FROM companies
WHERE idcompanies='$ID''
Either of two: or you first execute the firs sentence (select title from companies...) getting the effective title of the company or you can change your select into this:
SELECT budget
FROM n4399
WHERE title in (SELECT title
FROM companies
WHERE idcompanies='$ID')
So that this select can return all the values that have matching titles in the second select.

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

Selecting from two tables issue

This is was am trying to do table A has all profession categories & table B has users details.i want select from the 2 tables and match up categories selected,if user select 'web developer' from a dropdown of categories.i want to display list of users under web developer.
<?php
$q = intval($_GET['q']);
//select state of the two tables here
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
?>
///
<?php }?>
it's unclear from the question and lack of database details what and how to do the sql query ( which I think is what you are actually asking for ) but something along these lines perhaps.
select * from `tableB` b
left outer join `tableA` a on a.`professionid`=b.`professionid`
where a.`profession`='Web Developer'

Searching records in a relational database

Scenario:
I am working on a PHP/MySQLi aplplication where I have got 2 tables attendance and students .
students has fields: student_id, fullname, phone,email,gender, department and level.
attendance table has fields: attendance_id, student_id, department_id, level_id.
I was able to fetch all students whose records are in the attendance table according to their department and level.
Question:
Let's assume that I was able to fetch all students whose records are in the attendance table and are in 200L (with level_id, 2) computer science (with department_id, 4) department, if the list of the students present are much and it was paginated and I want to search for a particular student's fullname that's in attendance table in reference to student's table.
How will the SQL query be like? I tried the following query which didn't work.
$search_query = mysqli_query($db_connect, "SELECT *FROM attendance WHERE student_id=\"SELECT student_id FROM students WHERE fullname LIKE '%$student_fullname%'\";
Please help.
Try this query:
SELECT attendance.*
FROM `students`
INNER JOIN `attendance`
ON `attendance`.`student_id` = `students`.`student_id`
WHERE `students`.`fullname` LIKE `%$student_fullname%`
I know that may look back-to-front at first, but I prefer to structure the SQL to show the strong selector (the LIKE filter) in the WHERE clause. If you do not like that, you can get the same result like this:
SELECT attendance.*
FROM `attendance`
INNER JOIN `students`
ON `students`.`student_id` = `attendance`.`student_id`
AND `students`.`fullname` LIKE `%$student_fullname%`
Note that this second version does NOT have a WHERE clause - always put filters on the RHS of a join in the join's ON clause, because otherwise outer joins will not behave correctly.
The SQL query you are looking for is:
select * from attendance join students on attendance.student_id = students.student_id where students.fullname like '%NAME%'
so in PHP you would need something like:
$query_string = "select * from attendance join students on attendance.student_id = students.student_id where students.fullname like '%$student_fullname%'";
$search_query = mysqli_query($db_connect, $query_string);
I would recommend you to have a look at prepared statements though, to prevent SQL injection: http://php.net/manual/en/mysqli.prepare.php
/* create a prepared statement */
$query_string = "select * from attendance join students on attendance.student_id = students.student_id where students.fullname like ?";
if ($stmt = $mysqli->prepare($query_string)) {
$stmt->bind_param("s", $student_fullname);
$stmt->execute();
$result = $stmt->get_result();
while ($myrow = $result->fetch_assoc()) {
// use your $myrow array as you would with any other fetch
printf("%s found in attendance record ID: %s\n", $student_fullname, $myrow['attendance_id']);
}
$stmt->close();
}

How to Display data from 2 different Database

I have an hard time to retrieve data in a table from MySQL database.
I have 2 different database that cannot be merge but there is a table in the first database that is identical to the second database.
Description Database 1 table: areas : ar_id, name, password.
Description Database 2 table: user : id, username, pass.
Now, When the user Login, He logs in the 2nd database. in each page of the user I have use $_SESSION['username'] to call the username.
Importantly, In every page, I have table that displays data from different tables using the username in the 2 Database; this else the SQL to be specific and only provide each user with their own information. and That's Ok. This is the SQL:
SELECT Client_table.Name, Client_table.Client_Id FROM Client_table, user WHERE user.username = '" . $_SESSION['username'] . "' AND Client_table.Branch = user.area Order by Name ASC
In one of the page, I totally using the 1st Database with this SQL to display data in the table :
select site_id, site_name from sites WHERE srep_id = 5
AND status = 1 or status = 2
order by site_name asc
QUESTION: I would like to display this SQL data in a table by using the username or id from the 2nd database BUT is returns Empty Table (I include both Database in this page). This is my current SQL but still not displaying anything:
SELECT cl.client_name, st.site_id, st.site_name
FROM Database1.sites st
JOIN Database2.user u ON u.id = st.ar_id
JOIN Database1.clients cl ON cl.client_id = st.client_id
WHERE Database1.st.name = '".$_SESSION['username']."'
AND st.status > 0
ORDER BY st.site_name ASC
NOTE: This is a major problem that took me almost a week!
Please some one help!
I think I have an answer.
After browsing and doing some search, I sound that I can make use of the $_SESSION here and Also, This was my final SQL Statement that Helped me to Connect the 2 Database from the same SQL Statement by using variable in PHP Script.
session_start();
$result = mysql_query("SELECT cl.client_name, st.site_id, st.site_name, ar.rep_id
FROM sites st
JOIN areas ar ON ar.rep_id = st.srep_id
JOIN clients cl ON cl.client_id = st.client_id
WHERE st.srep_id = '".$_SESSION['userarea']."'
AND st.status > 0
ORDER BY st.site_name ASC");

PHP/ MYSQL Inserting Data Into Multiple Tables

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.

Categories