Searching several databases in php

Discussion in 'PHP' started by Joobz, Sep 19, 2007.

  1. #1
    Using php, how is it possible for me to have a search page that searches multiple databases and displays all of the search results with links to each record detail?
     
    Joobz, Sep 19, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    Yes:

    
    <?php
    
    error_reporting(E_ALL);
    
    // Search query
    $q = 'Find me';
    
    $databases = array(
    	array(
    		'database' => 'forums',
    		'table'    => 'vb_post',
    		'fields'   => array('postid', 'pagetext', 'title')
    	),
    	array(
    		'database' => 'nicoswd',
    		'table'    => 'scripts',
    		'fields'   => array('scriptid', 'code')
    	),	
    );
    
    $mysql_hostname = 'localhost';
    $mysql_username = 'root';
    $mysql_password = '';
    
    if (!empty($q))
    {
    	$con = mysql_connect($mysql_hostname, $mysql_username, $mysql_password) OR die(mysql_error());
    	$q = mysql_real_escape_string($q);
    	$results = array();	
    
    	foreach ($databases AS $dbinfo)
    	{
    		mysql_select_db($dbinfo['database'], $con) OR die(mysql_error());
    		
    		$query = mysql_query("
    			SELECT " . implode(', ', $dbinfo['fields']) . "
    			FROM " . $dbinfo['table'] . "
    			WHERE CONCAT(" . implode(', ', $dbinfo['fields']) . ")
    			LIKE '%" . $q . "%'
    		") OR die(mysql_error());
    
    		while ($result = mysql_fetch_assoc($query))
    		{
    			$results[] = array(
    				array($dbinfo['database'], $dbinfo['table'], $dbinfo['fields']),
    				$result
    			);
    		}
    		
    		mysql_free_result($query);
    	}
    	
    	mysql_close($con);
    }
    
    echo '<pre>' . print_r($results, true) . '</pre>';
    
    ?>
    
    PHP:
    This will give you an array with following content for each item.

    • Database name
    • Table name
    • Field names
    • Field contents


    So you would have to make a separate page and pass these values via GET to it, and connect to the right database. In the "fields" array, make sure to include the row ID field, so you can create a link to the unique row for more details.
     
    nico_swd, Sep 19, 2007 IP
    Joobz likes this.
  3. Joobz

    Joobz Peon

    Messages:
    598
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I'll play with this one a bit. Thank you for taking the time to post this. Much appreciated!
     
    Joobz, Sep 19, 2007 IP