I'm trying to count the number of rows in several tables and echo the results individually. I've tried using the below script and it returns the original value of $table1count, t1c. It never returns the actual count value. I think the syntax is wrong but all of the info I've found online is 8-10 years old. Could anyone help?
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbName = "database";
$table1count = 't1c';
$table2count = 't2c';
$conn = new mysqli ($servername, $username, $password, $dbName);
if(!$conn){
die("Connection failed. ". mysqli_connect_error());
}
$sql = "SELECT ";
$sql .= "(SELECT COUNT(*) FROM table1) AS $table1count, ";
$sql .= "(SELECT COUNT(*) FROM table2) AS $table2count; ";
$result = mysqli_query($conn ,$sql);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)){
echo "table1count:" . $table1count . "|table2count:". $table2count . ";";
}
}
?>
$table1count;
and $table2count;
need to have values before they can be used in the $sql
string. It doesn't really matter what the values are, as long as they are valid MySQL identifiers.
$table1count = 't1c';
$table2count = 't2c';
I just used assigned a string similar to the variable name because I'm not creative.
Those strings will be passed to MySQL with the query where they're used as aliases for the results of the count queries. The aliases will be returned with the query results, so they will be keys in the $row
array returned by $row = mysqli_fetch_assoc($result)
.
You can access the count values in $row
using those array keys in your echo
statement.
echo "table1count:" . $row[$table1count] . "|table2count:". $row[$table2count] . ";";
Also, be sure to remove that trailing comma from the SQL string, it will cause an SQL syntax error.