PHP PDO SQL Join two strings together - php

I'm trying to join two strings together in a prepare statement (table name & column which is dynamic) but I am getting
Uncaught PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'exp.$getSkill' in 'field list'
My code is:
$query = $db->prepare('SELECT members.*, exp.*, lvl.*, exp.$getSkill AS exp_skill, lvl.$getSkill AS level_skill FROM members INNER JOIN exp ON members.id = exp.member_id INNER JOIN lvl ON members.id = lvl.member_id ORDER BY lvl.$getSkill DESC, exp.$getSkill DESC');
$query->execute();
$row = $query->fetch();
Is there a way I can join exp. and $getSkill properly?

Variable aren't evaluated inside strings with single quotes. You'd need to use double quotes, and surround the name with curly braces ({}):
$query = $db->prepare("SELECT members.*, exp.*, lvl.*, exp.${getSkill} AS exp_skill, lvl.$getSkill AS level_skill FROM members INNER JOIN exp ON members.id = exp.member_id INNER JOIN lvl ON members.id = lvl.member_id ORDER BY lvl.$getSkill DESC, exp.$getSkill DESC");
Mandatory note:
Using string concatenation in an SQL query could potentially expose your code to SQL Ijection attacks. You should be very careful if you intend to use such a technique.

Try something like this:
$query = 'SELECT members.*,
exp.*,
lvl.*,
exp.'.$getSkill.' AS exp_skill,
lvl.$getSkill AS level_skill
FROM members
INNER JOIN exp ON members.id = exp.member_id
INNER JOIN lvl ON members.id = lvl.member_id
ORDER BY lvl.$getSkill DESC, exp.$getSkill DESC';
$query = $db->prepare($query);
$query->execute();
$row = $query->fetch();

Related

My MySQLi query gives error but i can't find out thats wrong with it

I'm working with a mysql query to select data from multiple tables using LEFT OUTER JOIN. Now i get the following error when i exequte the query:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'wg.werkbon_global_id = wk.werkbon_klant_globalid LEFT OUTER
JOIN users AS u' at line 16
Only the problem is that i can't find out what's wrong with my query.
PHP Query:
$query = '
SELECT
wg.werkbon_global_id AS id,
wg.werkbon_global_status AS status,
wg.werkbon_global_date_lastedit AS date,
usr.user_firstname AS monteur_vn,
usr.user_insertion AS monteur_tv,
usr.user_lastname AS monteur_an,
wg.werkbon_global_type AS type,
wg.werkbon_global_layout AS layout,
wg.werkbon_global_werkzaamheden AS werkzaamheden,
wg.werkbon_global_opmerkingen AS opmerkingen,
wk.werkbon_klant_nummer AS klantnr
FROM
werkbon_klant AS wk
LEFT OUTER JOIN werkbon_global AS wg
wg.werkbon_global_id = wk.werkbon_klant_globalid
LEFT OUTER JOIN users AS usr
usr.user_id = wg.werkbon_global_monteur_finish
WHERE
wk.werkbon_klant_nummer = '.$db->Quote($klantid).'
ORDER BY id ASC;
$result = $db->loadAssoc($query);
I think my problem has something todo with left outer join but what?
You are missing the ON operator in your joins!
The correct syntax for a join is:
SELECT * FROM x LEFT JOIN y ON condition WHERE...
$query = "
SELECT
wg.werkbon_global_id AS id,
wg.werkbon_global_status AS status,
wg.werkbon_global_date_lastedit AS date,
usr.user_firstname AS monteur_vn,
usr.user_insertion AS monteur_tv,
usr.user_lastname AS monteur_an,
wg.werkbon_global_type AS type,
wg.werkbon_global_layout AS layout,
wg.werkbon_global_werkzaamheden AS werkzaamheden,
wg.werkbon_global_opmerkingen AS opmerkingen,
wk.werkbon_klant_nummer AS klantnr
FROM
werkbon_klant AS wk
LEFT OUTER JOIN werkbon_global AS wg
wg.werkbon_global_id = wk.werkbon_klant_globalid
LEFT OUTER JOIN users AS usr
usr.user_id = wg.werkbon_global_monteur_finish
WHERE
wk.werkbon_klant_nummer = '.$db->Quote($klantid).'
ORDER BY id ASC";
$result = $db->loadAssoc($query);
Make sure there isn't missing quote
Problem soved thanks to arkascha
The fixed query is now:
$query = '
SELECT
wg.werkbon_global_id AS id,
wg.werkbon_global_status AS status,
wg.werkbon_global_date_lastedit AS date,
usr.user_firstname AS monteur_vn,
usr.user_insertion AS monteur_tv,
usr.user_lastname AS monteur_an,
wg.werkbon_global_type AS type,
wg.werkbon_global_layout AS layout,
wg.werkbon_global_werkzaamheden AS werkzaamheden,
wg.werkbon_global_opmerkingen AS opmerkingen,
wk.werkbon_klant_nummer AS klantnr
FROM
werkbon_klant AS wk
LEFT OUTER JOIN werkbon_global AS wg ON
wg.werkbon_global_id = wk.werkbon_klant_globalid
LEFT OUTER JOIN users AS usr ON
usr.user_id = wg.werkbon_global_monteur_finish
WHERE
wk.werkbon_klant_nummer = '.$db->Quote($klantid).'
ORDER BY id ASC';
$result = $db->loadAssoc($query);
#fred i don't need to add quotes by column names. You only need to add quotes by string/blob values.
#johny my $db->Quote() function will add qoutes automaticly. I don't need to add them and put everything in quote's.
Thanks all for help.

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 = ?"

SQL Error when trying to JOIN tables

I'm trying to run this query:
$query = $conn->query("SELECT * FROM $table
LEFT JOIN vacatures ON bedrijven.id = vacatures.id
WHERE id = '$id'
AND bedrijfID = '$bedrijf_id'");
But it fails for some reason. I get this error.
Syntax error or access violation: 1066 Not unique table/alias
When I leave the JOIN part, the query is succesful. Why is this happening?
I'm using PHP & PDO to fetch the queries.
Thanks.
EDIT: I wrote the query thanks of the answers given. This is working:
$query = $conn->query("SELECT * FROM bedrijven
LEFT JOIN vacatures v ON bedrijven.id = v.bedrijfID WHERE v.bedrijfID = $bedrijf_id AND v.id = $id");
You need to specify one table or the other in WHERE id = '$id', even though they're equal to each other in this case.
You also need to make sure your LEFT JOIN includes $table:
$query = $conn->query("SELECT * FROM $table
LEFT JOIN vacatures ON $table.id = vacatures.id
WHERE $table.id = '$id'
AND bedrijfID = '$bedrijf_id'");
or:
$query = $conn->query("SELECT * FROM bedrijven
LEFT JOIN vacatures ON bedrijven.id = vacatures.id
WHERE bedrijven.id = '$id'
AND bedrijfID = '$bedrijf_id'");
Your question isn't super clear, but if you're just trying to do a simple join where the id on table 1 = id on table 2, then the below statement would work. If that's what you're attempting to do, then the AND statement is redundant. Hard to know what you're going for without a clearly defined question with clearly defined variables. Also, use prepared statements as shown below rather than inserting variables directly into your statement. And avoid SELECT * whenever possible. Only select what is absolutely necessary.
$query = $conn->prepare("SELECT * FROM bedrijven b
LEFT JOIN vacatures v
ON b.id = v.id
WHERE v.id = :id");
$query->bindValue(':id', $id);
$query->execute();
The '$id' will be treated as string not as variable.and you need to specify the id as table.id if both of the tables have a field called id.
$query = $conn->query("SELECT * FROM $table LEFT JOIN vacatures ON bedrijven.id = vacatures.id WHERE $table.id = $id AND bedrijfID = $bedrijf_id");

joining two tables and fetching values from them error

i am joining the two tables but is giving me error that mysql_fetch_array() expects parameter 1 to be resource,
<?php
$result=mysql_query("SELECT * FROM `photo_gallery`.`photographs` WHERE id=1");
$result .=mysql_query("SELECT * FROM `photo_gallery`.`users` WHERE id=1");
while($row=mysql_fetch_array($result))
{
echo 'You are Welcome'.'<br/>';
$Id=$row['id'];
$Name=$row['username'];
$Batch=$row['password'];
$Address=$row['first_name'];
$Course=$row['last_name'];
$filename=$row['filename'];
$type=$row['type'];
echo 'your ID is'.$Id.'<br/>'.'username '. $Name.'<br/>'.'your password '. $Batch.'<br/>'.'yor first name'. $Address. '<br/>'.'last'.$Course.'<br/>'.'file name is'.'<br/>'.$filename.'<br/>'.'type is '.$type;
}
?>
Here is the most easy syntax to use join function
$query=mysql_query("SELECT * FROM `databasename`.`firstablename` JOIN `seconddatabasename` ON firsttablename.id = secondtablename.id ");
If you want to work with join array than visit this link http://www.w3schools.com/php/func_string_join.asp.
I hope you get what join function is used for.
Try this.
$query = "SELECT * FROM photographs INNER JOIN users ON photographs.id = users.id";
$result = mysql_query($query);
you cannot chain mysql queries in php that way. you have 2 options.
create a real mysql join.
you can use the shorthand syntax:
SELECT * FROM `photographs` p, `users` u WHERE p.id = u.id AND id=1
or a real join:
SELECT * FROM `photographs` p INNER JOIN `users` u WHERE p.id = u.id AND id=1
might i suggest reading more about mysql joins:
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

PHP And MYSQ help

ok here is my php and mysql code:
where it is bold i wanted to the the uid from the online table and if it in there
where online.uid = '' i needed so it put the uid in there.
$sql = ("select accounts.id,
accounts.tgid,
accounts.lastactivity,
cometchat_status.message,
cometchat_status.status,
**online.uid**
from friends_list join accounts
on friends_list.fid = accounts.id
left join cometchat_status
on accounts.id = cometchat_status.userid
where friends_list.status = '1'
and **online.uid = ''**
and friends_list.uid = '".mysql_real_escape_string($userid)."'
order by tgid asc");
#sledge identifies the problem in his comment above (I'm not sure why he didn't post an answer).
You are selecting a column from the online table, but you don't include it in your FROM clause. You have to query from a table in order to reference its columns in other parts of the query. For example:
$sql = ("select accounts.id,
accounts.tgid,
accounts.lastactivity,
cometchat_status.message,
cometchat_status.status,
online.uid
from friends_list
join accounts on friends_list.fid = accounts.id
join online on ( ??? )
left join cometchat_status
on accounts.id = cometchat_status.userid
where friends_list.status = '1'
and online.uid = ''
and friends_list.uid = '".mysql_real_escape_string($userid)."'
order by tgid asc");
You need to fill in the join condition, because there's not enough information in your original post to infer how the online table is related to other tables.
PS: Kudos for using mysql_real_escape_string().

Categories