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)
Related
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);
}
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.
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
Am trying to join two tables with the same column but different values but each time i output it duplicates.
Here is my code:
<?php
$dept = $_SESSION['department'];
$dept1 = strtolower($dept);
$dept2 = str_replace(" ", "_", $dept1);
$dept4 = "$dept2" . "_200";
$dept = $_SESSION['department'];
$level = $_SESSION['level'];
$level2 = str_replace (" ", "_", $level);
if($level ="200_level") {
$query = " SELECT * FROM $dept2 Join $dept4";
}
else
{
$query = " SELCT * FROM $dept2";
}
$result = mysql_query($query) or die('<div class="header5"small_font">Your Courses are not available yet. Pls contact the ICT Unit</div>');
while ($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
$course = htmlspecialchars($row['course_name']);
$code = htmlspecialchars($row['course_code']);
$status = $row['status'];
$unit = htmlspecialchars($row['unit']);
?>
If you are looking to get the contents of two tables with the same columns, a MySQL UNION should help
UNION is used to combine the result from multiple SELECT statements into a single result set.
Like so:
$query = "(SELECT * FROM $dept2)
UNION
(SELECT * FROM $dept4)";
how would you do a mysql query where a user can choose from multiple options. Fox example I have a form that user can use to search for houses. Now I have a select box where you can chosse whether you want a house, a flat or whatever. Then I have a second box where you can choose for example the city you want the house or flat to be in. And maybe another one with the maximum price.
Now how would you do the mysql query? My problem is, I would do it like that:
if($_POST["house_type"] != 0) {
$select = mysql_query("SELECT * FROM whatever WHERE type = '".$_POST["house_type"]."'");
}
But now I only have the case that someone has chosen a house type but not any other option. So do I have to do an "if" for every possible combination of selected elements?
To emphasize my problem:
if(!isset($_POST["house_type"])) {
if($_POST["something"] == 0) {
$search_select = #mysql_query("SELECT * FROM housedata WHERE something = $_POST["whatever"]);
}
elseif($_POST["something"] != 0) {
$search_select = #mysql_query("SELECT * FROM housedata something = $_POST["whatever"] AND somethingelse = 'whatever');
}
}
elseif(!isset($_POST["house_type"])) {
if($_POST["something"] == 0) {
$search_select = #mysql_query("SELECT * FROM housedata WHERE something = $_POST["whatever"]);
}
elseif($_POST["something"] != 0) {
$search_select = #mysql_query("SELECT * FROM housedata something = $_POST["whatever"] AND somethingelse = 'whatever');
}
}
Now imagine I had like 10 or 20 different select boxes, input fields and checkboxes and I would have to do a mysql query depending on what of these boxes and fiels and checkboxes is filled. This would be a code that is extremely complicated, slow and horrible. So is there a possibility to make a mysql query like:
SELECT * FROM whatever WHERE house_data = '".$whatever."' AND (if(isset($_POST["something"])) { whatever = '".$whatever2."' } AND ...;
You get what I mean? Its a bit complicated to explain but actually its a very important question and probably easy to answer.
Thank you for your help!
phpheini
Generate the WHERE clause prior to running the SQL.
A short example:
$whereClause = "";
if ($_POST['opt1']) {
$opt1 = mysql_real_escape_string($_POST['opt1']);
$whereClause .= "AND opt1='$opt1'";
}
if ($_POST['opt2']) {
$opt2 = mysql_real_escape_string($_POST['opt2']);
$whereClause .= "AND opt2='$opt2'";
}
mysql_query("SELECT * FROM table WHERE 1 ".$whereClause);
To point you a little bit into the right direction, try something like this:
if(isset($_POST["something"]))
{
$where = " AND whatever = '".$whatever2."'";
}
else $where = '';
mysql_query("SELECT * FROM whatever WHERE house_data = '".$whatever."'".$where);
$where = array();
if($_POST["something"]) {
$where[] = " something =".$_POST["something"];
}
if($_POST["something2"]) {
$where[] = " something2=".$_POST["something2"];
}
.
.
.
//build where string
$where_ = !(empty($where) ? " WHERE ".implode(" AND ",$where) : "";
//build sql
$sql = "SELECT * ... ".$where;
write some simple query builder
$where = array();
if($_POST["something"]) {
$where[] = sprintf(" something='%s'",$_POST["something"]);
//sprintf - prevent SQL injection
}
if($_POST["something2"]) {
$where[] = sprintf(" something2='%s'",$_POST["something2"]);
}
//build where string
$where_str = " WHERE ".implode(" AND ",$where);
//build sql
$sql = "SELECT * ... $where_str";
You need to build your search string separately but the format is simply
SELECT * FROM your_table WHERE number = {$number} AND sentence = '{$sentence}';
Since you are creating the search term based on PHP logic do this:
$search = "SELECT * FROM your_table WHERE ";
if(isset($whatever)) $search .= "something = '{$whatever}'";
if(isset($whateverelse)) $search .= " AND somethingelse = '{$whateverelse}'";
$search_select = mysql_query($search);