God damn confused at the syntax for my MYSQL query.
Is this correct... Can't find an entry in internet similar to it.
$query_game_string = '';
while($game = mysql_fetch_assoc($get_game_list)){
$query_game_string .= ' OR target = "' . $game['id'] . '" AND ancestors = "0"';
}
echo '' . $query_game_string . '';
//prints: OR target = "11" AND ancestors = "0" OR target = "12" AND ancestors = "0" OR target = "27" AND ancestors = "0" OR target = "29" AND ancestors = "0" OR target = "32" AND ancestors = "0"
$database->connect();
$comments = mysql_query(
'SELECT *
FROM ' . $database->db_prefix . 'comments
WHERE user_id = "' . $user->user_object["id"] . '"' .
$query_game_string . '
ORDER BY created DESC'
, $database->connection_handle);
$database->close();
So the actual query would be in total:
'SELECT *
FROM ' . $database->db_prefix . 'comments
WHERE user_id = "' . $user->user_object["id"] . '"' .
'OR target = "11" AND ancestors = "0" OR target = "12" AND ancestors = "0" OR target = "27" AND ancestors = "0" OR target = "29" AND ancestors = "0" OR target = "32" AND ancestors = "0"' . '
ORDER BY created DESC'
Is the syntax okay?
Don't know exactly what your are looking for but probably you need parenthesis:
OR (target = "11" AND ancestors = "0")
OR (target = "12" AND ancestors = "0")
OR (target = "27" AND ancestors = "0")
OR (target = "29" AND ancestors = "0")
OR (target = "32" AND ancestors = "0")
php to achieve that:
while($game = mysql_fetch_assoc($get_game_list))
{
$query_game_string .= ' OR (target = "' . $game['id'] . '" AND ancestors = "0")';
}
a way to simplify the query is using IN operand
OR target IN("11","12","27","29","32") AND ancestors = "0"
php:
$targets = array();
while($game = mysql_fetch_assoc($get_game_list))
{
$targets[] = '"'.$game['id'].'"';
}
$query_game_string = ' OR target IN (' . implode(",",$targets) . ') AND ancestors = "0"';
Related
I am a relative novice and could use some help with this problem.
This will be used in a search filter situation.
Users need to search by a value and 1 or more other values passed by the search form.
$name = $_POST['name'];
$sdate = $_POST['sdate'];
$startdate = $_POST['startdate'];
$enddate = $_POST['enddate'];
$vehicle = $_POST['vehicle'];
$triptype = $_POST['triptype'];
If any of these values are '' I do not want them in the query, If they contain a value I do want them in the query.
SELECT * FROM form_data WHERE `resp_person` = '$name',
IF $sdate != '' then `sdate` = '$sdate',
IF $startdate != '' then `sdate` = *all values between $startdate and $enddate*,
IF $triptype != '' then `triptype` = '$vehicle',
IF $vehicle != '' then `vehicle` = '$vehicle', `sdate`
ORDER BY `sdate` DESC, `stime` DESC")
I know the code is wrong but it should give you a good idea of what I am trying to accomplish. Any guidance would be greatly appreciated.
A better way is to not use string concatenation to build the entire query, but rather use an sql library that supports prepared statements, such as PDO.
$pdo = new PDO('... connection string ...', username, password);
$where = '';
$possible_values = array('name', 'sdate', 'startdate', 'enddate', 'vehicle', 'triptype' );
$params = array();
foreach($possible_values as $val)
{
if(isset($_POST[$val]))
{
$params[] = $_POST[$val];
if($where == '')
{
$where = "WHERE $val = ?";
}
else
{
$where .= " AND $val = ?";
}
}
}
$stmt = $pdo->prepare("SELECT * FROM form_data " . $where);
$stmt->execute($params);
In cases like this, I prefer to build the query in pieces...
$wheres = array(); // Collect things to AND together
if ($searchterm != 'All') $wheres[] = "subject LIKE '%searchterm'";
if (...) $wheres[] = "...'";
...
if (count($wheres) > 0)
$where_str = "WHERE " . implode(' AND ', $wheres);
else
$where_str = '';
$order_str = (...) ? "ORDER BY ..." : '';
$limit_str = $limit ? "LIMIT $limit" : '';
$query = "SELECT ... FROM foo $where_str $order_str $limit_str";
Oh, and don't forget to use escape the strings on any data coming in from a form -- else a user can do nasty things to the SQL statement!
How can I update a table in the data base where the SET clause from MySQL query depends on variables? It can be one $var, two, or many more.
Here is my ex. code:
$name = 'comp_name = "'.$nume.'",';
$large = 'logolarge = "'.$linklogolarge.'",';
$small = 'logosmall = "'.$linklogosmall.'",';
...............................
$sql = 'UPDATE company
SET
'.$name.'
'.$large.'
'.$small.'
WHERE id_comp = 43 ';
The problem is that the normal syntax of the UPDATE query is that after SET .......between values needs a comma " , "
ex.
UPDATE table
SET
col1 = x ,
col2 = y ,
col3 = z
WHERE id = 4
and at the end before WHERE doesn't needs one ..... ( ex. after " z ")
So how can I make the sql query to accept different combination of those $var ...( only '.$name.' or '.$name.' and '.$large.' or only last two '.$large.' and '.$small.' .... etc)
basically any combination between those 3 var ...and maybe combining more than 3 var.
$name = "comp_name = '$nume'";
$large = "logolarge = '$linklogolarge'";
$small = "logosmall = '$linklogosmall'";
$sql = "UPDATE company SET " . $name;
if( ! is_null( $linklogolarge ) ) $sql = $sql . ", " . $large;
if( ! is_null( $linklogosmall ) ) $sql = $sql . ", " . $small;
$where = " WHERE id_comp = 43"; /* change this if required*/
$sql = $sql . $where;
echo $sql;
Here is my double-minded query:
$Quest = "SELECT * FROM TOAWorkorders";
$FindTechResult = mysql_query($Quest, $cxn)
or die ('The easter bunny is watching you' . mysql_error());
while ($row = mysql_fetch_array($FindTechResult))
{
if (strpos($BBT, 0, 3) != 'Sys')
{
$IdNum = $row['IdNum'];
$BBT = $row['BBT'];
$BBTArray = explode("-", $BBT);
$TechNum = $BBTArray["0"];
$Title = $BBTArray["2"];
$Name = explode(" ", $BBTArray['1']);
$FirstName = $Name["0"];
$LastName = $Name["1"];
}
echo $TechNum . ' !! ' . $FirstName . ' !! ' . $LastName . ' !! ' . $Title . '<br>';
$Quest = "UPDATE TOAWorkorders SET TechNum = '$TechNum', FirstName = '$FirstName', LastName = '$LastName', Title = '$Title' WHERE IdNum = '$IdNum'";
$result = mysql_query($Quest, $cxn) or die(mysql_error());
}
Everything works for about 2/3s of the database. That leaves 33,000 rows that are not updated. I cannot find any difference between the data that works and the data that doesn't.
Since you're doing an UPDATE, and you say the rest of the code works (meaning, I hope, that you get 109,112 echo'ed results), it must be that the ID isn't being found (WHERE IdNum = '$IdNum').
Try preceding that command with "SELECT COUNT(*) from TOAWorkorders WHERE IdNum = '$IdNum'" and see if you get 33,000 zeros when the program runs. If you do, then you have missing IdNum values in your table.
If you don't, please provide details and I'll let you know.
I'm attempting to modify a mySQL query (that works) to return a more specific result. I've added a variable to the statement so that it looks for jobID AND UserName. Adding the $userName to the statement breaks it.
I've included the code below with the three variations of the SQL statement for comparison. I'm sure it's something obvious - to everyone but me...
Thanks in advance!
DB
// get all applicants from a User
public function GetAllMyApplications($from=false, $to=false, $user_name)
{
global $db;
$applicants = array();
if ($from >= 0 && $to > 0)
{
$sql_limit = ' LIMIT ' . $from .', ' . $to;
}
else
{
$sql_limit = '';
}
$user_name = "Bob Bobberton"; // reset this var for testing
$sql = 'SELECT * FROM '.DB_PREFIX.'job_applications WHERE job_id = '. $this->mJobId . ' ORDER BY name ASC ' . $sql_limit; // This was the original SQL that worked
$sql = 'SELECT * FROM '.DB_PREFIX.'job_applications WHERE job_id = '. $this->mJobId . ' AND name = ' . $user_name . ' ORDER BY name ASC ' . $sql_limit; // Added "and" $user_name - it breaks
$sql = 'SELECT * FROM '.DB_PREFIX.'job_applications WHERE job_id = '. $this->mJobId . ' AND name = "Bob Bobberton" ORDER BY name ASC ' . $sql_limit; // Replace var with value "Bob Bobberton" and it works
$result = $db->query($sql);
while ($row = $result->fetch_assoc())
{
$applicants[] = array('id' => $row['id'],
'job_id' => $row['job_id'],
'name' => $row['name'],
'email_address' => $row['email_address'],
'message' => str_replace(array("\r\n", "\r", "\n"), "<br />", $row['message']),
'resume_path' => base64_encode($row['resume_path']),
'created_on' => $row['created_on'],
'ip' => $row['ip']);
}
if (isset($applicants))
{
return $applicants;
}else{
return("");
}
}
change this
' AND name = ' . $user_name . ' ORDER BY name ASC '
to
" AND name = '" . $user_name . "' ORDER BY name ASC "
and it will work
The solution provided by Satya is not enough. You should escape your inputs properly.
Assume your $username contains a " character. That will break your SQL statement. So you should use prepared statements or, at least, use the function mysql_real_string_escape().
I am using a Joomla module (ArogaRousel) that was made to display images of another module (AdsManager), and the module displays the following error:
No valid database connection 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 ')) ORDER BY views DESC, id
LIMIT 0, 9' at line 1 SQL=SELECT
*,concat('/images/com_adsmanager/ads/',id,'a.jpg')
as imgUrl FROM root_adsmanager_ads ,
root_adsmanager_adcat as ac WHERE
published=1 AND (ac.adid=id and
ac.catid IN ()) ORDER BY views DESC,
id LIMIT 0, 9
I am not proficient in mysql, but I have found the file where the query is being made.
This is the code where the query is being made
$query = "SELECT *,concat('/images/com_adsmanager/ads/',id,'a.jpg') as imgUrl FROM #__adsmanager_ads "
. $table
. " WHERE published=1 "
. $where
. $ordering
. $limit;
Could any of you, oh knowledgeable humans, indicate the error and the solution?
In response to Bemace here I add the whole function
// Get list of banners
function getAds(&$paramslist){
$where = array();
if ($paramslist['ads'] != '') $where[] = 'id IN (' . modArogarouselAdsmanagerHelper::cleanIds($paramslist['ads']) . ')';
if ($paramslist['categories'] != '') {
$where[] = 'ac.adid=id and ac.catid IN (' . modArogarouselAdsmanagerHelper::cleanIds($paramslist['categories']) . ')';
$table = ' , #__adsmanager_adcat as ac';
}
$where = (count($where) > 0) ? ' AND (' . implode(' OR ', $where) . ')' : '';
if ($paramslist['ordering'] == 1) {
$ordering = ' ORDER BY views DESC, id';
} else if ($paramslist['ordering'] == 2) {
$ordering = ' ORDER BY views ASC';
} else if ($paramslist['ordering'] == 3) {
$ordering = ' ORDER BY id';
} else if ($paramslist['ordering'] == 4) {
$ordering = ' ORDER BY RAND()';
}
$limit = ($paramslist['limit'] != '') ? ' LIMIT 0, ' . ($paramslist['limit']) : '';
$query = "SELECT *,concat('/images/com_adsmanager/ads/',id,'a.jpg') as imgUrl FROM #__adsmanager_ads "
. $table
. " WHERE published=1 "
. $where
. $ordering
. $limit;
$db = &JFactory::getDBO();
$db->setQuery($query);
$adslist = $db->loadObjectList();
$adslist = ($paramslist['mode_dir'] == 'bottom') ? array_reverse($adslist, true) : $adslist;
//print_r($adslist);
return $adslist;
}
The empty IN () right before the ORDER BY is the problem. You'll need to check the code that is setting the $where variable. It appears to be expecting at least one category to be selected but none appear to have been.