php mysql where IN clause - php

I have a simple query:
$user_id = $_SESSION['user_id'];
SELECT * FROM pages WHERE user_id IN($user_id);
field user_id in pages tables has the following format 1,3,5,...
it contains multiple user_id
What I need is to select all rows based on logged in user_id.
The above attempt does not works, it only picks up the first number.

You need to use find_in_set():
select *
from pages
where find_in_set(user_id, $user_id) > 0;
Alternatively, you can construct the SQL so it has the values in the string. Something like:
select *
from pages
where user_id in (".$user_id.")"

Related

Check First on Table A, if not found Check on other table

I am creating a Log in and I have separate tables for Users A and Users B.
What I want to do is check first in first table if the Users that trying to Login is in the Table A,
if YES, it will not go to the Table B to check the Login credentials, if NOT, go to Table B and check the Login credentials.
Table A
SELECT * FROM tableA WHERE userId='$userId' AND password='$password'
Table B
SELECT * FROM tableB WHERE accountNumber='$accountNumber' AND password='$password'
Note: The 2 Tables has different Field Name userId and accountNumber.
I presume you are fetching the values of username and password from client side so I will tell you only what you asked for.
$getUserBasic1=$db->prepare('SELECT * FROM tableA WHERE userId="$userId" AND password="$password"');
$getUserBasic1->execute();
$user= $getUserBasic1->fetchAll();
if(count($user)>0)
{
//if yes do what you want here
}
else
{
$getUserBasic2=$db2->prepare('SELECT * FROM tableB WHERE accountNumber="$accountNumber" AND password="$password"');
$getUserBasic2->execute();
$user2= $getUserBasic2->fetchAll();
//write your code here
}
You could use an INNER JOIN and select both table results taking Table A's result first if it exists, else take Table B's result.
Assuming both tables have some sort of reference like the User ID you can use something like this:
SELECT tbla.*, tblb.* FROM tableA tbla
INNER JOIN tableB tblb ON tbla.userId = tblb.userId
WHERE userId='$userId' OR accountNumber='$accountNumber' AND password='$password'
ORDER BY userId ASC
LIMIT 1
The query above uses the cross-reference (userId in this case) and joins both tables together before querying the results. It orders the results by Table A before Table B but limits the result to 1 bringing either Table A or Table B out depending which is null.
Try combining the tables, some thing like:
SELECT * FROM tableA, tableB WHERE tableA.userId='$userId' AND tableA.password='$password' OR tableB.accountNumber='$accountNumber' AND tableB.password='$password'
I have not checked, so may not work, but see if this gets what you are looking for!
Something like this:
$sql = "SQL QUERY FOR TABLEA";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// checking if result in TABLE A
}
else{
//search in TABLE B by updating your sql value.
}
I hope that you want to check for the registered user, the best way to do that is to keep one table and just search there itself keeping the userID as the primary key.

php/mySQL: querying records by id from array?

i want to query several records by id like:
$ids = array(10,12,14,16,....);
the query would be something like:
select * from users where id=10 or id=12 or id=14 or id=16 ..
is it possible to query it in a more comfortable way like (compared to php):
select * from user where in_array(id, array(10,12,14,16))
thanks
You can use IN instead of OR clauses
select * from users where id IN (put_your_array_here)
Example:
select * from users where id IN (10,12,14,16);
Note:
According to the manual for MySQL if the values are constant IN
sorts the list and then uses a binary search. I would imagine that
OR evaluates them one by one in no particular order. So IN is
faster in some circumstances.
Related post
Try this.
$id = array(10,12,14,16,....);
$ids = join("','",$id);
$sql = "select * from user where id IN ('$ids')";
OR
$ids = implode(',', $id);
$sql = "select * from user where id IN ($ids)";
You can do it like that using implode in PHP:
"select * from users where id in '".implode("','", $ids)."'"
Please be sure that your ids are safe though

How to apply conditions in mysqli query

I want to apply conditions with my query like i want to interchange one column's value to another column. Here is my query and now i am not getting how to apply
mysqli_query($connect, "
select
user_pro.User_No,
user_pro.Fist_Name,
user_pro.Last_Name,
user_pro.Designation,
user_pro.Profile,
user_pro.ProfileDP,
user_fndrst.Frnd_SNo,
user_fndrst.Rqst_Sender,
user_fndrst.Rqst_Receiver,
user_fndrst.Rqst_Status
from
user_profile INNER JOIN user_fndrst ON user_pro.User_No = user_fndrst.Rqst_Sender
WHERE
user_fndrst.Rqst_Status='1' AND
user_fndrst.Rqst_Receiver='$user_id'
ORDER BY Frnd_SNo DESC
");
Here "user_pro" table contains user's details, "user_fndrst" table contains user's friend request status and $user_id is user's logined id. Here I want that IF user_fndrst.Rqst_Receiver='$user_id' THEN user_fndrst.Rqst_Receiver value change to user_fndrst.Rqst_Sender.
For this I have stuck with user friend request status fetching from table "user_fndrst".
It seems your query has some problems. Use this:
SELECT
user_pro.User_No, user_pro.Fist_Name, user_pro.Last_Name, user_pro.Designation, user_pro.Profile, user_pro.ProfileDP, user_fndrst.Frnd_SNo, user_fndrst.Rqst_Sender, user_fndrst.Rqst_Receiver, user_fndrst.Rqst_Status
FROM
user_profile user_pro
INNER JOIN user_fndrst ON user_pro.User_No = user_fndrst.Rqst_Sender
WHERE
user_fndrst.Rqst_Status='1' AND user_fndrst.Rqst_Receiver='$user_id'
ORDER BY
user_fndrst.Frnd_SNo DESC

two pdo selects in one if there is a result in both tables

So i have a problem i have a user table and a website table i need to select a random user from the users table just there username were there is a row in the website table with there username.Is this possible ?
So i am getting a random user table
$stmt9 = $db->prepare('SELECT * FROM users WHERE coins >= ? ORDER BY RAND() LIMIT 1');
$stmt9->execute( array('1') ) ;
$row = $stmt9->fetch();
Now some how i need to grab a random website were the owner = there username like so
$stmt21 = $db->prepare('SELECT * FROM websites WHERE owner = ? ORDER BY RAND() LIMIT 1');
$stmt21->execute( array($row['username']) ) ;
$row21 = $stmt21->fetch();
The problem i have is it will grab the username fine but then if the user has not submitted a website the second select will fail so some how i need to put both these select together. And grab a row of the website table were there is a row and were the coins in the user table is over 1.
You could check if the first query returns an empty set, anyway if you want one query and you are not interested in the username you could use this:
SELECT
*
FROM
websites w
WHERE w.owner
IN (SELECT u.username FROM users u WHERE u.coins >= ?)
ORDER BY
RAND()
LIMIT
1
If you want you can limit the username selected in the subquery adding the random order by and the limit clause.

SQL "LIKE" If empty returns all rows

Hello I have 2 textboxes and i want to give to the user the option to choose one in order to find results. The user can search through the id or the name. My problem is because i use LIKE%field% when the user chooses to search through the id the name field stays empty and returns all the table rows. I want to have results only if the user enters some value in the textbox. This is my sql query. I'm using mysql
"SELECT * FROM properties WHERE ID='$id' OR Name LIKE '%$name%'"
Thank you all
If the user has to select which field to search, you can do:
if ($_POST['search'] == 'id') {
$sql = "SELECT * FROM properties WHERE ID='$id'"
} else {
$sql = "SELECT * FROM properties WHERE Name LIKE '%$name%'"
}
You can do this in a single query (values are checked from the query itself):
"SELECT * FROM properties WHERE ('$id'='' OR ID='$id') AND ('$name' ='' OR Name LIKE '%$name%')"
Explanation:
First condition:
The query will select records with ID='$id' only when $id is not empty.
If $id is empty, query will not go for the second part ID='$id'
Second condition:
The query filters records with Name LIKE '%$name%' only when $name is not empty.
If $name is empty, query will not go for Name LIKE '%$name%'.
NB: This technique is extremely useful when you have numerous parameters to check, rather than using a bunch of if...elses at php side.

Categories