简体   繁体   中英

How to combine two MySQL connections into one MySQL connection?

I have two MySQL connections for the same database in the one .php file.

Second connection is base on the result of First one.

How can I combine two connection into one ? Please help & teach me how to modify it ?

First connection:

<?php
header('Content-Type: text/html; charset=utf-8');

$servername = "localhost";
$username = "abcabc";
$password = "12341234";
$dbname = "abc1234";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

// Logic data
$previous_page = ($_GET['crno'] - 1);
$next_page = ($_GET['crno'] + 1);


// select data

$sql    = 'SELECT * FROM ComData WHERE com_no = '. $_GET['crno'];
$result = $conn->query($sql);



if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $pageTitle = $row['com_eng_name'] . $row['com_chi_name'];

        $com_no = $row['com_no'];   
        $br_no = $row['br_no'];     
        $com_eng_name = $row['com_eng_name'];
        $com_chi_name = $row['com_chi_name'];       
        $com_type = $row['com_type'];   
        $date_of_incorp = $row['date_of_incorp'];   
        $active_status = $row['active_status']; 
        $date_commenced_dormancy = $row['date_commenced_dormancy']; 
        $remarks = $row['remarks'];
        $date_of_dissolution = $row['date_of_dissolution']; 
        $register_charges = $row['register_charges'];       
        $name_history = $row['name_history'];       
        $phone = $row['phone'];     
        $email = $row['email'];     
        $address = $row['address'];     
        $website = $row['website'];     
        $background = $row['background'];           
        $update_time = $row['update_time']; 




    }
} else {
    echo "No Results";
}

$conn->close();
?>

Second connection:

<?php
header('Content-Type: text/html; charset=utf-8');

$servername = "localhost";
$username = "abcabc";
$password = "12341234";
$dbname = "abc1234";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 



// select data for similar search

$string = "$com_eng_name";
$words = implode(' ', array_slice(explode(' ', $string ), 0, 2));


$sql = "SELECT * FROM ComData 
        WHERE com_eng_name REGEXP '$words'
        ORDER BY com_no 
        DESC 
        LIMIT 20";
$result = $conn->query($sql);


if ($result->num_rows > 0) {
    echo "<table><tr><th>CR No.</th><th>Company Name</th><th>Active Status</th></tr>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>".$row["com_no"]."</td><td><a href='search.php?crno=".$row["com_no"]."' >".$row["com_eng_name"]." ".$row["com_chi_name"]."</a></td><td>".$row["active_status"]."</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}
$conn->close();
?>

If those 2 pieces of code both exist in the same physical file then as the variable holding your connection in both cases is $conn you can just throw away the second attempt at making a connection to the database.

So just remove of comment out this code from the piece of code you called Second Connection ie this bit

$servername = "localhost";
$username = "abcabc";
$password = "12341234";
$dbname = "abc1234";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

Then remove this line

$conn->close();

from the piece of code you called First Connetion so you do not close the connection before the second piece of code runs.

However if in fact those 2 pieces of code are in seperate .php files. they have to stays the way they are.

It's not clear either if your two connection are in the same page or not, and if your two queries are execute sequentially or alternately.

Anyway, if the queries are on the same page or if you want put it in same page, sure you can use one only connection.

Start your script in this way:

header('Content-Type: text/html; charset=utf-8');

$servername = "localhost";
$username = "abcabc";
$password = "12341234";
$dbname = "abc1234";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

then, if you have to performs both queries, continue in this way:

// Logic data
$previous_page = ($_GET['crno'] - 1);
$next_page = ($_GET['crno'] + 1);

// select data
$sql    = 'SELECT * FROM ComData WHERE com_no = '. $_GET['crno'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {

    (...)

} else {
    echo "No Results";
}

// select data for similar search
$string = "$com_eng_name";
$words = implode(' ', array_slice(explode(' ', $string ), 0, 2));

(...)

$conn->close();

Otherwise, if the queries are executed only on condition, after connection check continue in this way:

if( /* Your Condition Here */ )
{
    // Logic data
    $previous_page = ($_GET['crno'] - 1);
    (...)
}
else
{
    // select data for similar search
    $string = "$com_eng_name";
    (...)
}

If you want use connection in any different file, you can create a file dbconnect.php with this content:

$servername = "localhost";
$username = "abcabc";
$password = "12341234";
$dbname = "abc1234";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

Then, in each file with db query, include it in this way:

header('Content-Type: text/html; charset=utf-8');
include( 'dbconnect.php' );
// Logic data
$previous_page = ($_GET['crno'] - 1);
(...)

header('Content-Type: text/html; charset=utf-8');
include( 'dbconnect.php' );
// select data for similar search
$string = "$com_eng_name";
(...)

etc...

Please note that, depending on 'dbconnect.php' file location, you can have to change include( 'dbconnect.php' ) with include( '/Full/Or/Relative/Path/dbconnect.php' ) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM