I have two variables in my WHERE statement. I cant seem to separate them with a space so i end up getting a syntax error. Thanks for the help.
(I am using codeigniter)
btw i have tried setting a $space variable, and putting spaces before the and, after setting both variables, and in the sql.
ERROR
Error Number: 1064
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 'source_adusers.ad_account="Wolfs, Marc" GROUP BY rollout_systems.eam_user LIMIT ' at line 2
SELECT *, COUNT(rollout_systems.EAM_USER) as systems FROM rollout_systems LEFT JOIN source_adusers ON rollout_systems.EAM_User = source_adusers.ad_account WHERE rollout_systems.scope_ID = 3AND source_adusers.ad_account="Wolfs, Marc" GROUP BY rollout_systems.eam_user LIMIT 0,50
Line Number: 330
PHP
if ($this->session->userdata('scopeId') != NULL) {
$where1 = 'WHERE rollout_systems.scope_ID = '. $this->session->userdata('scopeId') . '';
} else {
redirect('/headquarters/home');;
}
if ($search) {
$where2 = ' AND rollout_systems.sys_name ="'.$search.'"';
} else {
$where2 = '';
}
$query = $this->db->query('SELECT * FROM rollout_systems LEFT JOIN source_adusers
ON rollout_systems.eam_user = source_adusers.ad_account '. $where1 .''. $where2 .' GROUP BY rollout_systems.sys_name LIMIT '.$limit.',50');
what if you keep the spaces and the AND in the $query, instead of building them into your where variables? Then your $where 2 just needs to work without affecting the query - thus 0=0.
if ($this->session->userdata('scopeId') != NULL) {
$where1 = 'WHERE rollout_systems.scope_ID = '. $this->session->userdata('scopeId') . '';
} else {
redirect('/headquarters/home');;
}
if ($search) {
$where2 = 'rollout_systems.sys_name ="'.$search.'"';
} else {
$where2 = '0=0';
}
$query = $this->db->query('SELECT * FROM rollout_systems LEFT JOIN source_adusers
ON rollout_systems.eam_user = source_adusers.ad_account '. $where1 .' and '. $where2 .' GROUP BY rollout_systems.sys_name LIMIT '.$limit.',50');
Just add a space between the two vars - '. $where1 .' '. $where2 .'
As pointed out by others you really should be escaping your user input using mysql_real_escape_string() or intval() if you are expecting an integer value. If you are using PDO or mysqli use prepared statements.
If $this->db is a PDO instance you could use -
$params = array();
if ($this->session->userdata('scopeId') != NULL) {
$where = 'WHERE rollout_systems.scope_ID = ?';
$params[] = $this->session->userdata('scopeId');
} else {
redirect('/headquarters/home');;
}
if ($search) {
$where .= ' AND rollout_systems.sys_name = ?';
$params[] = $search;
}
$sql = "SELECT * FROM rollout_systems
LEFT JOIN source_adusers ON rollout_systems.eam_user = source_adusers.ad_account
$where
GROUP BY rollout_systems.sys_name
LIMIT ?, 50";
$params[] = $limit;
$query = $this->db->prepare($sql);
$query->execute($params);
$where = array();
if ($this->session->userdata('scopeId') != NULL) {
// better to escape your parameter here unless you trust it totally
// judging by its name, it's user-provided data, so I wouldn't trust it
$where[] = 'rollout_systems.scope_ID = '. $this->session->userdata('scopeId');
} else {
redirect('/headquarters/home');
// you may need to exit here after redirection, depends on your implementation
}
if ($search) {
// once again don't forget to escape $search in real application
$where[] = "rollout_systems.sys_name = '" . $search . "'";
}
$query = $this->db->query("
SELECT
*
FROM
`rollout_systems`
LEFT JOIN
`source_adusers`
ON rollout_systems.eam_user = source_adusers.ad_account
WHERE
" . implode (' AND ', $where) . "
GROUP BY
rollout_systems.sys_name
LIMIT " . $limit /* escape it! */ . ",50"
);
You also have the option to use the PHP syntax
$sql = " blah blah {$my_var} {$my_other_var} ";
Related
I've got a pretty complex SQL statement and want to add a WHERE clause that only selects results WHERE the hidden column IS NOT '1', however it needs to relate to a specific user.
i.e If in table 1 hidden is 1 and userid is 1 I don't want to get this results. However as there is no record for user 2 in that table I want them to see it.
This is what I have managed to get working so far:
$where .= " AND uh.hidden IS NULL ";
However if I login as User 2 then I see the same results as user 1.
How do I make it so results are shown based on the user too?
SQL query:
$pdo = new PDO('mysql:host=localhost;dbname=myDB', 'root', 'root');
$select = 'SELECT tl.id,
tl.name,
tl.locale,
ROUND(AVG(pr.rating),0) AS rating ';
$from = ' FROM theList AS tl ';
$join = ' LEFT JOIN post_rating AS pr ON tl.id = pr.postid ';
$join2 = ' LEFT JOIN user_hidden_list AS uh ON uh.est_id = tl.id ';
$opts = isset($_POST['filterOpts']) ? $_POST['filterOpts'] : [''];
$where = ' WHERE 1 = 1 ';
if (in_array("pub", $opts)) {
$where .= " AND pub = 1";
}
if (in_array("bar", $opts)) {
$where .= " AND bar = 1";
}
$where = ' WHERE uh.hidden IS NULL ';
$group = ' GROUP BY tl.id, tl.name ';
$sql = $select . $from . $join . $join2 . $where . $group;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
I have this little issue with sql that doesn't function. I have a query which grows based on specific critera. Here it is
$SELECT = ' SELECT * ';
$FROM = ' FROM a ';
$WHERE = ' WHERE TRUE ';
$how = ' GROUP By a_id ';
$result = mysqli_query($link, $SELECT . $FROM . $WHERE . $how );
This works but the second stage doesn't
$FROM .= " INNER JOIN b ON b_aid = a_id";
$WHERE .= " AND b_id = $id";
Specifically, the additional $WHERE . causes an undefined variable. If it is removed, I can see within the array the line I am after.
The normal query $result = mysqli_query($link, $SQL) works ok for the above;
Thanks
i am trying to write a dynamic sql query. the query works ok with intergers. however once i tried to insert a string it fails.
below is my query:
public function getList($params['SearchBy'])
{
$select = "
SELECT
u.id, u.firstName,u.lastName,u.city";
$from = "
FROM
user u";
$where = "
WHERE
u.live = 1 ";
if(isset($params['SearchBy']))
{
$where .= 'AND '. implode(' AND ', $params['SearchBy']);
}
$GroupBy = "
GROUP BY
u.id ";
$sql = $select.$from.$where.$GroupBy;
}
for the searchby(), i dynamically produce these values from a search query; i then place these in an array.:
$this->searchBy[$key][] = $key.' = '. $val;
this works perfectly when its an integer. however strings need to have "" . i am not sure to escape the ""so that it shows up in the query.
i.e
$this->searchBy[$topkey][] = $key.' = '. "$val";
i tried doing this but it did not work:
$this->searchBy[$topkey][] = $key.' = '. \"$val\";
would appreciate any advice on how to escape it.
thank you.
below is the raw sql query-derived from the search ;
SELECT
u.id,u.picNo,
u.membershipType,
u.firstName,u.lastName
FROM
user u
LEFT OUTER JOIN
table_messages_between_members sm
ON
u.id = sm.senderId
LEFT OUTER JOIN
list_photos_uploaded_by_members ph
ON
u.id = ph.userId
WHERE
u.live = 1 AND u.membershipType = 1 AND u.city = London
GROUP BY
u.id
ORDER BY
The trivial solution would be
$this->searchBy[$topkey][] = $key.' = "'. $val .'"';
This approach, especially if available public by allowing end user to write/input values, can be a major security threat and you should escape the input values or use PDO (even better).
I have a pdo command like this $sql = $pdoObj->execute($query) but it does not work, 0 result returning. I echo'ed out the $query variable just before calling execute() and then pasted it inside the execute() and the code ran successfully. I can't understand what is the problem here as I have done this in other parts of my code without problems.
Here are some examples of the queries:
SELECT s.id, s.marca, s.colore, s.prezzo, i.id_scarpa, i.taglia FROM scarpe AS s INNER JOIN info_scarpe AS i ON i.id_scarpa = s.id WHERE 1 = 1 AND taglia IN ('40','41','42') AND colore IN ('rosso', 'nero')
SELECT * FROM scarpe WHERE 1=1
SELECT * FROM scarpe WHERE 1=1 AND marca IN ('adidas','nike')
They are all dynamic generated queries based on the $_GET variable.
EDIT:
Sure
if ( isset($_GET) ) {
if ( isset($_GET['taglia']) ) {
$query = "
SELECT
s.id, s.marca, s.colore, s.prezzo, i.id_scarpa, i.taglia
FROM
scarpe AS s
INNER JOIN
info_scarpe AS i
ON i.id_scarpa = s.id
WHERE
1 = 1
";
foreach ( $_GET as $index => $val ) {
$a = explode(',', $val);
$in = "'" . implode("','", $a) . "'";
$query .= ' AND '.$index.' IN ('.$in.')';
}
} else {
$query = " SELECT * FROM scarpe WHERE 1=1";
foreach ( $_GET as $index => $val ) {
$a = explode(',', $val);
$in = "'" . implode("','", $a) . "'";
$query .= ' AND '.$index.' IN ('.$in.')';
}
}
echo 'data loaded';
} else {
$query = " SELECT * FROM scarpe ORDER BY id DESC ";
}
EDIT2:
I use query() and not execute() but still does not work
The arguments for execute should be an array with query parameters. You mean to use either
$result = $pdoObj->query($query);
OR
$stmt = $pdoObj->prepare($query);
$stmt->execute();
I can search multiple value with mysql.
I need to implement SORT BY on it
This is my coding which is working perfect
$conditions = array();
if ($key) {
$conditions[] = 'job_title LIKE "%'.$key.'%"';
}
if ($category) {
$conditions[] = 'job_category = "'.$category.'"';
}
if ($location) {
$conditions[] = 'job_location = "'.$location.'"';
}
if ($country) {
$conditions[] = 'job_country = "'.$country.'"';
}
if ($salary) {
$conditions[] = 'job_salary >= "'.$salary.'"';
}
$sqlStatement = 'SELECT * FROM jobs JOIN job_category ON jobs.job_category=job_category.category_id '.implode(' AND ', $conditions);
When I apply SORT BY
like this
if ($sort)
{
$conditions[] = 'ORDER BY "'.$sort.'"';
$sqlStatement = 'SELECT * FROM jobs JOIN job_category ON jobs.job_category=job_category.category_id '.implode(' AND ', $conditions);
}
else
{
$sqlStatement = 'SELECT * FROM jobs JOIN job_category ON jobs.job_category=job_category.category_id '.implode(' AND ', $conditions);
}
result is
Blockquote
SELECT * FROM jobs JOIN job_category ON jobs.job_category=job_category.category_id job_location = "Manjeri" AND ORDER BY "job_salary"
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/work/mobjob/test.php on line 41
you shouldn't implode your order by as a condition.. it's not one..
just append it onto the end like so:
$sqlStatement = 'SELECT * FROM jobs JOIN job_category ON jobs.job_category=job_category.category_id ';
if( sizeof($conditions)) {
$sqlStatement .= ' WHERE ' . implode(' AND ', $conditions);
}
if($sort) {
$sqlStatement .= ' ORDER BY "'.$sort.'"';
}