Mixing two tables that are interconnected - php

I have
$sql = "SELECT * FROM `address` WHERE ...some requirements...";
Among the results $sql has a column called addressid.
Then I iterate through all addressid and execute
$sql2 = "SELECT * FROM `products` WHERE ...some other requirements... AND addressid = $currentaddressid";
I choose * because I use several columns of each so this needs to be taken into account. The result is like
$valueone = $sql_assoc_array['name'];
$valuetwo = $sql2_assoc_array['nameproduct'];
It looks currently like this:
execute $sql
while ($sql is being fetched)
{
execute $sql2 with addressid
while ($sql2 is being fetched)
{
do stuff
}
}
How can I mix both into one command and give the processing necessary to mysql so the results of $sql2 come immediately?

Use inner join between address id of both the tables.
SELECT * from table1 a inner join table2 b where a.addressid=b.addressid.

Related

Add MySQL Count Column to PHP/HTML Table

I'm developing a website using HTML, PHP and MySQL to access a database. On one page I present a table with data from that database. This is some of the code I'm using:
$sql1 = "SELECT * FROM MyTable ORDER BY ID ASC";
$rs1 = mysqli_query($link,$sql1);
(...)
while($row1 = mysqli_fetch_assoc($rs1)) {
echo "<tr><td>".$row1['ID']."</td><td>".$row1['Field1']."</td><td></td><td>".$row1['Field2']."</td><td>".$row1['Field3']."</td></tr>\n" ;
}
Notice the empty <td></td>? That's because I want to have there the number of time a given ID appears on two other tables (there are foreign keys involved, obviously). I have sorted out the code I need for that:
$sql2 = "SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total";
However, I'm struggling with figuring out a way to add this result to the other table. Any help?
try with this.. it inserts the total to an table after selecting the count.
"INSERT INTO total_table (total)
SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total
WHERE cid = 2"

MySQL two conditions for two tables

I have a mysql query:
$query5 = mysql_query("SELECT * FROM `pages` WHERE (`id`='$switch' AND `rand`='$randID' AND `email`!='".$_SESSION['user']."') ");
And second:
$query5 = mysql_query("SELECT * FROM `pages_admin` WHERE (`pId`='$switch' AND `rand`='$randID' AND `admin`!='".$_SESSION['user']."') ");
I use a while loop to present data.
while($row = mysql_fetch_array($query5)) {}
I need one mysql query instead two.
If these tables are related you can JOIN them using the foreign key.
If I'm not mistaken this pId in the table pages_admin is a foreign key to the id on the table pages, is that correct?
If so, you could do something like this to you query:
"SELECT * FROM pages p
LEFT JOIN admin_pages ap on p.id = ap.pId
WHERE (`pId`=$switch AND `rand`=$randID AND `admin`!='{$_SESSION['user']}')"
Note that I've changed the syntax, instead of merging string you can use only one containing all variables you need.

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();
}

merge two query into one single query in sql

In my file there is already one query name query1 and I write another query name query2. The o/p of both query is userid. Now I want to find the common userid from these two queries. So is there any function for that?
The array_intersect() function generates an error.
Use a JOIN
$query1 = "SELECT userid FROM table1";
$query2 = "SELECT userid FROM table2 WHERE something = 10";
$joinQuery = "
SELECT a.userid
FROM ($query1) AS a
JOIN ($query2) AS b
ON a.userid = b.userid";

Select all data from a table and insert it to another table

I wanted to select all the data from one of my table and insert it to another table. I have this code but it wasn't working..This is what the phpMyadmin says "MySQL returned an empty result set (i.e. zero rows). (Query took 0.0010 seconds.)"
Here is my code:
if(isset($_POST['select_table']))
{
$select_table = mysql_real_escape_string($_POST['select_table']);
$query_select = "INSERT INTO pdf_table
SELECT * FROM $select_table";
$select_query = mysql_query($query_select,$connectDatabase);
}
Please ensure that both the tables have equal number of columns.
It is a good practice to use following way for inserting records with select query :-
INSERT INTO pdf_table (column_1, column_2) SELECT column_1, column_2 FROM $select_table
your sql query is like
INSERT INTO table2 (column_name(s)) SELECT column_name(s) FROM table1;
The approach you are using INSERT INTO pdf_table SELECT * FROM $select_table will give you only single row inserted from 1st table to another table.
As per your requirement you want all the records from 1st table should get insert in your pdf_table
So i will like to suggest try the following approach
May be this is what you looking for
if(isset($_POST['select_table']))
{
$select_table = mysql_real_escape_string($_POST['select_table']);
$select_query = mysql_query( "select * from $select_table ",$connectDatabase);
while ($row = mysql_fetch_array($select_query))
{
mysql_query( "insert into pdf_table values($row['column1'],$row['column2'],...,$row['columns']) ",$connectDatabase);
}
}
try this one :
if(isset($_POST['select_table']))
{
$select_table = mysql_real_escape_string($_POST['select_table']);
$query_select = " Create Table pdf_table ( SELECT * FROM $select_table); ";
$select_query = mysql_query($query_select,$connectDatabase);
}
but, this query will create new table "pdf_table".

Categories