Combine MySQL SELECT queries with IF statement - php

I want to combine my two SELECT statements with an if statement. Currently I am just getting the row and then doing if($row['activated'] === 1) { ... run 2nd select statement }.
There has to be a better and much faster way of doing it (performance-wise). This is what I'm trying to do:
For example: (1st SELECT statement)
$db = $stmt->("SELECT * FROM users WHERE id = :id AND activated = 1");
$db->bindParam(':id', $id);
$db->execute();
If that above SELECT statement is true, then do this: (2nd SELECT statement)
$db = $stmt->("SELECT * FROM user_settings WHERE user_id = :user_id");
$db->bindParam(':user_id', $id);
$db->execute();
How can I combine those two SELECT statements? If it is else or if activated = 0, then only do the first select.
Bonus question:
How can I make it three If statements? For example, the 2nd SELECT statement will be like this:
$db = $stmt->("SELECT * FROM user_settings WHERE user_id = :user_id AND color = :color");
$db->bindParam(':user_id', $id);
$db->bindParam(':color', $color);
$db->execute();
Now if that statement is true, run this 3rd SELECT statement:
$db = $stmt->("SELECT * FROM friends WHERE user_id = :user_id");
$db->bindParam(':user_id', $id);
$db->execute();

You can merge/combine
SELECT * FROM user_settings WHERE user_id = :user_id AND color = :color
and
SELECT * FROM friends WHERE user_id = :user_id
Into one query with a JOIN
SELECT
*
FROM
user_settings
INNER JOIN
friends
ON
user_settings.user_id = friends.user_id
AND
user_settings.color = :color
Or a other JOIN format
SELECT
*
FROM
user_settings
INNER JOIN
friends
ON
user_settings.user_id = friends.user_id
WHERE
user_settings.color = :color
Or you can write it as this JOIN. (most likely slower)
SELECT
*
FROM (
SELECT
*
FROM
user_settings
WHERE
user_settings.color = :color
) AS user_settings
INNER JOIN
friends
ON
user_settings.user_id = friends.user_id
The used method which is best/faster can/will be depending which indexes you have in use.

Related

Select and unlink file on 3 tables

Please help me to check my query. I have search a lot and I have'nt try to select 3 tables before.
I think I got it right but I dont know why there's nothing happen.
public function delSection($delete_id)
{
$stmt = $this->conn->prepare("SELECT * FROM tbl_section
JOIN tbl_login ON (tbl_login.sec_id = tbl_section.sec_id)
JOIN tbl_content ON (tbl_content.sec_id = tbl_section.sec_id)
WHERE tbl_section.sec_id=:del_id");
$stmt->execute(array(":del_id"=>$delete_id));
while($linkRow=$stmt->fetch(PDO::FETCH_ASSOC))
{
unlink(__DIR__."/Admin/cover_images/".$linkRow['sec_cover']);
unlink(__DIR__."/Admin/Files/".$linkRow['sec_id']."/".$linkRow['file_name']);
rmdir(__DIR__."/Admin/Files/".$linkRow['sec_id']);
}
$stmt2 = $this->conn->prepare("DELETE tbl_section, tbl_login, tbl_content FROM tbl_section
JOIN tbl_login ON (tbl_login.sec_id = tbl_section.sec_id)
JOIN tbl_content ON (tbl_content.sec_id = tbl_section.sec_id)
WHERE tbl_section.sec_id=:del_id");
$stmt2->bindparam(":del_id",$delete_id);
$stmt2->execute();
return true;
}
What I am trying to do is to select * from 3 tables and fetch their data with fk sec_id
here's the manual running of query
link:
Code:
Done With LEFT OUTER JOIN QUERY
$stmt = $this->conn->prepare("SELECT * FROM tbl_section
LEFT OUTER JOIN tbl_login ON (tbl_login.sec_id = tbl_section.sec_id)
LEFT OUTER JOIN tbl_content ON (tbl_content.sec_id = tbl_section.sec_id)
WHERE tbl_section.sec_id=:unlink_id");

php mysql select something and get columns from other tables

I'm using prepared statements and I need to "select" other table, apart from these two, to get data but I get this:
Fatal error: Call to a member function bind_param() on a non-object in C:\xampp\htdocs\views\user\referral.php on line 16
If I add in SELECT table1.* , table.* , "theothertable.*"
$stmt = $mysqli->prepare("SELECT friends.*, rc_usuario.* // or just *
FROM friends
INNER JOIN rc_usuario ON rc_usuario.id = friends.friendID
WHERE friends.userID = ?");
$stmt->bind_param('s', $connectedUserID);
This is working fine, I get what i need, but I also need to get data from another table and I can't make other select because i need it all in a while to print all the data together.
The question is, can I SELECT something like that from 2 tables and also get data from other table/s?
Thank YOU!
EDIT: Add the new statement:
if ($stmt = $mysqli->prepare("SELECT friends.*, members.*, account_type.*
FROM friends
INNER JOIN members ON members.id = friends.friendID
INNER JOIN account_type ON account_type.name = members.acc_type
WHERE friends.userID = ? AND members.acc_type = ?")) {
$stmt->bind_param('is', $connectedUserID, $connectedAcc_type);
$stmt->execute();
} else echo $mysqli->error;
You can join more tables by using another INNER JOIN, like as follows;
INNER JOIN rc_usuario ON rc_usuario.id = friends.friendID
INNER JOIN rc_another ON rc_another.col = friends.coljoin
Just make sure you select all the columns you want in the joined table.
It might also help to run your prepare statement in an if, like this;
if($stmt = $mysqli->prepare("SELECT ...")) { // ... where the rest of your query is
$stmt->bind_param('s', $connectedUserID);
$stmt->execute();
}
else {
echo $mysqli->error;
}
which will give you an idea of any problems with the SQL syntax.
Hope this helps.

Inner/Left join with two different where clauses

i'm in the process of joining two tables together under two different conditions. For primary example, lets say I have the following nested query:
$Query = $DB->prepare("SELECT ID, Name FROM modifications
WHERE TYPE =1 & WFAbility = '0'");
$Query->execute();
$Query->bind_result($Mod_ID,$Mod_Name);
and this query:
$Query= $DB->prepare("SELECT `ModID` from `wfabilities` WHERE `WFID`=?");
$Query->bind_param();
$Query->execute();
$Query->bind_result();
while ($Query->fetch()){ }
Basically, I want to select all the elements where type is equal to one and Ability is equal to 0, this is to be selected from the modifications table.
I further need to select all the IDs from wfabilities, but transform them into the names located in modifications where WFID is equal to the results from another query.
Here is my current semi-working code.
$Get_ID = $DB->prepare("SELECT ID FROM warframes WHERE Name=?");
$Get_ID->bind_param('s',$_GET['Frame']);
$Get_ID->execute();
$Get_ID->bind_result($FrameID);
$Get_ID->fetch();
$Get_ID->close();
echo $FrameID;
$WF_Abilties = $DB->prepare("SELECT ModID FROM `wfabilities` WHERE WFID=?");
$WF_Abilties->bind_param('i',$FrameID);
$WF_Abilties->execute();
$WF_Abilties->bind_result($ModID);
$Mod_IDArr = array();
while ($WF_Abilties->fetch()){
$Mod_IDArr[] = $ModID;
}
print_r($Mod_IDArr);
$Ability_Name = array();
foreach ($Mod_IDArr AS $AbilityMods){
$WF_AbName = $DB->prepare("SELECT `Name` FROM `modifications` WHERE ID=?");
$WF_AbName->bind_param('i',$AbilityMods);
$WF_AbName->execute();
$WF_AbName->bind_result($Mod_Name);
$WF_AbName->fetch();
$Ability_Name[] = $Mod_Name;
}
print_r($Ability_Name);
See below:
SELECT ModID,
ID,
Name
FROM modifications M
LEFT JOIN wfabilities WF
ON WF.ModID = M.ID
WHERE TYPE =1 & WFAbility = '0'
To do this, you need to join your tables, I'm not quite sure what you are trying to do so you might have to give me more info, but here is my guess.
SELECT ID, Name, ModID
FROM modifications
JOIN wfabilities
ON WFID = ID
WHERE TYPE = '1'
AND WFAbility = '0'
In this version I am connecting the tables when WFID is equal if ID. You will have to tell me exactly what is supposed to be hooking to what in your requirements.
To learn more about joins and what they do, check this page out: MySQL Join
Edit:
After looking at your larger structure, I can see that you can do this:
SELECT modifications.Name FROM modifications
JOIN wfabilities on wfabilities.ModID = modifications.ID
JOIN warframes on warframes.ID = wfabilities.WFID
WHERE warframes.Name = 'the name you want'
This query will get you an array of the ability_names from the warframes name.
This is the query:
"SELECT A.ID, A.Name,B.ModID,C.Name
FROM modifications as A
LEFT JOIN wfabilities as B ON A.ID = B.WFID
LEFT JOIN warframes as C ON C.ID = B.WFID
WHERE A.TYPE =1 AND A.WFAbility = '0' AND C.Name = ?"

Mysql Join two Id's to get there Usernames

Im trying to get in Array that contains the results from a MYSQL query.
I have 2 ids stored in the table hitlist user_id and mark_id
they need to join in the table users to retrieve there usernames that match there id's and in the future other variables.
i have this working in a weird way and was hopeing to get this working in a more efficent simple way similar to this
$Hitlists = $db->query("SELECT * FROM hitlist JOIN users ON hitlist.user_id = users.id AND hitlist.mark_id = users.id")->fetchAll();
This is the code i have that is working...for now it looks like it might give me problems later on.
<?php
$index = 0;
$Hitlists = array();
$st = $db->query("SELECT * FROM hitlist JOIN users ON hitlist.user_id = users.id")->fetchAll();
$sth = $db->query("SELECT * FROM hitlist JOIN users ON hitlist.mark_id = users.id")->fetchAll();
foreach($st as $id)
{
$Hitlists[] = $id;
}
foreach($sth as $id)
{
$Hitlists[$index]['markedby'] = $id['username'];
$Hitlists[$index]['mark_id'] = $id['mark_id'];
$index++;
}
The way you are joining the table is wrong. You can get the exact records you want, you need to join users table twice to get the username of each ID
SELECT a.*,
b.username User_name,
c.username mark_name
FROM hitlist a
INNER JOIN users b
ON a.user_id = b.id
INNER JOIN users c
ON a.mark_id = c.id
and you can access
$result['User_name']
$result['mark_name']

How to convert normal sql query to Zend_Db_Select?

Hi I want to convert my normal mysql query to zend.db.select;
I want to use this script:
$select = $db->select();
// Add a FROM clause
$select->from( ...specify table and columns... )
// Add a WHERE clause
$select->where( ...specify search criteria... )
// Add an ORDER BY clause
$select->order( ...specify sorting criteria... );
$select->limit(20, 10);
for my query below
SELECT
IF(derived_messages.toid = '$user', derived_messages.fromid,
derived_messages.toid) friend1,c.UserName,
derived_messages.message, derived_messages.fromid, derived_messages.toid,
derived_messages.is_read,derived_messages.type,derived_messages.id as mesid,
derived_messages.date,
(SELECT M.message_id FROM messagesmapped M where M.message_id= derived_messages.id AND M.user_id ='$user' AND M.important = 1) as MesMapid
FROM
(
SELECT *
FROM messages
WHERE messages.deleted_by NOT
IN ( $user )
ORDER BY Date DESC
) derived_messages
INNER JOIN Users c ON c.MemberID = IF(derived_messages.toid = '$user', derived_messages.fromid,
derived_messages.toid)
WHERE (derived_messages.id IN
(SELECT M.message_id FROM messagesmapped M where M.message_id= derived_messages.id AND M.user_id ='$user' AND M.important = 1)
AND
(derived_messages.toid='$user' OR derived_messages.fromid='$user'))
GROUP BY friend1 ASC
ORDER BY derived_messages.date DESC, derived_messages.id DESC LIMIT $limit $offset
I hope someone can help m on this.
Thank you.
It's possible but unlikely someone will write the query for you.
My recommendation on tackling such a query is to write each individual subquery as its own Zend_Db_Select object and then build the final query using the subqueries that you already have objects for.
Zend_Db_Select doesn't directly support the IF function, so for that you will need to use Zend_Db_Expr to add that statement into your select.
Here is a basic example of what I am talking about. Let's build the following query:
SELECT IF(msg.toId = 'drew010', msg.fromId, msg.toId), id, name, age, history.ip
FROM users
JOIN history ON users.id = history.userId
WHERE users.id = (
SELECT id FROM users WHERE loginCount > 1000
)
GROUP BY id,
ORDER BY age DESC
First build the subselect that select users where loginCount > 1000.
$subquery1 = $db->select()
->from('users', array('id'))
->where('loginCount > ?', 1000);
Next, build the outer query with the IF function:
$cols = array(
new Zend_Db_Expr('IF(' . $db->quoteInto('msg.toId = ?', 'drew010') . '), msg.fromId, msg.toId'),
'id', 'name', 'age'
);
$query = $db->select()
->from('users', $cols)
->join('history', 'users.id = history.userId', array('ip'))
->where('id = ?', $subquery1)
->group('id')
->order('age DESC');
echo $query;
The output:
SELECT
IF(msg.toId = 'drew010', msg.fromId, msg.toId),
`users`.`id`,
`users`.`name`,
`users`.`age`,
`history`.`ip`
FROM `users`
INNER JOIN `history`
ON users.id = history.userId
WHERE id = (
(SELECT `users`.`id`
FROM `users`
WHERE (loginCount > 1000))
)
GROUP BY `id`
ORDER BY `age` DESC
So the way to go is break the entire query into individual queries first, and then construct the outer query. Just have patience and take it slow. That and read over the Zend_Db_Select docs to get a full picture of what you have available to you.

Categories