So I am doing a search and I am using an implode in my select statement, which I find quite useful. Basically this search engine will have 3 different selects which will select different things based on different criteria and when I use my implode I get an error of invalid arguments passed.
Here is my sql statement:
$sql = "SELECT DISTINCT camp.title, camp.startDay, camp.typeOfCamp, camp.endDay,
camp.link FROM ((camp INNER JOIN gender ON camp.id = gender.camp_id)
INNER JOIN grades ON camp.id = grades.camp_id)
INNER JOIN interests ON camp.id = interests.camp_id
WHERE ((grades.year = '".implode('\' OR grades.year = \'',$age)."')
AND gender.gender = '".$gender."')
OR ((interests.activity = '".implode('\' OR interests.activity = \'',$array)."')
AND (grades.year = '".$age."' AND gender.gender = '".$gender."'))";
The second implode for the interests is where I began having my problem and $array is an array. Another thing I don't understand is that when I run my code I get the correct results, but I am still getting the error that I am passing invalid arguments.
You may believe what PHP says, normally. If it says it isn't an array you probably didn't pass an array.
And a small tip to save you some code: There is an IN() statement in MySQL:
$sql = "SELECT DISTINCT camp.title, camp.startDay, camp.typeOfCamp, camp.endDay,
camp.link FROM ((camp INNER JOIN gender ON camp.id = gender.camp_id)
INNER JOIN grades ON camp.id = grades.camp_id)
INNER JOIN interests ON camp.id = interests.camp_id
WHERE (grades.year IN(".implode(',', $age).")
AND gender.gender = '".$gender."')
OR (interests.activity IN('".implode("','", $array)."')
AND grades.year = ".$age." AND gender.gender = '".$gender."')";
To save the duplicate gender.gender = $gender and (maybe) optimize the query:
$sql = "SELECT DISTINCT camp.title, camp.startDay, camp.typeOfCamp, camp.endDay,
camp.link FROM ((camp INNER JOIN gender ON camp.id = gender.camp_id)
INNER JOIN grades ON camp.id = grades.camp_id)
INNER JOIN interests ON camp.id = interests.camp_id
WHERE gender.gender = '".$gender."'
AND (
grades.year IN(".implode(',', $age).")
OR (
interests.activity IN('".implode("','", $array)."')
AND grades.year = ".$age."
)
)";
Furthermore I think MySQL doesn't require to use all those parentheses for joins:
$sql =
"SELECT DISTINCT camp.title, camp.startDay, camp.typeOfCamp, camp.endDay,
camp.link
FROM camp
INNER JOIN gender ON camp.id = gender.camp_id
INNER JOIN grades ON camp.id = grades.camp_id
INNER JOIN interests ON camp.id = interests.camp_id
WHERE gender.gender = '".$gender."'
AND (
grades.year IN(".implode(',', $age).")
OR (
interests.activity IN('".implode("','", $array)."')
AND grades.year = ".$age."
)
)";
Now the query should be way better to understand.
You're trying to do everything in on big statement. Why not build your imploded array-strings before you include them in the SQL?
Chris, your problem is that you're not passing an array to the second parameter of implode().
If you see www.php.net/implode the second parameter must be of type ARRAY so that PHP can start joining your array together with your delimiter specified in the first parameter.
A good way to check the data type of your variable is to use var_dump() which will tell you if something is an array, or int..etc
There are two variables you're passing to implode() there. $age and $array, I am guessing that it's age and you need to modify your code a bit.
Pasting your whole code that's generating $array and $age would help us further to see where you're going wrong in creating those variables.
Hope this helps.
Since you are using strings:
OR (interests.activity IN ('".implode("','", $array)."')
will neaten up that line.
But I am worried about $age. You use it as if it is an array in:
WHERE ((grades.year = '".implode('\' OR grades.year = \'',$age)."')
but as a string variable:
AND (grades.year = '".$age."' AND gender.gender = '".$gender."'))";
I think you should be using the "IN" and implode() expressions for both places you're using $age if it is an array.
Related
As you can see inside my while loop i declare i variable $TYPES..
This is my first Query
$first = "SELECT DISTINCT DATE_FORMAT(z.DatePaid,'%M %d, %Y') AS Paid
FROM tblStudPayments z
INNER JOIN tblPersonalData p ON p.StudNo=z.StudNo
WHERE z.StudNo=p.StudNo AND z.SY='".$SY."' AND z.Sem='".$Sem."' ORDER BY z.DatePaid;";
$fs = safe_query($first);
$numrows = mysql_num_rows($fs);
if($numrows>0)
{
while($dataf = mysql_fetch_assoc($fs))
{
$types =$dataf['Paid'];
}
}
I wanted to pass the value of $TYPES to my second Query
And This is my Second Query
$sql="SELECT DISTINCT p.StudNo, p.LName, p.FName, p.MName, p.NName, c.Description, p.YearLevel, d.Status,
'".$types."' AS DateEnlisted,
FROM tblPersonalData p
INNER JOIN tblStudPayments sp ON sp.StudNo=p.StudNo AND sp.SY='".$SY."' AND sp.Sem='".$Sem."'
INNER JOIN tblStatusHistory d ON d.StudNo=sp.StudNo AND d.SY=sp.SY AND d.Sem=sp.Sem
INNER JOIN tblCourses c ON c.CourseCode=d.CourseCode AND c.HSOrCollege='".$dType."'
INNER JOIN tblUserAcct u ON u.UserName=p.StudNo
";
$sql.=" HAVING DateEnlisted = '".$a['DateEnrolled']."' ";
$sql.=" ORDER BY p.StudNo ASC;";
At the bottom of SELECT Statement you can see my variable $TYPES i get it from my first query.
The problem is it doesn't get all the data.. it only get the last data from mysql
Thanks in Advance..
[Image Suggested by Kundu Updated][1]
[Image Suggested by Kundu echo $sql][2]
i try one query but the loading of data takes 10-15MIN.
Put the 2nd query inside the 1st query while loop
In your while loop you put the value in a variable & evry time this variable is updated.So at the end of the loop it will return last type value. Either put it in a array, so it will store all the value.But that case you need to convert the array into string when you put it in 2nd query.Also make sure when you put value in $type it should be unique.
update your code like this:
$types=array();
while($dataf = mysql_fetch_assoc($fs))
{
$types[] = $dataf['Paid'];
}
$allTypes = implode(",`", array_unique($types));
Now in your query:
$sql="SELECT DISTINCT p.StudNo, p.LName, p.FName, p.MName, p.NName, c.Description, p.YearLevel, d.Status,
`".$allTypes."` AS DateEnlisted,
FROM tblPersonalData p
INNER JOIN tblStudPayments sp ON sp.StudNo=p.StudNo AND sp.SY='".$SY."' AND sp.Sem='".$Sem."'
INNER JOIN tblStatusHistory d ON d.StudNo=sp.StudNo AND d.SY=sp.SY AND d.Sem=sp.Sem
INNER JOIN tblCourses c ON c.CourseCode=d.CourseCode AND c.HSOrCollege='".$dType."'
INNER JOIN tblUserAcct u ON u.UserName=p.StudNo
";
I have the following code for selecting from multiple tables where the order number matches.
$orderNumber = $_GET['orderNumber'];
$sql = $db->prepare("
SELECT
*
from `KC_Orders`
INNER JOIN
`KC_Payments`
on KC_Orders.orderNumber = KC_Payments.orderNumber
INNER JOIN
`KC_OrderStatus`
on KC_Orders.orderNumber = KC_OrderStatus.orderNumber
INNER JOIN
`KC_Statuses`
on KC_OrderStatus.statusID = KC_Statuses.statusID
WHERE
orderNumber= :orderNumber");
$sql->execute(array(':orderNumber' => $orderNumber));
$orderInfo = $sql->fetchAll();
Now when I var_dump($orderInfo); it returns: array(0) { } What is wrong? All the tables include the same $orderNumber field within it. If I take the WHERE part out it works just fine except it returns every row not just one. (obviosly).
Please help us!
You need to specify what the OrderNumber is from, and the * is from (what table). So try this new code:
$sql = $db->prepare("SELECT KC_Orders.* from `KC_Orders` INNER JOIN `KC_Payments` on KC_Payments.orderNumber = KC_Orders.orderNumber INNER JOIN `KC_OrderStatus` on KC_OrderStatus.orderNumber = KC_Order.orderNumber INNER JOIN `KC_Statuses` on KC_Statuses.statusID = KC_OrderStatus.statusID WHERE KC_Orders.orderNumber= :orderNumber");
Ordernumber in where clause should have table prefix if it exists in multiple tables
Try this
$orderNumber = (int)$_GET['orderNumber'];
Then where :ordernumber is put $orderNumber
Then execute
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 = ?"
I am having a hard time creating a mySQL join statement.
The issue is that it seems to return the correct results, but it returns duplicates.
$result= mysql_query("SELECT Photos.Filename, Photos.Filetype
FROM Photos, PhotoUserTags
WHERE PhotoUserTags.User_ID IN ($friendlist) && PhotoUserTags.Photo_ID = Photos.Photo_ID && Photos.Event_ID = $eid");
I am new to these statements, any help or guidance is greatly appreciated.
Here's your query:
SELECT
Photos.Filename, Photos.Filetype
FROM Photos
INNER JOIN PhotoUserTags ON (PhotoUserTags.Photo_ID = Photos.Photo_ID)
WHERE
Photos.Event_ID = $eid
AND PhotoUserTags.User_ID IN ($friendlist) /* assuming they are IDs separated by a comma) */
GROUP BY Photos.Photo_ID;
I would also explain this query just in case you use the right indexes to maximize the performance of your query
For one, the logical and in mysql is not && but AND, like this:
SELECT * from table WHERE field1 = 'value1' AND field2 = 'value2';
You should also use the newer join syntax like this:
SELECT Photos.Filename, Photos.Filetype
FROM Photos, PhotoUserTags
INNER JOIN PhotoUserTags ON PhotoUserTags.Photo_ID = Photos.Photo_ID
WHERE PhotoUserTags.User_ID IN ($friendlist)
AND Photos.Event_ID = $eid
GROUP BY Photos.Photo_ID
Note the join expression (I used inner join, assuming a matching record needs to exist in both tables) - it makes your where cleaner and easier to read.
Does this help:
$result= mysql_query("SELECT Photos.Filename, Photos.Filetype
FROM Photos, PhotoUserTags
WHERE PhotoUserTags.User_ID IN ($friendlist) && PhotoUserTags.Photo_ID = Photos.Photo_ID && Photos.Event_ID = $eid GROUP BY Photos.Photo_ID");
Hey guys need some more help
I have 3 tables USERS, PROFILEINTERESTS and INTERESTS
profile interests has the two foreign keys which link users and interests, they are just done by ID.
I have this so far
$statement = "SELECT
InterestID
FROM
`ProfileInterests`
WHERE
userID = '$profile'";
Now I want it so that it selects from Interests where what it gets from that query is the result.
So say that gives out 3 numbers
1
3
4
I want it to search the Interests table where ID is = to those...I just don't know how to physically write it in PHP...
Please help.
Using a JOIN:
Best option if you need values from the PROFILEINTERESTS table.
SELECT DISTINCT i.*
FROM INTERESTS i
JOIN PROFILEINTERESTS pi ON pi.interests_id = i.interests_id
WHERE pi.userid = $profileid
Using EXISTS:
SELECT i.*
FROM INTERESTS i
WHERE EXISTS (SELECT NULL
FROM PROFILEINTERESTS pi
WHERE pi.interests_id = i.interests_id
AND pi.userid = $profileid)
Using IN:
SELECT i.*
FROM INTERESTS i
WHERE i.interests_id IN (SELECT pi.interests_id
FROM PROFILEINTERESTS pi
WHERE pi.userid = $profileid)
You are on the right track, lets say you execute the query above using this PHP code:
$statement = mysql_query("SELECT InterestID FROM `ProfileInterests`
WHERE userID = '$profile'");
Then you can use a PHP loop to dynamically generate an SQL statement that will pull the desired IDs from a second table. So, for example, continuing the code above:
$SQL = "";
while ($statementLoop = mysql_fetch_assoc($statement)) {
//Note the extra space on the end of the query
$SQL .= "`id` = '{$statementLoop['InterestID']}' OR ";
}
//Trim the " OR " off the end of the query
$SQL = rtrim($SQL, " OR ");
//Now run the dynamic SQL, using the query generated above
$query = mysql_query("SELECT * FROM `table2` WHERE {$SQL}")
I haven't tested the code, but it should work. So, this code will generate SQL like this:
SELECT * FROM `table2` WHERE `id` = '1' OR `id` = '3' OR `id` = '4'
Hope that helps,
spryno724
Most likely you want to join the tables
select
i.Name
from
ProfileInterests p
inner join
interests i
on
p.interestid = i.interestid
where
p.userid = 1