MySQL IF Condition in Where Clause - mysql

Is it possible to decide by IF Condition which Where Clause I want to choose.
Something like:
IF(DATE_FORMAT(DATE(akDate), '%a')='SAT', USE WHERECLAUSE1, USE WHERECLAUSE2)

This is the case you can still write using rather common WHERE statement such as this:
... WHERE
(
(DATE_FORMAT(DATE(akDate), '%a') = 'SAT')
AND
(WHERECLAUSE1)
)
OR
(
(DATE_FORMAT(DATE(akDate), '%a') != 'SAT')
AND
(WHERECLAUSE2)
)
where, of course, you should replace WHERECLAUSE1 and WHERECLAUSE2 with appropriate conditions.

Easy, you should read on Boolean Algebra. In your case, here we go:
A = WhereClause1
B = WhereClause2
X = Choice
You need to select lines with X && A OR lines with !X && B. So basically your expression will be: (X && A) || (!X && B). Which leads to:
(
(Choice AND WhereClause1)
OR
((NOT Choice) AND WhereClause2)
)

$query = " SELECT apt.apt_id,apt.reg_id,apt.u_id,apt.b_id,apt.apt_bathroom,apt.apt_size,apt.apt_rent,apt.apt_desc,apt.negotiable,apt.apt_status,apt.govt_program,building.b_borough,building.b_zipcode,building.b_type,building.b_intersection,building.b_intersection2,building.b_desc FROM apt LEFT JOIN building ON apt.b_id = building.b_id WHERE apt.apt_status = 1 AND ";
if ($search_size != 'empty')
{
$query .= "apt.apt_size = '".$search_size."' ";
if ($search_borough != 'empty' || $search_zipcode != 'empty' )
{
$query .= " AND ";
}
}
if ($search_borough != 'empty')
{
$query .= "building.b_borough= '".$search_borough."' ";
if ($search_zipcode != 'empty')
{
$query .= " AND ";
}
}
if ($search_zipcode != 'empty')
{
$query .= "building.b_zipcode = '".$search_zipcode."' ";
}
$query .= "ORDER BY apt.apt_id DESC LIMIT $start,$perpage ";
$query_run = mysql_query ($query);
if (!$query_run)
{
echo 'Error In the Query limit.';
}

Related

searching keywords with dynamic query

need quick help.
I am creating a dynamic MySQL query for keywords and wants to search only those keyword having more than 3 characters. I have created query but I don't know how to search only for more than three characters?
here is query I wrote
$returned_results = array ();
$where = "";
$keywords = preg_split('/[\s]+/', $keywords);
$total_keywords = count($keywords);
foreach ($keywords as $key=>$keyword)
{
$where .= "keywords LIKE '%$keyword%'";
if ($key != ($total_keywords - 1))
$where .= " OR ";
}
$query = "SELECT title, url FROM pages WHERE $where";
In the where clause you add the code below
and CHAR_LENGTH('keywords') > 3
With this clause you get the lines which keyword length it more than 3
You may use strlen to filter keywords which have length greater than 3 chars.
foreach ($keywords as $key=>$keyword){
if(strlen($keyword) > 3){
$where .= "keywords LIKE '%$keyword%'";
if ($key != ($total_keywords - 1))
$where .= " OR ";
}
}

adding a condition to a WHERE clause based on a passed variable value mysql

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!

Database Query - Order by two values (Nested Order)

I want to order results by two database values: rating_full followed by rating_count
Currently, Im ordering by the highest rating_full. it works fine.
$sql .= " LEFT JOIN {$wpdb->postmeta} rating ON ({$wpdb->posts}.ID = rating.post_id AND rating.meta_key IN ('rating_full'))";
…
…
$sql = "cast(rating.meta_value as decimal(10,2)) {$order}";
……
The first line of code, part of the SELECT statement, retrieves the rating_full part
The second line of code is the ORDER BY part, which currently just uses the rating_count
As far as I can tell rating.meta_value referred to in the second line of code is the rating_full value
I'm trying to get it to ORDER BY rating_full, rating_count
I'm not sure how to modify the first line so that I can achieve this.
Thanks
FULL CODE:
<?php
// Sorting
add_filter('posts_join', 'directorySortingJoin',10,2);
function directorySortingJoin($join, $query) {
global $wpdb, $aThemeOptions;
if ($query->is_main_query() && !$query->is_admin && ((isset($_GET['dir-search'])) || (isset($query->query_vars["a-dir-item-category"])) || (isset($query->query_vars["a-dir-item-location"])))) {
$sql = "";
// default ordering
$orderby = (isset($aThemeOptions->directory->defaultOrderby)) ? $aThemeOptions->directory->defaultOrderby : 'post_date';
// get from get parameters
if (!empty($_GET['orderby'])) {
$orderby = $_GET['orderby'];
}
if ($orderby == 'rating') {
$sql .= " LEFT JOIN {$wpdb->postmeta} rating ON ({$wpdb->posts}.ID = rating.post_id AND rating.meta_key IN ('rating_full'))";
//$sql .= " LEFT JOIN {$wpdb->postmeta} rating ON (wp_posts.ID = rating.post_id AND rating.meta_key IN ('rating_full')) LEFT JOIN {$wpdb->postmeta} count ON ({$wpdb->posts} = count.post_id AND count.meta_key IN ('rating_count'))";
}
if ($orderby == 'packages') {
directorySaveUserPackagesToDb();
$sql .= " LEFT JOIN {$wpdb->usermeta} packages ON ({$wpdb->posts}.post_author = packages.user_id AND packages.meta_key IN ('dir_package'))";
}
if (isset($aThemeOptions->directory->showFeaturedItemsFirst)) {
$sql .= " LEFT JOIN {$wpdb->postmeta} featured ON ({$wpdb->posts}.ID = featured.post_id AND featured.meta_key IN ('dir_featured'))";
}
$join .= $sql;
//echo $join;
}
return $join;
}
add_filter('posts_orderby', 'directorySortingOrderby',10,2);
function directorySortingOrderby($orderby, $query) {
global $wpdb, $aThemeOptions;
if ($query->is_main_query() && !$query->is_admin && ((isset($_GET['dir-search'])) || (isset($query->query_vars["a-dir-item-category"])) || (isset($query->query_vars["a-dir-item-location"])))) {
$sql = "";
// default ordering
$orderby = (isset($aThemeOptions->directory->defaultOrderby)) ? $aThemeOptions->directory->defaultOrderby : 'post_date';
$order = (isset($aThemeOptions->directory->defaultOrder)) ? $aThemeOptions->directory->defaultOrder : 'DESC';
// get from get parameters
if (!empty($_GET['orderby'])) {
$orderby = $_GET['orderby'];
}
if (!empty($_GET['order'])) {
$order = $_GET['order'];
}
if ($orderby == 'rating') {
if (isset($aThemeOptions->directory->showFeaturedItemsFirst)) {
$sql = "featured.meta_value DESC, convert(rating.meta_value, decimal) {$order}";
} else {
//$sql = "convert(rating.meta_value, decimal) {$order}";
$sql = "cast(rating.meta_value as decimal(10,2)) {$order}";
//$sql = "cast(rating.meta_value as decimal(10,2)) {$order}, count.meta_value {$order}";
}
} else if ($orderby == 'packages') {
if (isset($aThemeOptions->directory->showFeaturedItemsFirst)) {
$sql = "featured.meta_value DESC, packages.meta_value {$order}";
} else {
$sql = "packages.meta_value {$order}";
}
} else {
if (isset($aThemeOptions->directory->showFeaturedItemsFirst)) {
$sql = "featured.meta_value DESC, {$wpdb->posts}.{$orderby} {$order}";
}
}
$orderby = $sql;
//echo $orderby;
}
return $orderby;
}
// Save directory packages for sorting
function directorySaveUserPackagesToDb() {
$users = get_users();
// capabilities list
$roles = array(
'administrator' => 10,
'directory_5' => 9,
'directory_4' => 8,
'directory_3' => 7,
'directory_2' => 6,
'directory_1' => 5,
'editor' => 4,
'author' => 3,
'contributor' => 2,
'subscriber' => 1
);
foreach ($users as $user) {
if (isset($user->roles[0])) {
if (array_key_exists($user->roles[0], $roles)) {
update_user_meta($user->ID, 'dir_package', $roles[$user->roles[0]]);
} else {
update_user_meta($user->ID, 'dir_package', 0);
}
}
}
}
The MySQL documentation for ORDER BY should be helpful here, particularly the last paragraph on sorting multiple columns.
Your ORDER BY should be something like
ORDER BY rating_full DESC, rating_count DESC

mySQL query from two different tables with mutual conditional

Please help me to structure mysql query
I have 2 tables, #_udjacomment AND #_content
currently I have query:
$query = "SELECT udja.id";
if( $include_author == 1 ) $query .= ", udja.full_name";
if( $include_date == 1 ) $query .= ", udja.time_added";
if( $include_comment == 1 ) $query .= ", if(CHAR_LENGTH(udja.content) > ".$content_number_of_characters.", SUBSTR(udja.content, 1, ".$content_number_of_characters."), udja.content) AS content";
if( $include_link_to_comment == 1 ){
$query .= ", CASE WHEN LOCATE('com_content:', udja.comment_url) > 0
THEN CONCAT(SUBSTRING_INDEX(udja.comment_url,':',-1),'-', com_content.alias, '.html')
ELSE udja.comment_url END AS comment_url";
}
$query .= " FROM #__udjacomments AS udja, #__content AS com_content WHERE udja.is_published = 1 AND com_content.id = SUBSTRING_INDEX(udja.comment_url,':',-1) AND com_content.checked_out = 0 ORDER by udja.id DESC limit ".$number_of_comments;
But I am not getting the proper results. If I stop trying to access from the table #__content AS com_content, then I get the results for #__udjacomment AS udja correct
So, I guess I am asking how can indicate and include the constrain that I want the field com_content.alias WHERE com_content.id = SUBSTRING_INDEX(udja.comment_url,':',-1)
In some cases, udja.comment_url will have this format com_content:22, com_content:19
and in other instances, udja.comment_url will have a string like word-word-another-word
this is why I have the more extensive statement inside the conditional if($include_link_to_comment == 1)
UPDATE: THE FINAL QUERY LOOKED LIKE THIS (I IMPLEMENTED WHAT RESPONDER SUGGESTED AND CHANGED THE CASE STATEMENT AND THE WHERE STATEMENT)
$query = "SELECT udja.id";
if( $include_author == 1 ) $query .= ", udja.full_name";
if( $include_date == 1 ) $query .= ", udja.time_added";
if( $include_comment == 1 ) $query .= ", if(CHAR_LENGTH(udja.content) > ".$content_number_of_characters.", SUBSTR(udja.content, 1, ".$content_number_of_characters."), udja.content) AS content";
if( $include_link_to_comment == 1 ){
$query .= ", CASE
WHEN LOCATE('com_content:', udja.comment_url)<>0
THEN CONCAT(SUBSTRING_INDEX(udja.comment_url,':',-1),'-', com_content.alias, '.html')
ELSE udja.comment_url
END AS comment_url";
}
// THEN CONCAT(SUBSTRING_INDEX(udja.comment_url,':',-1),'-', com_content.alias, '.html')
$query .= " FROM #__udjacomments AS udja
LEFT JOIN #__content AS com_content
ON com_content.id = SUBSTRING_INDEX(udja.comment_url,':',-1)
WHERE udja.is_published = 1 ORDER by udja.id DESC limit ".$number_of_comments;
You need to use an outer join:
...
FROM #__udjacomments AS udja
LEFT JOIN #__content AS com_content
on com_content.id = SUBSTRING_INDEX(udja.comment_url,':',-1)
WHERE ...

MySql LIKE returns false if search term is same as entire string in the column, why is that?

So I have following as part of my query
SELECT * FROM $table WHERE columname LIKE '%$searchterm%'
I have tried taking out leading and/or ending wildcards meaning
SELECT * FROM $table WHERE columname LIKE '$searchterm%'
AND
SELECT * FROM $table WHERE columname LIKE '%$searchterm'
AND
SELECT * FROM $table WHERE columname LIKE '%$searchterm%' OR columname LIKE '$searchterm'
and also tried adding following to the query with no luck
OR columname = '$searchterm'
So when my search term is "myval" and if column has whole string "myval", I would like to have that selected. But ALL of my queries above, return false/return nothing where myval is searchterm and column value as full.
I can not use MATCH because this is not Full-Text index.
EDIT:
PHP Code:
$sterm = NULL;
$table = 'mytable';
if(isset($_GET['s'])) { $sterm = explode(" ", mysql_real_escape_string($_GET['s'])); }
if(isset($_POST['s'])) { $sterm = explode(" ", mysql_real_escape_string($_POST['s'])); }
if(!empty($sterm)){
$getdata = "SELECT * FROM $table WHERE termsi != 'Special' ";
foreach ($sterm as $value){
$getdata .= "AND netid_all LIKE '%$value%' OR netid_all = '$value' ";
} //End foreach
$getdata .= "LIMIT 10";
$result = mysql_query($getdata) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo <<<PRINTALL
{$row[0]}, {$row[1]}, {$row[2]}, {$row[3]}, {$row[4]}, {$row[5]}, {$row[6]}, {$row[7]}, ' <br />'
PRINTALL;
} //End While
} //End If search exists
Okay So As you guys suggested, i tried PHPMyAdmin sql console and it works fine, so it would have to be by PHP!? so here it is.
I'd suggest writing your query building like this:
$fullvalues = array();
$partials = array();
foreach ($sterm as $value){
$partials[] = "(netid_all LIKE '%" . mysql_real_escape_string($value) . "%')";
$fullvalues[] = "'" . mysql_real_escape_string($value) . "'";
}
$partials = implode(' OR ', $partials);
$fullvalues = implode(', ', $fullvalues);
$sql = <<<EOL
SELECT *
FROM $table
WHERE (termsi != 'Special')
AND (($partials) OR (netid_all IN ($fullvalues));
EOL;
Assuming your search string is a b c, you'd get this query:
SELECT *
FROM yourtable
WHERE (termsi != 'Special')
AND (((netid_all LIKE '%a%') OR (netid_all LIKE '%b%') OR (netid_all LIKE '%C%')) OR (netid_all IN ('a', 'b', 'c')))
If your search requires that all terms be present, then change the 'OR' to 'AND' in the implode.
Well found it,
$row = mysql_fetch_array($result, MYSQL_ASSOC);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
Was the problem, earlier when I was testing things, anyhow, it should have been the following
$row = mysql_fetch_array($result, MYSQL_ASSOC);
while($row)