Using an array in a PHP MySQL WHERE clause - php

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.

Related

Can you do a "INSERT SELECT WHERE" between two tables?

So I've been trying to create a simple friend system. When you register, you get randomized numbers and chars of 8 in length. I save this number in a column to the user. I have been trying to insert the currently sessioned user(PHP), $SessionUser together with the friends' username, uidUsers using an "INSERT SELECT WHERE" statement, but something goes wrong. Heres something I have tried:
$sql = mysqli_query($conn, "INSERT into friends (uid1, uid2)
values($sessionUser, (SELECT uidUsers FROM users WHERE idFriendCode = $idFriendCode)");
Inside the table, friends, I have two columns, uid1 (the sessioned user/sender) and uid2 (the reciever, name of specified $idFriendCode). I want to insert the $sessionUser to the uid1 and whatever username (uidUsers) that matches with the $idFriendCode to the uid2. This does not seem to work and I don't know why. I imagine the problem is that I can't use a PHP variable like this.
I know that I don't use prepared statements. I have tried to implement it, but I think it's much harder than just using a basic mysqli_query().
You may phrase your insert as an INSERT INTO ... SELECT:
INSERT into friends (uid1, uid2)
SELECT $sessionUser, uidUsers
FROM users
WHERE idFriendCode = $idFriendCode;
Note that you should ideally be using a prepared statement here, so the above should look like:
INSERT into friends (uid1, uid2)
SELECT ?, uidUsers
FROM users
WHERE idFriendCode = ?;
Try having a new variable for select and use it in the insert query
example:
$select_qr='SELECT uidUsers FROM users WHERE idFriendCode = $idFriendCode'
$sql = mysqli_query($conn, "INSERT into friends (uid1, uid2)
values($sessionUser, $select_qr)");

Join in one column to another table

I know this question is very common on Stack, but I can't seem to find an answer or a snippet of code that actually solves my problem...
I have two tables, accounts and orders. I want to write a SQL statement to pull Order ID, Date, Total and Status from orders, and also Username from accounts.
The statement would be something like this:
$ohsql = "select * from orders where Username = '". $login_session ."'";
Obviously Username will come from the accounts table, but the principal is there. I am missing the join as I am clueless about it!
You need to 'link' the two tables. For that do something like :
- add a column accountid to Orders table; so this tells us, which order belongs to which user . We then use this info in our JOIN.
Easy way to do it in 2 queries :
// get the id value of the username
$id = select id from accounts table where username = $login_session
// use that in the JOIN
select * from orders JOIN accounts ON orders.accountid = accounts.id where accounts.id = $id
Assuming that your orders table contains the accountId and your accounts table containing the user name use following query
$ohsql = "select o.*, a.username from orders o
INNER JOIN accounts a ON a.id = o.accountId
WHERE a.username = '". $login_session ."'";
Let me know if you face any issue

Select from one table where id in another and replace integer with char varying from second table

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

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

SELECT data via array from different tables in mysql

hello guys i found some similar questions here but nothing work's for me maybe someone can help me.
i have a couple of filter where the user can list other users by properties like in a dating site. i want to show the user just the members from the filters the user choose. i store the keywords in an array and want to get the data now from two different tables.
at the moment i use this query but its just shows me the values from one table
$sql = "SELECT * FROM users WHERE username IN ($data) AND country IN ($data) OR city IN ($data) OR gender IN ($data)";
i need to get some more properties like smoker or non smoker etc. from another table how would i do this with this array ($data). sorry for the bad english
the table one is users who contains id, username, gender, country
and the other table called properties who contains id, userid, hobbies, jobs i need to join them somehow
Use JOIN on their "linked" column :
$sql = " SELECT u.username, u.country ";
$sql .= " FROM users u ";
$sql .= " LEFT OUTER JOIN other_table t ON u.id = t.id";
$sql .= " WHERE username IN ($data) AND country IN ($data) OR city IN ($data) OR gender IN ($data)";
MySQL documentation.

Categories