dividing database table data into two but what if count is odd - mysql

I want top half and bottom half of data of one table I am using queries which works fine when count is even
select count(*) from reviews
select * from reviews limit count/2
select * from reviews offset count/2
but these queries fails when count is odd
kindly give any solutions
php code
public function getdatedata($data,$data1){
if(empty($data) && empty($data1) ) return false;
$data1 = $data1/2;
$empty='';
$sql = "SELECT ";
$sql .= $this->reviews.".*";
$sql .= " FROM ".$this->reviews;
$sql .= " WHERE DATE(reviews_date) = '" . $data . "' LIMIT CEIL(". $data1.")";
$result = $this->db->query($sql);
if($result->num_rows > 0){
return $result;
} else
{ return $empty ;}
}

You can use CEIL to round the result:
select count(*) from reviews
select * from reviews limit CEIL(count/2)
select * from reviews offset CEIL(count/2)
You can also use FLOOR or ROUND, whatever you like.

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.

Fatal error: Call to a member function result() on a non-object in code igniter model working fine in localhost

this my model code:
function get_ads($page=0, $type, $limit=1, $order=' order by rand()') {
if ($page === 0) {
$page = $this->get_adpage();
$qry = "select * from tbl_ads ";
$qry .= " where status=1 and pages like '%".$page. "%'";
$qry .= " and type = ".intval($type);
$qry .= $order;
$qry .= intval($limit) > 1 ? " limit 0,".$limit : " limit 0,1";
$results = $this->db->query($qry)->result(); return $results;}
}
}
Query like this
SELECT * FROM tbl_ads WHERE STATUS=1 AND pages LIKE '%1%' AND TYPE = 1 ORDER BY RAND() LIMIT 0,1`
Controller code is
function get_ads(){
$this->main_model->get_ads(14,2,1);
}
Its working fine local when uploading to server showing fatal error some times but some times its working fine.
Thanks for your help
Here the solution
$this->db->query($qry)->result() in this instead of result() result_array() for multiple rows or row_array() for single row of result did the trick

SQL Like Statement with multiple WHERE clauses

I am having an issue getting this to work. I have multiple WHERE statements that need to happen based on conditional information from the search query. Within there I can't seem to get the LIKE statements to work.
In the database the STREET_NUM & STREET_NAME are in different rows. I am using one input field to check against called $address
I am also struggling with getting the MIN & MAX to work.
Here is the Query:
$sql = "SELECT * FROM arc_property_res WHERE ( arc_property_res.STATUS = 'Active'";
if(!empty($_GET['city'])){
// City only query!
$sql .= "AND arc_property_res.CITY = '{$_GET['city']}'";
}
if(!empty($_GET['neighborhood'])){
// Hood only query!
$sql .= "AND arc_property_res.SUBDIVISION = '{$_GET['neighborhood']}'";
}
if(!empty($_GET['mls-number'])){
// MLS only query!
$sql .= "AND arc_property_res.MLS_ACCT = '{$_GET['mls-number']}'";
}
if(!empty($_GET['min-price']) && !empty($_GET['max-price'])){
// MIN AND MAX only query!
$sql .= "AND arc_property_res.LIST_PRICE = MIN('{$_GET['min-price']}') MAX('{$_GET['max-price']}')";
}
if(!empty($_GET['num-of-beds'])){
// BEDS only query!
$sql .= "AND arc_property_res.BEDROOMS = '{$_GET['num-of-beds']}'";
}
if(!empty($_GET['num-of-baths'])){
// BATHS only query!
$sql .= "AND arc_property_res.BATHS_FULL = '{$_GET['num-of-baths']}'";
}
if(!empty($_GET['mls-number'])){
// BATHS only query!
$sql .= "AND arc_property_res.MLS_ACCT = '{$_GET['mls-number']}'";
}
if(!empty($_GET['address'])){
$sql .= "AND arc_property_res.STREET_NUM LIKE '%{$_GET['address']}'";
$sql .= "OR arc_property_res.STREET_NAME LIKE '{$_GET['address']}%'";
}
$sql .= ") ORDER BY {$orderby}{$price_order}{$comma}{$list_date}";
I think all you need are some parentheses around the arc_property_res.STREET_NUM. Further, I would recommend you add some spaces around each line in your entire code so that you don't get syntax errors.
if(!empty($_GET['address'])){
$sql .= " AND (arc_property_res.STREET_NUM LIKE '%{$_GET['address']}' ";
$sql .= " OR arc_property_res.STREET_NAME LIKE '{$_GET['address']}%') ";
}
In addition to the obvious "Bobby Tables" issue that your query has, the problem at hand is that you do not insert a space in front of AND. This results in queries that look like this:
AND arc_property_res.BEDROOMS =3AND arc_property_res.BATHS_FULL =2
Note that there is no space between 3 and AND - a syntax error.
You should look into parametrizing your queries, and modifying it in a way that ignores the parameters that have been set to NULL.
SELECT * FROM arc_property_res WHERE ( arc_property_res.STATUS = 'Active'
AND (arc_property_res.CITY = #cityParam OR #cityParam is NULL)
AND (arc_property_res.SUBDIVISION = #subdiv OR #subdiv is NULL)
...
)
This modification would let you keep the query the same regardless of the number of parameters that were actually set, get you the same results, taking pretty much the same time.
$sql .= "AND arc_property_res.LIST_PRICE = MIN('{$_GET['min-price']}') MAX('{$_GET['max-price']}')";
The min and max functions are for when you want to get the min and max of a field in your database.
What you want is to compare the list price to see if it falls in between the min and max values supplied by the user.
$sql .= " AND arc_property_res.LIST_PRICE >= '{$_GET['min-price']}' AND arc_property_res.LIST_PRICE <= '{$_GET['max-price']}'";

how would I change this over to do a full text search instead of LIKE?

after some researching I put this code together to search a mysql table in the db. while it works fine, it limit itself to match the words exactly as the user enters it. anyone know how to make it so that it matches my some sort of relevancy? I have been reading about the full text search but I cant really seem to grasp it.
for example, if you search for 'unanswered questions' in two fields, I want to be able to get result like that include the searched word(s) in any string that it show up in, and list it according to relevancy, like so (search results example output):
- unanswered questions
- answered questions
- answer question
- unanswered questions
- unanswered questions
- questions
- answer
$k = trim ($_GET['search']);
$i = "";
$terms = explode (" ", $k);
$query = "SELECT * FROM table1 WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "fld_title LIKE '%$each%' OR fld_keyword LIKE '%$each%' ";
else
$query .= "OR fld_title LIKE '%$each%' OR fld_keyword LIKE '%$each%' ";
}
// connect
include_once "connect.php"; //connect 2 db
$query = mysql_query($query);
$numrows = mysql_num_rows ($query);
if ($numrows > 0){
while ($row = mysql_fetch_assoc ($query)){
//
//
// echo out something here
//
//
}
}else
{
echo "No results found for <b>$k</b>";
}
to do a fulltext search you have to:
Create a Fulltext index in the table (note the fields can't be BLOB)
ALTER TABLE tablename ADD FULLTEXT(field1, field2,...);
in your case:
ALTER TABLE table1 ADD FULLTEXT(fld_title, fld_keyword);
in php change
$k = trim ($_GET['search']);
$i = "";
$terms = explode (" ", $k);
$query = "SELECT * FROM table1 WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "fld_title LIKE '%$each%' OR fld_keyword LIKE '%$each%' ";
else
$query .= "OR fld_title LIKE '%$each%' OR fld_keyword LIKE '%$each%' ";
}
for
$k = trim ($_GET['search']);
$query="SELECT * FROM table1 WHERE MATCH(fld_title, fld_keyword) AGAINST ('".$k."')";
if you want to see the relevancy of the results:
$query="SELECT *, MATCH(fld_title, fld_keyword) AGAINST ('".$k."') as relevancy FROM table1 WHERE MATCH(fld_title, fld_keyword) AGAINST ('".$k."')";
The MATCH-AGAINST returns a number: 0 for no match or other depending on matching.
You can "order by relevancy", change the query for make more relevant the search... MATCH(fld_title, fld_keyword) AGAINST ('".$k."') > 0.5
Only one problem: the AGAINST part ($k for you) must be greater than 3 characters.

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)