left statement doesn't work properly in mysql - mysql

I used left statement and Locate to fet substring of some field in database to do (Show more). It is working properly but sometimes it's not working right.
This is the code :
function split_field($table = "d_book", $field = "bo_about", $length = 195) {
$tbl_field = "TRIM(".$table.".".$field.")";
$sql = "CONCAT(LEFT({$tbl_field}, IF(LENGTH({$tbl_field}) > {$length}, LOCATE(' ', {$tbl_field}, {$length}), {$length})),
IF(LENGTH({$tbl_field}) > {$length}, '...', ''))
AS `{$field}`";
return $sql;
}
$sql = "SELECT `bo_price`,`bo_id`, `bo_au_id`,`bo_name`,";
$sql .= split_field();
$sql .=",`bo_cover_img`, `bo_num_pages`, `d_book`.`bo_sec_id`, `d_section`.`sec_id`, `d_author`.`au_id`, `d_author`.`au_name`
FROM (`d_book`)
JOIN `d_section` ON `d_section`.`sec_id`=`d_book`.`bo_sec_id`
JOIN `d_author` ON `d_author`.`au_id`=`d_book`.`bo_au_id`
WHERE `d_book`.`bo_state` = '1'";
$sql .= " ORDER BY `d_book`.`bo_ord` DESC LIMIT $start_limit,20";
The problem is that some books that have string less than 195 don't appear totally.
Tip: all strings in arabic language

Related

SQl code analysis

Please i need help to analyze this code . I am bit confuse to interpret what it means . This is not a code i write but some else .
All i need to do is to understand it and able to implement it
somewhere else . Thank you
$sql = "select t0.userid,concat(t3.firstname,',',t3.lastname) as name,count(*) as quizs,sum(if(t0.finalgrade > 0,1,0)) as quiz, sum(t0.finalgrade) as grade";
$sql .= " from mdl_grade_grades t0";
$sql .= " left join mdl_grade_items t1 on( t0.itemid= t1.id and t1.courseid = 37 and (t1.itemname like '%Daily Quiz%' or t1.itemname in ('Mid Term Exam','FINAL EXAM')))";
$sql .= " left join mdl_user t3 on(t3.id=t0.userid)";
$sql .= " where t0.userid >= 480";
$sql .= " group by t3.firstname,t3.lastname";
$res = mysql_query($sql);
$response->totalcount = mysql_num_rows($res);
$sql .= " Order by t3.firstname,t3.lastname";
$sql .= " Limit " .$start ."," .$limit ;
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)){
$attend = $row->gquiz / $row->quizs;
$grade = $row->grade / $row->gquiz;
$response->items[] = array('id' => $row->userid,'name' => $row->name,'attend' => $attend,'grade' => $grade);
}
//
echo json_encode($response);
The function sum(if(t0.finalgrade > 0,1,0)) actually counts the number of records having a finalgrade greater than 0.
The function sum(t0.finalgrade) simply sums the finalgrade of all records.
IF() is a builtin function and it's documented:
IF(expr1,expr2,expr3)
If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL), IF() returns expr2.
Otherwise, it returns expr3.
In your case:
if(t0.finalgrade > 0,1,0)
If final grade is greater than 0 then return 1, else return 0.
Finally, SUM() sums all these zeros and ones.
PHP code does not play any role in this MySQL logic.

SQL search multiple values in same field

I'm building a simple search algorithm and I want to break my string with spaces, and search my database on it, like so:
$search = "Sony TV with FullHD support";
$search = explode( ' ', $search );
SELECT name FROM Products WHERE name LIKE %$search[1]% AND name LIKE %$search[2]% LIMIT 6
Is this possible?
Yes, you can use SQL IN operator to search multiple absolute values:
SELECT name FROM products WHERE name IN ( 'Value1', 'Value2', ... );
If you want to use LIKE you will need to use OR instead:
SELECT name FROM products WHERE name LIKE '%Value1' OR name LIKE '%Value2';
Using AND (as you tried) requires ALL conditions to be true, using OR requires at least one to be true.
Try this
Using UNION
$sql = '';
$count = 0;
foreach($search as $text)
{
if($count > 0)
$sql = $sql."UNION Select name From myTable WHERE Name LIKE '%$text%'";
else
$sql = $sql."Select name From myTable WHERE Name LIKE '%$text%'";
$count++;
}
Using WHERE IN
$comma_separated = "('" . implode("','", $search) . "')"; // ('1','2','3')
$sql = "Select name From myTable WHERE name IN ".$comma_separated ;
This will works perfectly in both cases, one or multiple fields searching multiple words.
Hope this will help someone. Thanks
declare #searchTrm varchar(MAX)='one two three four';
--select value from STRING_SPLIT(#searchTrm, ' ') where trim(value)<>''
select * from Bols
WHERE EXISTS (SELECT value
FROM STRING_SPLIT(#searchTrm, ' ')
WHERE
trim(value)<>''
and(
BolNumber like '%'+ value+'%'
or UserComment like '%'+ value+'%'
or RequesterId like '%'+ value+'%' )
)
This has been partially answered here:
MySQL Like multiple values
I advise against
$search = explode( ' ', $search );
and input them directly into the SQL query as this makes prone to SQL inject via the search bar. You will have to escape the characters first in case they try something funny like: "--; DROP TABLE name;
$search = str_replace('"', "''", search );
But even that is not completely safe. You must try to use SQL prepared statements to be safer. Using the regular expression is much easier to build a function to prepare and create what you want.
function makeSQL_search_pattern($search) {
search_pattern = false;
//escape the special regex chars
$search = str_replace('"', "''", $search);
$search = str_replace('^', "\\^", $search);
$search = str_replace('$', "\\$", $search);
$search = str_replace('.', "\\.", $search);
$search = str_replace('[', "\\[", $search);
$search = str_replace(']', "\\]", $search);
$search = str_replace('|', "\\|", $search);
$search = str_replace('*', "\\*", $search);
$search = str_replace('+', "\\+", $search);
$search = str_replace('{', "\\{", $search);
$search = str_replace('}', "\\}", $search);
$search = explode(" ", $search);
for ($i = 0; $i < count($search); $i++) {
if ($i > 0 && $i < count($search) ) {
$search_pattern .= "|";
}
$search_pattern .= $search[$i];
}
return search_pattern;
}
$search_pattern = makeSQL_search_pattern($search);
$sql_query = "SELECT name FROM Products WHERE name REGEXP :search LIMIT 6"
$stmt = pdo->prepare($sql_query);
$stmt->bindParam(":search", $search_pattern, PDO::PARAM_STR);
$stmt->execute();
I have not tested this code, but this is what I would do in your case.
I hope this helps.
You can try and execute below query:
SELECT name FROM Products WHERE REGEXP '.*Value1|.*Value2';
Pls note that there should not be a space before or after the pipe symbol
(|).
I know this is long time ago, but I have a solution. It can solved like this:
#intial query
query = 'SELECT var1, var2 FROM dbo.db_name WHERE'
if status :
query = query + " AND status='" + status + "'"
if type :
query = query + " AND Type='" + type + "'"
if number :
query = query + " AND Number='" + number + "'"
if cancel_request:
query = query + " AND CancelRequest='" + cancel_request + "'"
query = query + ' ORDER BY transid DESC'
cur.execute(query)

can this phpbb query be optimized?

Here's some code adapted from phpBB. Near as I can tell it's trying to delete all topics wherein the only poster is the target user.
(note that for testing purposes I changed the final query from a DELETE to a SELECT)
<?php
$user_id = 66275;
mysql_connect('localhost', 'username', 'password');
mysql_select_db('db_name');
$start = microtime(true);
$total = 0;
define('POSTS_TABLE', 'phpbb_posts');
define('TOPICS_TABLE', 'phpbb_topics');
$sql = 'SELECT topic_id, COUNT(post_id) AS total_posts
FROM ' . POSTS_TABLE . "
WHERE poster_id = $user_id
GROUP BY topic_id";
$result = mysql_query($sql);
$topic_id_ary = array();
while ($row = mysql_fetch_assoc($result))
{
$topic_id_ary[$row['topic_id']] = $row['total_posts'];
}
mysql_free_result($result);
if (sizeof($topic_id_ary))
{
$sql = 'SELECT topic_id, topic_replies, topic_replies_real
FROM ' . TOPICS_TABLE . '
WHERE ' . sql_in_set('topic_id', array_keys($topic_id_ary));
$result = mysql_query($sql);
$del_topic_ary = array();
while ($row = mysql_fetch_assoc($result))
{
if (max($row['topic_replies'], $row['topic_replies_real']) + 1 == $topic_id_ary[$row['topic_id']])
{
$del_topic_ary[] = $row['topic_id'];
}
}
mysql_free_result($result);
if (sizeof($del_topic_ary))
{
$sql = 'SELECT topic_id FROM ' . TOPICS_TABLE . '
WHERE ' . sql_in_set('topic_id', $del_topic_ary);
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
$total++;
echo $row[topic_id] . "\r\n";
}
}
}
function sql_in_set($field, $array, $negate = false, $allow_empty_set = false)
{
if (!sizeof($array))
{
if (!$allow_empty_set)
{
// Print the backtrace to help identifying the location of the problematic code
$this->sql_error('No values specified for SQL IN comparison');
}
else
{
// NOT IN () actually means everything so use a tautology
if ($negate)
{
return '1=1';
}
// IN () actually means nothing so use a contradiction
else
{
return '1=0';
}
}
}
if (!is_array($array))
{
$array = array($array);
}
if (sizeof($array) == 1)
{
#reset($array);
$var = current($array);
return $field . ($negate ? ' <> ' : ' = ') . $var;
}
else
{
return $field . ($negate ? ' NOT IN ' : ' IN ') . '(' . implode(', ', $array) . ')';
}
}
$elapsed = microtime(true) - $start;
echo "\r\ntook $elapsed seconds";
echo "\r\ngot $total rows back";
?>
This does three queries. First gets all the topics the target user has posted in and the number of times they've posted in each topic. The second gets how many replies each topic in the first query actually has. Then there's some PHP code to see which topics have had all their posts made by the target user. After that the code (prior to my changes) DELETEs all those topics.
Overall it seems to me that this could be written better by doing something like this:
SELECT t.topic_id
FROM phpbb_topics AS t
JOIN phpbb_posts AS p1
ON p1.topic_id = t.topic_id
AND p1.poster_id = $poster_id
LEFT JOIN phpbb_posts AS p2
ON p2.topic_id = t.topic_id
AND p2.poster_id <> $poster_id
WHERE p2.poster_id IS NULL;
Or maybe this:
SELECT t.topic_id
FROM phpbb_topics AS t
JOIN phpbb_posts AS p1
ON p1.topic_id = t.topic_id
AND p1.poster_id = $poster_id
AND t.topic_poster = $poster_id
AND t.topic_last_poster_id = $poster_id
LEFT JOIN phpbb_posts AS p2
ON p2.topic_id = t.topic_id
AND p2.poster_id <> $poster_id
WHERE p2.poster_id IS NULL
Testing this is actually quite difficult thanks to MySQLs caching but... from what testing I have been able to do it seems like the way phpBB is currently doing it is in fact faster. Which is surprising to me.
Any ideas?
It looks to me like you are on the right track. Try adding indexes to all the columns you are using in the joins as this can often drastically increase the speed of joins.

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)