Christopher Robbins
Christopher Robbins

Reputation: 37

How to use a script within another script connecting to MySql

I looked through the suggested other posts though I didn't see what I was looking for. This may seem basic to most of you here, so please forgive my simplicity, but I'm stuck. So below is what I have and it's working. (not everything is showing of the page). What I want to do is call the "payment_status" from a different database completely. What my question is, is how can I use this, and then have another script within this just to pull that column from a different database. I'm using PHP.

What I have

    <?php
    $servername = " ";
    $username = " ";
    $password = " ";
    $dbname = " ";
    
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
    }
    
    $sql = "SELECT id, name, email, payment_status, FROM paymenttable";
    $result = $conn->query($sql);
    
    echo "<div id='firstentry" . $row["id"]. "'><font color='yellow'>Name:</font> <span class='name'>" . $row["name"]. "</span> <br>";   // This uses the first database listed
    
    echo "<font color='yellow'>Payment Status:</font>  <span class='payment_status'>" . $row["payment_status"]. "</span>";  // This is what needs called from a different database than the rest of the page

    echo "<div id='next entry" . $row["id"]. "'><font color='yellow'>Email:</font> <span class='email'>" . $row["email"]. "</span> <br>";  // This uses the first database listed

Upvotes: 0

Views: 44

Answers (1)

griv
griv

Reputation: 2245

First, you can connect to two different databases on the same server by not specifying the database in the connection string:

$dbname1 = " ";
$dbname2 = " ";

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

Second, use mysqli_select_db to change your default database.

Select your first database, write your first query, then select your second database, and write your second query. You can write it in ether object oriented style, or procedural style:

Object oriented style:

$conn -> select_db($dbname1);
//write your first query again database 1 here

$conn -> select_db($dbname2);
//write your second query again database 2 here

Procedural style:

mysqli_select_db($conn, $dbname1);
//write your first query again database 1 here

mysqli_select_db($conn, $dbname2);
//write your second query again database 2 here

Next, output your results using echo here, be sure to differentiate your results between the two queries using $row1 and $row2 for example.

Finally, close your connection:

mysqli_close($conn);

Upvotes: 2

Related Questions