How to limit search results while using foreach and while loops - php

The following code works well, but I couldn't find a way to limit the number of results. Any ideas please?
$q = "some keywords for search"; // always escape
$keys = explode( " ",$q );
$query = "SELECT * FROM table WHERE para LIKE '%$q%' ";
foreach($keys as $k)
{
$query .= " OR para LIKE '%$k%'";
}
$result = $mysqli->query($query);
while( $row = $result->fetch_assoc())
{
if ($row != 0) {
$title = $row['title'];
}
}
Any help while be appreciated.
Note: the $q holds the search keywords, and then the code explode it, and search for the keywords in 2 steps:
1- as one sentence using ($q as it is).
2- it searches for each keyword as an array after exploding the $q (here is the part that the "foreach" does).
After that the code loops using "while" to find all results match the search request.

Use LIMIT after completing your query.
Also, if you want to get results sorted by some fields in your table, you could also say " ORDER BY fieldname ASC|DESC"
As follows:
$q = "some keywords for search"; // always escape
$keys = explode( " ",$q );
$query = "SELECT * FROM table WHERE para LIKE '%$q%' ";
foreach($keys as $k)
{
$query .= " OR para LIKE '%$k%'";
}
$query .= " LIMIT 10"; //<<<<<<<<<<<<<<<
$result = $mysqli->query($query);
while( $row = $result->fetch_assoc())
{
if ($row != 0) {
$title = $row['title'];
}

Use LIMIT.
SELECT * FROM table WHERE para LIKE '%$q%' LIMIT 2

You can limit the number of results in your MySQL query, like so:
$query = "SELECT * FROM table WHERE para LIKE '%$q%' LIMIT 5";
this will limit it to 5 results. If you want 10, change it to 10

Related

searching through sql

i want to make sql search
for now i am using this
$term="red sky";
$query=explode(' ', $term);
$sql = "SELECT * as result FROM `disk` WHERE ";
$a=0;
foreach ($query as $part)
{
$part=mysqli_real_escape_string($con, $part);
$a++;
if ($a==1)
{
$sql .= " title like '%".$part."%'";
}
else
{
$sql .= " and title like '%".$part."%'";
}
}
$sql = $sql." order by time desc";
$i=0;
if ($term!="")
{
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result);
}
so this results in showing results like:
vredy tskyi
redy sky
vredy sky
red sky
i want to order it somehow so it show "red sky" at first and other results are same so they can arrange themselves.
second thing--- this type of searching is a bit slow, i want to make it faster. please help me by making a new faster script or update in this one. (must work same but faster)
for more details plz comment. its hard to explain
Sorry, but your question is not clear enough.
I think this code should render fast.
$sql = ""; $add = "";
$term="red sky";
$query=explode(' ', $term);
foreach ($query as $part)
{
$add .= " title like '%".$part."%' and";
}
$add .= substr($add,0,-3);
$sql = "SELECT * as result FROM `disk` WHERE".$add."order by time desc";
if ($term!="")
{
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result);
}
And If you want to get the specific result on red & sky then you should use IN clause instead of LIKE.
Example:
$sql = "";$new= [];
$term="red sky";
$query=explode(' ', $term);
foreach($query as $part)
{
$new[].= "'".$part."'";
}
$term=implode(',', $new);
$sql = "SELECT * FROM `disk` WHERE title IN(".$term.") order by time desc";
if ($term!="")
{
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result);
}

Search more then one MySql table in Mysql Database PHP

I have a database have 20 tables I want to search all of these I got stuck that how can I search this and solve this query help is very appreciated. Like:
table1
table2
table3
table4
and so one. This is my script.
<?php
if(isset($_GET["search"]))
{
$condition = '';
//$query = explode(" ", $_GET["search"]);
$query = explode(" ", $_GET["search"]);
foreach($query as $text)
{
$condition .= "`title` LIKE +'%".mysqli_real_escape_string($connect, $text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$sql_query = "SELECT * FROM countries2 WHERE " . $condition;
$result = mysqli_query($connect, $sql_query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<tr><td>'.$row["title"].'</td></tr>';
}
}
else
{
echo '<label>Data not Found</label>';
}
}
?>
Try with this
sql_query = "SELECT * FROM `countries`,`countries2` WHERE " . $condition;
i have noticed that you are making a search directory or something like this.
you may use FULLTEXT SEARCH with operators and Stemming
after this your query will look like this.
implement as per your requirement ;).
(SELECT * FROM table1 WHERE(col1,col2,clo3) AGAINST(."$search".) IN NATURAL LANGUAGE MODE)

How can I loop through assoc array values and put the data into a function

I build a query which i get an assoc array from. But how can I loop through them. this is what I have.
My SQL Query:
public static function album_display() {
global $database;
$sql = "SELECT a.*, ";
$sql .= "(SELECT photographs.filename ";
$sql .= "FROM photographs ";
$sql .= "WHERE photographs.albumid = a.name ";
$sql .= "ORDER BY photographs.creation_date ASC ";
$sql .= "LIMIT 1) ";
$sql .= "AS filename FROM album a ";
$result_set = $database->query($sql);
while($rows = mysqli_fetch_assoc($result_set)){
foreach($rows as $row) {
print_r($row);
}
}
}
If I use print_r() on $row the output is:
15Jaap1Jaap1.JPG16Jaap2Jaap4.JPG17Jaap3Jaap7.JPG18Jaap4Jaap12.JPG19Jaap5
I want to loop through Jaap1, Jaap2, Jaap3, Jaap 4 and put these in $albumid from the function album_path($albumid, $filename). I want to do the same wiht the JPG files. This function is in Class() Album. So is the function album_display()
The function album_path($albumid, $filename) if called needs to output the complete album/images path en echo these to the screen. And display the images
public function album_path($albumid, $filename) {
return $this->upload_dir.DS.$albumid.DS.$filename;
}
How can I use foreach for this. Or is there an other better way to do it?
Kind Regards,
Coos Wolff
Change the select a.*, into a select a.albumid. That should only return you the album id, and the filename, coming from the second SELECT statement.
Perhaps something like this? You can break the sql up onto multiple lines within the quotes which makes it easier to read and also use an alias for each of the tables, again making it slightly easier to read and quicker to write.
<?php
public static function album_display() {
global $database;
$sql = "SELECT a.*,
( SELECT p.`filename`
FROM `photographs` p
WHERE p`.`albumid` = a.name
ORDER BY p.`creation_date` ASC
LIMIT 1
) AS 'filename' FROM `album` a ";
$result_set = $database->query( $sql );
/* using object notation rather than array for ease */
while( $rows = mysqli_fetch_object( $result_set ) ){
$this->album_path( $rows->albumid, $rows->filename );
}
}
?>
$my_array = [];
public static function album_display() {
global $database;
$sql = "SELECT a.*, ";
$sql .= "(SELECT photographs.filename ";
$sql .= "FROM photographs ";
$sql .= "WHERE photographs.albumid = a.name ";
$sql .= "ORDER BY photographs.creation_date ASC ";
$sql .= "LIMIT 1) ";
$sql .= "AS filename FROM album a ";
$result_set = $database->query($sql);
while($rows = mysqli_fetch_assoc($result_set)){
foreach($rows as $row) {
$my_array['albumid'][] = $row->albumid;
$my_array['filename'][] = $row->filename;
}
}
}
foreach ($my_array['albumid'] as $albumid) {
echo $albumid;
}
foreach ($my_array['filepath'] as $filepath) {
echo $filepath;
}
album_path($my_array['albumid'], $my_array['filepath']);
mysqli_fetch_assoc returns one row at a time from the result set built by your query.
Each $row is an associative array and if you look more closely at the output of the var_dump() you will see that the array is a set of key - value pairs.
while($rows = mysqli_fetch_assoc($result_set)){
//echo $row['id'];
//echo $row['filename'];
//echo $row['albumid'];
// just to be sure add this line
// so we know exactly whats in $row
print_r($row);
}
Sorry because you used SELECT * for the other fields I dont know what to call the array elements. I hope you get the basic idea.

Echo the 2 last columns of tabel

I have a table and i want to echo the 2 last rows of my tabel, I used the below code but just the last one showed, what is the problem.
$result1 =(mysql_fetch_array(mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")));
Print $result1['time'];
mysql_fetch_array = 1 fetch.
do it again for fetching 2nd result.
Also, use mysqli eh.
You're doing mysql_fetch_array only one time, so it gets the first element. If you want to get all the elements, then do it again, or use a loop.
Something like:
$query = "SELECT * FROM $table ORDER BY id DESC LIMIT 2";
while($row = mysql_fetch_array(mysql_query($query) )
{
echo $row['time'].'<br>';
}
For 2 Or more rows you need to loop it
$sql = mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")
while($row=mysql_fetch_array($sql))
{
echo $row['time']."<br>";
}
$query = mysqli_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2");
while ($result = mysqli_fetch_array($query)) {
echo $result['time'];
}
Gives out every return of your database (2 in this case). You should use mysqli_-functions.
Maybe you should try like this, since mysql_fetch_array returns only one row
while ($row = mysql_fetch_array($yourQuery)) {
echo $row["yourAlias"];
}
Further details here : http://fr2.php.net/manual/en/function.mysql-fetch-array.php
My solution:
$limit = 2;
$sql = "SELECT * FROM $table ORDER BY id DESC LIMIT $limit";
$result = mysql_query($sql);
$array = array(); $i = 0;
while($row = mysqli_fetch_array($result))
{
$array[$i] = $row;
$i++;
}
var_dump($array[0]);
var_dump($array[1]);

MySQL query within another query's while loop in PHP

I have the following code:
$query = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
while($result = mysql_fetch_array($query)) {
extract($result);
if ($activity_type == "discussion") {
$query = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
while($result = mysql_fetch_array($query)) {
extract($result);
echo $discussion_user . " said:<br>" . $discussion_text . "<br>";
}
} elseif ($activity_type == "file") {
}
}
But it just returns the last row. My goal is to have a chronological list of "activities" each displayed slightly differently depending on their type.
Your using $query and $result twice so the second loop is overwriting the result of the first and stopping...
$query = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
and
$query = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
same with $results var...
I would suggest you change to $query and $query2 but best to use something like
$activies = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
while($activity = mysql_fetch_array($activies)) {
and
$discussions = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
while($discussion = mysql_fetch_array($discussions)) {
I would also avoid using extract - as you might be overwriting vars your not expecting to...
You have to create another connection to the database so that you can run them at the same time.
OR
You can load the results of the first one into an array, and then just loop through the array.

Categories