¿Obtener resultados de búsqueda de diferentes tablas de bases de datos y mostrarlos?

I'm trying to create a search function that will retrieve search results for different posters we're creating on our site. If a person is searching for lets say "dog" then it will show the posters which is related to dogs. The site is going to publish different events in the form of posters.

The code looks as following at the moment:

<?php

class Search
{
    public static $con;

    private $search = '';

    function __construct()
    { 
        self::$con = mysqli_connect('localhost', 'guest', 'guestpw', 'db_users');

        $this->search = mysqli_real_escape_string(self::$con, $_POST['search']);
    }

    if(isset($_POST['submit_search']))
    {

    $sql = mysqli_query($con, "SELECT * FROM Event WHERE eventNamn LIKE '%" . $search);

    $sql = mysqli_query($con, "SELECT * FROM Användare WHERE userName LIKE '%" . $search);

    $sql = mysqli_query($con, "SELECT * FROM Poster WHERE Kategori LIKE '%" . $search);

    $sql = mysqli_query($con, "SELECT * FROM EventTyp WHERE EventTyp LIKE '%" . $search);

    $result = mysqli_query($sql);

    }
}

What I want to happen now is to use the search word the user is searching for and then display the events that are associated with that word. All help is much appreciated! Thank you.

preguntado el 28 de mayo de 14 a las 13:05

you replace the variable $sql each time so only the last will be executed -

First of all you re-assign the $sql var over and over again. Then there's the wrong object scope on the search variable (you should use $this->search en lugar de). -

What @mplungjan says, each time you give a new meaning to $sql you overwrite it. So the previous one will be 'gone' so when you created your 4th $sql only that one 'exists'. -

You are missing the closing single quote from all variables in queries. -

Consider also using prepared statements -- directly building your query strings like that is unsafe. ca3.php.net/manual/en/mysqli.prepare.php -

3 Respuestas

Es posible que desee utilizar UNION or UNION ALL operator. The SQL UNION operator combines the result of two or more SELECT statements.

 SELECT col FROM Event WHERE ...
 UNION ALL
 SELECT col FROM User WHERE ...

El documento está aquí:
MYSQL UNION operator : http://dev.mysql.com/doc/refman/5.0/en/union.html


Tu código podría ser así:

$sql  = "SELECT [your column] AS event FROM Event WHERE eventNamn LIKE '%" . $search . "'".
    "UNION ALL ".
    "SELECT [your column] AS event FROM Användare WHERE userName LIKE '%" . $search . "'".
    "UNION ALL".
    "SELECT [your column] AS event FROM Poster WHERE Kategori LIKE '%" . $search . "'".
    "UNION ALL".
    "SELECT [your column] AS event FROM EventTyp WHERE EventTyp LIKE'%" . $search . "'";

$result = mysqli_query($con,$sql);

while($row = mysqli_fetch_array($result)) {
  echo $row['event '];
  echo "<br>";
}
mysqli_close($con);

Espero que esto ayude.

contestado el 28 de mayo de 14 a las 14:05

Thank you for your answer. How will I display the search results after using UNION or UNION ALL? And how can I fix the problem of having the $sql variable being replaced? Is this fixing that problem? - schivv

The code you're having now is not going to work. You're checking for a $_POST request inside a class? I made some adjustments

<?php

class Search
{
    public static $con;
    private $search = '';

    public function __construct($search)
    { 
        self::$con = mysqli_connect('localhost', 'guest', 'guestpw', 'db_users');

        $this->search = mysqli_real_escape_string(self::$con, $search);
    }

    //Do this for every search

    public function search() {
       $sql = mysqli_query(self::$con, "SELECT [column] FROM Event WHERE eventNamn LIKE '%" .       $search . "'".
"UNION ALL ".
"SELECT [column] FROM Användare WHERE userName LIKE '%" . $search . "'".
"UNION ALL".
"SELECT [column] FROM Poster WHERE Kategori LIKE '%" . $search . "'".
"UNION ALL".
"SELECT [column] FROM EventTyp WHERE EventTyp LIKE'%" . $search . "'");
       return mysqli_query($sql);
    } 
}

if(isset($_POST['search'])) {

  $searchClass = new Search($_POST['search']);
  $result = $searchClass->searchEvent();

}

contestado el 28 de mayo de 14 a las 14:05

Thank you for your answer. Did you mean for me to create a function for each query? Like public function searchName(), searchEvent(), etc? - schivv

Just 3 other function searchAnvändare(), searchPoster() and searchEventTyp(); - Daan

@Daan Super Globals are available in any scope, even a class. - r3wt

@r3wt Yes thats not what I meant with it. I meant it doesn't look clean. - Daan

@Daan oh, well i agree, but thats not the problem here. The OP doesn't understand PHP yet, but atleast he/she is trying. - r3wt

1.don't rely on mysqli escape string. use a prepared statement. its faster and foolproof.

2.You can select from multiple tables in one query pretty easily

public $mysqli; //make sure your connection is available

public $result = NULL;//setup your result variable
public $search = NULL;
public function getresults() //pass your connection to the object
{
    $search = $_POST["search"]; //post is a super global. no need to pass it by reference

    $result = array();//create an array to store the search results in

    $mysqli = $this->mysqli;//define mysqli so you can access the property of your class object. 

    //construct mysqli in your __construct call, and return it.

    $stmt = $mysqli->prepare("SELECT column1,column2,column3,column4 
                                FROM Event,Användare,Poster,Eventyp 
                                WHERE eventNamn LIKE '% ?';");//prepare our query

    $stmt->bind_param('s', $this->search); 

    //bind our search parameters to the question mark in the query. 
    //if you have multiple querystrings, they must be bound in order.
    if($stmt->execute())//execute prepared statment
    {
        $stmt->bind_result($col1,$col2,$col3,$col4);//bind the selected column results to variables. 
        //these also must be bound in order
        if($stmt->num_rows > 0)
        {
            $result[] = array('type'=> 'success','result' => $stmt->num_rows, 'search string' => $search); //success!
            while($row = $stmt->fetch()) //never use get_result to fetch your statement. always use fetch.
            {
                $result[] = array('type' => 'result', 
                                  'column1' => $col1 ,
                                  'column2' => $col2 ,
                                  'column3' => $col3 , 
                                  'column4' => $col4); //store each result row in an array.
            }
            $stmt->close();//close the connection
        }else{
            $result[] = array('type'=> 'emptyresult','result' => 'No Results Found', 'search string' => $search); //No Results!
        }
    }else{
        $result[] = array('type'=> 'error','result' => 'Error with query', 'search string' => $search); //No Results!
    }
    return $result;//finally return our result for further processing
}

contestado el 28 de mayo de 14 a las 13:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.