Sphiinx Sphiinx - 2 years ago 100
SQL Question

Get the number of columns in a table

I'm trying to get the number of columns in a table if that makes sense. For example, I have 5 tables with a column in each. Instead of getting the sum of all data in those columns, I would like to get the sum of how many there are. If that makes sense?

Here is a diagram of what I mean: http://i.imgur.com/NiYNn2H.png

Here is my code:

public function getNumber() {
$query = "SELECT
(SELECT username FROM table1)
+ (SELECT username FROM table2)
+ (SELECT username FROM table3)
+ (SELECT username FROM table4)
+ (SELECT username FROM table5)";
$result = mysqli_query($scriptdatasqlcon, $query);

if (mysqli_num_rows($result) > 0) {
echo mysqli_num_rows($result);
} else {
echo "UH OH";

Answer Source

Maybe you should use COUNT(*) - e.g.

$query = "SELECT 
        (SELECT COUNT(*) FROM table1)
        + (SELECT COUNT(*) FROM table2)
        + (SELECT COUNT(*) FROM table3)
        + (SELECT COUNT(*) FROM table4)
        + (SELECT COUNT(*) FROM table5)";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download