How to add values ​​from multiple MySQL databases

I am trying to add the number of items from multiple mysql databases (so far I have not gotten to the add part) in order to print the total number of entries on my home page.

I take away the basics of the "count" code from several sites that I googled, but something is wrong. If I run the query below on my own in phpMyAdmin, it works fine (I get 36 results from this 1 database), but when I run it on my php page using the code below, it returns only the number 1.

Any idea what I messed up? Thank you

$connection="localhost";
$username="myusername";
$password="mypassword";
$database1="mydb1";
$database2="mydb2";

$db1 = mysql_connect($connection,$username,$password) or die(mysql_error());
$sel1 = mysql_select_db($database1, $db1);
$query1 = "SELECT count(postID) FROM my_table";
$result1 = mysql_query($query1, $db1);

$db2 = mysql_connect($connection,$username,$password) or die(mysql_error());
$sel2 = mysql_select_db($database2, $db2);
$query2 = "SELECT count(postID) FROM my_table";
$result2 = mysql_query($query2, $db2) or die(mysql_error());

$total_rows = mysql_num_rows($result2);
print $total_rows; 
+3
source share
2 answers

(localhost), . , UNION , SUM(), .

SELECT SUM(postcounts) AS total
FROM (
  SELECT COUNT(postId) AS postcounts FROM mydb1.my_table
  UNION ALL 
  SELECT COUNT(postId) AS postcounts FROM mydb2.my_table
) allposts

, mysql_num_rows() 1, , - COUNT(postIdD). , .

, , , $result, total:

if ($result) {
  $row = mysql_fetch_assoc($result);
  echo $row['total'];
}

:

$db1 = mysql_connect($connection,$username,$password) or die(mysql_error());
mysql_select_db($database1, $db1);
$query = "    
    SELECT SUM(postcounts) AS total
    FROM (
      SELECT COUNT(postId) AS postcounts FROM mydb1.my_table
      UNION ALL 
      SELECT COUNT(postId) AS postcounts FROM mydb2.my_table
    ) allposts ";

$result = mysql_query($query, $db1);

// Fetch the resultant row
if ($result) {
  $row = mysql_fetch_assoc($result);
  echo $row['total'];
}
+3

2 , 2:

$total_rows = mysql_num_rows($result2);
print $total_rows; 

- :

$total_rows = mysql_num_rows($result2 + $result1);
print $total_rows; 
0

All Articles