Zend - The PHP Company




Databases

Add Code


Connect to mutiple fields/tables function  

Type: application
Added by: mbills2
Entered: 28/07/2006
Last modified: 08/12/2008
Rating: ** (4 votes)
Views: 4582
Function for connecting to databases by creating arrays and calling the function.


<?php
require 'include.php';

function 
ConnectToTable$field$tableName$data$data2 )
{
    require 
'include.php';

    
$fieldCount count($field);
                
    for (
$i=0$i<$fieldCount;$i++)
    {
        
$connection mysql_connect($DBhost$DBuser$DBpass) or die ("Unable to connect to MySQL server."); 
        
$db mysql_select_db($DBname$connection) or die ("Unable to select database."); 
        
        
$sql "SELECT $field[$i] FROM $tableName WHERE $data = $data2";    
        
        
// testing sql statement
         
echo ("sql: $sql  <br>");    
        
        
$sql_result mysql_query($sql,$connection) or die ("Couldn't execute SQL query");
    
        while (
$row mysql_fetch_array($sql_result)) 
        {    
            
$data3[$i] = ( $row["$field[$i]"] );
        }                
    }    
    
    return 
$data3;    
}

//---------------------------------------------------------------------------------------------------------------
//
//      Put the fields you want to query from the database into an array 
//    Then make another array to hold the data.
//    ConnectToTable( A, B, C, D )
//
//    The query will look like:  SELECT A FROM B WHERE C = D 
//
//    $fieldCount just counts how many fields you use, in this case I used a 'for loop' to output the data.
//    $field is the array of fields to select.
//    $photos was defined in the include.php - its the table in the database - this can also be an array of tables
//    photoid is 'C' above (the WHERE statement): WHERE photoid = 113 (in this example) 
//
//--------------------------------------------------------------------------------------------------------------- 

$field = array('manufacturer''seller''url''url2''url3''url4','url5');
$test ConnectToTable$field$photosphotoid113 );
$fieldCount count($field);

for (
$i=0$i<$fieldCount ;$i++)
{
    echo 
"data $i$test[$i] <br>";    
}
?>


Usage Example


$field = array('manufacturer', 'seller', 'url', 'url2', 'url3', 'url4','url5');
$test = ConnectToTable( $field, $photos, photoid, 113 );
$fieldCount = count($field);

for ($i=0; $i<$fieldCount ;$i++)
{
    echo "data $i: $test[$i] <br>";    
}


Rate This Script





Search



This Category All Categories