Saturday 23 December 2017

How to make multiple MySQL connections from PHP

itemprop="text">

The code below is working for one if
statement but not giving results for another else if and it is showing the 'flights'
table in first query but after another condition not display the other table named 'isb
to
muree'





$from
= isset($_POST['from'])?$_POST['from']:'';
$To =
isset($_POST['To'])?$_POST['To']:'';

if( $from
=='Islamabad'){
if($To == 'Lahore'){


$db_host
= 'localhost';
$db_user = 'root';


$database =
'homedb';
//$table = 'flights';

if
(!mysql_connect($db_host, $db_user))
die("Can't connect to
database");

if (!mysql_select_db($database))
die("Can't
select database");
$result = mysql_query("SELECT * FROM
flights");
if (!$result) {

die("Query to show fields
from table failed");
}



$fields_num
= mysql_num_fields($result);

echo "

Table:
'flights'

";
echo " border='1'>";



while($row =
mysql_fetch_row($result))
{
echo
"";

// $row is array... foreach( .. ) puts every
element
// of $row to $cell variable
foreach($row as
$cell)
echo "$cell";



echo "\n";
}
}

else if( $from
=='Islamabad'){
if($To == 'murree'){
if (!mysql_connect($db_host,
$db_user))
die("Can't connect to database");

if
(!mysql_select_db($database))

die("Can't select
database");

$result = mysql_query("SELECT * FROM 'isb to
murree'");
if (!$result) {
die("Query to show fields from table
failed");
}
$fields_num =
mysql_num_fields($result);

echo "

Table: 'isb to
murree'

";
echo " border='1'>";



while($row =
mysql_fetch_row($result))
{
echo
"";

// $row is array... foreach( .. ) puts every
element
// of $row to $cell variable
foreach($row as
$cell)
echo "$cell";



echo
"\n";

}
}
}
}


mysqli_close($con);

?>


Answer




You should move the database connection
variables to the top of your code (so they are outside of the if
statement)



$db_host =
'localhost';
$db_user = 'root';
$database =
'homedb';

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...