Explode element limit and Order By using - php

I wanna make this select with ORDER BY element and Limit Element But i cant solve it .. please help me..
I am doing a php chat bot tha find something on my database and reply ..but when i am selecting data it select many data in on time . thats whyy i nedd limit
$aKeyword = explode(" ",$keyword);
$query ="SELECT * FROM reply_key WHERE reply_key_value like '%" . $aKeyword[0] . "%' ";
for($i = 1; $i < count($aKeyword); $i++) {
if(!empty($aKeyword[$i])) {
$query .= "OR reply_key_value like '%" . $aKeyword[$i] . "%' ";
}
}

You can add order by id desc and then limit 1 to get the latest record, however, you can remove that "desc" if you want the oldest record.
$query ="SELECT * FROM reply_key WHERE reply_key_value like '%" . $aKeyword[0] . "%' " ORDER BY id desc LIMIT 1

Related

select where like with an array

$tag = 'sky';
select rows where tags contains $tag:
$sql = "select * from images where tags like '%" . $tag . "%' order by date desc";
What if I have an array of tags:
$tags = array('sky', 'earth', 'sun'); // max 3
foreach($tags as $tag) {
$sql = "select * from images where tags like '%" . $tag . "%' order by date desc";
}
Is this the right way, especially regarding performances.
The table images has about 20.000 rows.
You can use regexp.
$sql = "select * from images where tags REGEXP '" . implode('|', $tags) . "' order by date desc";
Your final result will be:
select * from images where tags REGEXP 'sky|earth|sun' order by date desc
Here is a possible implementation, you don't have to know the array size.
$tags = array('one', 'two');
$sql = "select * from images where tags like '%" . implode("%' OR tags like '%",$tags) . "%' order by date desc";
Add multiple tags to your query using OR in your query
$sql = "select * from images where tags like '%" . $tag[0] . "%' OR tags like '%" . $tag[1] . "%' OR tags like '%" . $tag[2] . "%' order by date desc";
You don't need to use foreach to run query
UPDATE 1
$comma_separated = "('" . implode("','", $tags) . "')";
$sql = "select * from images where tags IN ".$comma_separated;
Most Efficient Way
A REGEXP might be more efficient, you have to benchmark it by your self
$sql = "select * from images where tags REGEXP '" . implode('|', $tags) . "' order by date desc";

MySQL syntax error in string built by PHP

I have some code which generates a MySQL query string called $query:
$query = "select * from Surveys where surveylayoutid='$surveyid' and customerid='" . $_SESSION['login_customerid'] . "' and (";
$clue = $_POST['postcode'];
$onwhat="Postcode";
$query .= $onwhat . " like '%$clue%') order by id desc";
$result = mysql_query($query, $connection) or die(mysql_error());
This returns something like:
select * from Surveys where surveylayoutid='12' and customerid='1' and (Postcode like '%dn%') order by id desc
which works fine. I've then altered the code because I want to search on more fields so it now reads:
$remap = array("Postcode", "Street", "HouseNum", "District", "Town");
$query = "select * from Surveys where surveylayoutid='$surveyid' and customerid='" . $_SESSION['login_customerid'] . "' and (";
for ($i=0; $i<=4; $i++) {
if ($_POST[strtolower($remap[$i])]!="") {
$clue = $_POST[strtolower($remap[$i])];
$query .= $remap[$i] . " like '%$clue%') order by id desc";
break;
}
}
This also returns:
select * from Surveys where surveylayoutid='12' and customerid='1' and (Postcode like '%dn%') order by id desc
which on the face of it is identical but it generates this error:
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 'like '%dn%' order by id desc' at line 1
In both cases $query contains the same "text" but for some reason isn't treated as a valid MySQL query in the updated code, can anyone tell me why?
One possible problem could be the interpretation of the content here.
If you use:
$query .= $remap[$i] . " like '%$clue%') order by id desc";
All that is inside "" gets to be interpreted. Thus there could be unwanted side effects that you don't see at first glance and can explain what is happening. To avoid this it would have to be changed to:
$query .= $remap[$i] . ' like ' . "'" . '%' . $clue . '%' . "') order by id desc";
Even though more clunky in terms of how big it is, it makes sure that $lue and also the % are not interpreted as all in between ' ' is not interpreted.
See if this help you solve your problem?
$remap = array(
"Postcode",
"Street",
"HouseNum",
"District",
"Town"
);
for ($i = 0; $i <= 4; $i++)
{
if ($_POST[strtolower($remap[$i]) ] != "")
{
$query = "select * from Surveys where surveylayoutid='12' and customerid='1' and (";
$clue = $_POST[strtolower($remap[$i]) ];
$query.= $remap[$i] . " like '%$clue%') order by id desc";
$query_done[] = $query;
unset($query);
$result = mysql_query($query_done[$i], $connection) or die(mysql_error());
// Display your result here
}
}
I tried changing your code abit, and it seems the result is something like this
select * from Surveys where surveylayoutid='12' and customerid='1' and (Postcode like '%Postcode%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (Street like '%Street%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (HouseNum like '%HouseNum%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (District like '%District%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (Town like '%Town%') order by id desc

Why is this PHP / mySQL query giving me an error?

I am generating the first part of the query like this:
while ($all_products = $db->fetch_array($all_prods))
{
$filter_string .= 'AND product_id !=';
$filter_string .= $all_products['item_id'];
$filter_string .= ' ';
}
and then the second part like this:
$sql_more_items = $db->query("SELECT * FROM db_products
WHERE owner_id='" . $user_id . "' AND active=1 '" . $filter_string . "'
ORDER BY RAND() LIMIT 10");
However it's giving me a mySQL syntax error and the $filter_string part strangely adds ' twice before and after the string, so it runs like this:
WHERE user_id='12345' AND active=1 'AND product_id !=0001 AND product_id !=0002 ' ORDER BY RAND ...
What am I doing wrong?
$filter_string adds ' because you put it there. :P
Try with just the double quotes around $filter_string:
$sql_more_items = $db->query("SELECT * FROM db_products WHERE owner_id='" . $user_id . "' AND active=1 " . $filter_string . "ORDER BY RAND() LIMIT 10");
$sql_more_items = $db->query("SELECT * FROM db_products
WHERE owner_id='" . $user_id . "' AND active=1 '" . $filter_string . "'
ORDER BY RAND() LIMIT 10");
Check the way you're performing a string concatenation (putting together strings). It seems like there's a copy/paste error as you're using '" instead of just a "
I would use whitespace (and a good code editor) to your advantage by reformatting your code to look like this:
$queryString = "SELECT * FROM db_products WHERE owner_id='$user_id'"
." AND active=1 " //Note these
. $filter_string //are separated
. "ORDER BY RAND() LIMIT 10 "; //into individual lines
$sql_more_items = $db->query($queryString);
This style helps you keep track of whether you're using " or ' for your strings and also helps you debug things more easily than putting it into one giant hard to read string.
That's probably because of the part
`"' AND active=1 '"`
^.... This ' here

Where do I insert the ORDER BY in my MYSQL query

I need to have my results sorted by "ORDER BY prod_name" in my SQL statement but I cannot figure out get it to work. I tried after
$thisProduct .= " AND prod_type = 1 ORDER BY prod_name";
and also after
$thisProduct .= " AND ID = '" . mysql_real_escape_string($_GET['product']) . "' ORDER BY prod_name";
But I cannot get my results to sort correctly. Am I placing the order by in the wrong spot or did I query the DB incorrectly?
Thank you in Advance, I am still pretty new at MYSQL queries.
$thisProduct = "SELECT prod_name AS Name, days_span, CONCAT(LEFT(prodID,2),ID) AS ID, geo_targeting FROM products WHERE status = 'Active' AND vendID = ".$resort['vendID'];
if (isset($_GET['product']) AND is_numeric($_GET['product'])) {
$thisProduct .= " AND ID = '" . mysql_real_escape_string($_GET['product']) . "'";
}
else {
$thisProduct .= " AND prod_type = 1";
}
$thisProduct .= " LIMIT 1";
$getThisProduct = mysql_query($thisProduct);
if (!$getThisProduct/* OR mysql_num_rows($getThisProduct) == 0 */) {
header("HTTP/1.0 404 Not Found");
require APP_PATH . '/404.html';
die();
}
$thisProductData = mysql_fetch_assoc($getThisProduct);
You should have:
$thisProduct .= " ORDER BY prod_name";
$thisProduct .= " LIMIT 1";
(Note that the LIMIT 1 means you only get one record).
Assuming that your query is correct and you want the first product by name:
$thisProduct .= " ORDER BY prod_name LIMIT 1";
I believe it should go right before your "LIMIT 1", as in:
$thisProduct .= " ORDER BY prod_name LIMIT 1";
Insert it before the LIMIT
$thisProduct .= " ORDER BY prod_name LIMIT 1";
You can the select syntax at http://dev.mysql.com/doc/refman/5.0/en/select.html
SELECT query usually takes following form
SELECT which_all_to_select
FROM which_table/tables
WHERE criteria
ORDER BY column_name ASC/DESC;
ASC ascending order, and DESC is descending order
This orders query results by column_name specified in ORDER BY clause .

array_unique question

I have a search engine type website. It takes the users input, stores the query as $q, explodes the query and searches the database. It then displays the results with the name and web address of each result.
For example, if i searched for "computer programming"... Stack Overflow, stackoverflow.com would be my result. However, it displays twice. (once for computer, and once for programming.)
I tried to solve this with the array_unique function, and it does not work.
any help would be appreciated.
// trim whitespace
$trimmed = trim($q);
// seperate key-phrases
$trimmed_array = explode(" ", $trimmed);
// remove duplicates
$clean_array = array_unique($trimmed_array);
//query dataabase
foreach ($clean_array as $trimm){
$query = mysql_query("SELECT * FROM forumlist WHERE `keys` LIKE '%" . mysql_real_escape_string($trimm) . "%' ORDER BY rating DESC, total_ratings DESC") or die(mysql_error());
Thank you!
//query dataabase
$query = 'SELECT * FROM forumlist ';
$where = array();
foreach ($clean_array as $trimm){
$where[] = " `keys` LIKE '%" . mysql_real_escape_string($trimm) . "%' ";
}
if(!empty($where)){
$query .= " WHERE ". implode(' OR ', $where);
}
$query .= " ORDER BY rating DESC, total_ratings DESC";
$result = mysql_query($query) or die(mysql_error());

Categories