Monday, 19 February 2018

How to make multiple MySQL connections from PHP



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 "";


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

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

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 "
$cell
";


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

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

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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...

$cell

Blog Archive