Searching records in a relational database - php

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

Related

Select data from table using data from another table

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.

Combine rows into columns in mysql

I have a table customer(id_customer, email, id_default_group) and product_list(id_item,id_product,id_group,product_title,image,html_product,price,reduced_price,reduction_pourcentage) and banner_list(id_banner,id_group,html)
I would like to join the table with the id_group
I would like to get all email from customer and all informations from product_list and banner_list where customer.id_group = id_group from product_list and banner_list,
All this i can get it from a simple sql query, but i would like to get the result array in a particular form,
Expected result row:
email,
product_title_1,image_1,html_product_1,price_1,reduced_price_1,reduction_pourcentage_1, product_title_2,.....,reduction_pourcentage_2, product_title_n, .....,reduction_pourcentage_n,banner_list.html_1,banner_list.html_2,banner_list.html_z
I tried with this php code, but it doen't give me what i want
for($i=1;$i<$nb_product;$i++){
$sql = 'SELECT c.`email`
FROM `'._DB_PREFIX_.'customer` c
UNION ALL
Select
pl.title,pl.image,pl.html,pl.price,pl.price_barre,pl.pourcentage
FROM `'._DB_PREFIX_.'product_list` pl
WHERE 1 '.Shop::addSqlRestriction(Shop::SHARE_CUSTOMER).' and pl.id_item='.$i.' and pl.id_group =c.id_default_group
ORDER BY c.`id_customer` ASC';
$res[]= Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
}

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";

Mixing two tables that are interconnected

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.

Using an array in a PHP MySQL WHERE clause

Hi I am creating an array of user id's with a query. With another query I would like to select from a given table where the user_id is one that is in the array created from my very first query. How can I use an array in my WHERE clause?
Just for reference: $row_interest is the array
My Code:
//Grabs the user id's of the users that have the queried interest
$interest_search_query= "SELECT DISTINCT user_id FROM interests WHERE interest LIKE
'%".$search_term."%'";
$interest_search_result= mysqli_query($connect, $interest_search_query);
$row_interest= mysqli_fetch_array($interest_search_result);
//Grabs the user information with each user id
$search_query= "SELECT DISTINCT user_id, fname, lname, profile_pic, school FROM users
WHERE user_id IN $row_interest";
I tried "WHERE user_id IN $row_interest", but it doesn't seem to work. What could I be doing wrong?
Thanks.
$search_query= "SELECT DISTINCT user_id, fname, lname, profile_pic, school FROM users
WHERE user_id IN (".implode(',',$row_interest).")";
You can actually merge both queries.
SELECT distinct user_id, fname, lname, profile_pic, school
FROM users
WHERE user_id in
(SELECT distinct user_id from interests
where interest like %{search_term}%)
You could build an IN() clause for your SQL in PHP, but since the set is coming from another query you could use a JOIN to do this.
Edit:
I can't test this without your data, but the join would be something like
$search_query= "SELECT DISTINCT u.user_id, u.fname, u.lname, u.profile_pic, u.school
FROM user u
INNER JOIN interests i ON u.user_id = i.user_id
WHERE i.interest like '%".$search_term."%'";
It sounds like you could just use a join, but $row_interest is an array, and it is interpolated as "Array" in the query. It seems like you want to build the entire array first
$rows = array();
while ($row = mysqli_fetch_array($interest_search_result)) {
$rows[] = $row['user_id'];
}
Then you can create the "IN" clause you need.
"WHERE user ID IN (" . implode(",", $rows) . ")"
Your code is vulnerable to injection. You should properly parameterize the queries using prepared statements. This is more difficult to do with a variable number of arguments in mysqli as I understand it, but it is something to keep in mind.

Categories