简体   繁体   中英

Count all rows in database where column equals to `YES`

I have a database crm_data in which I have multiple tables. Now I want to calculate all rows in whole database where column_name value is equal to YES . To calculate all rows in database I am using this mysql query.

My SQL Query:

$sql = $db_con2->prepare("SELECT SUM(TABLE_ROWS) AS all_rows FROM 
       INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'crm_data'");
$sql->execute();
$all_rows = $sql->fetchAll();
if (count($all_rows) > 0) {
   foreach ($all_rows as $all_rows) {
      echo $all_rows['all_rows'];
   }
} else {
   $all_rows = '0';
}

Thanks

What I did I went back to basics and used SHOW TABLES then I use table query SELECT * FROM $company WHERE rental_status = 'YES' . and I got the results.

BTW thanks guys giving me your suggestion.

Try this, i hope it works for you

// connect to Database.
   $links = mysqli_connect($db_host, $db_username, $db_password, $db_name );

   if($links === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
      }

//get total
    $n = 'YES';



$result = mysqli_query($links,"SELECT   Count(*) As column_name FROM crm_data WHERE column_name='".$n."'");

                                                       $rows = mysqli_num_rows($result);



                                                if($rows){

                                                    $gt = mysqli_fetch_assoc($result);

                                                     $total = $gt["column_name"];

                                                    }
                                   echo $total;

Using PDO as requested.

 // using PDO
  $servername = "localhost";
$username = "user";
$password = "pass";

try {
    $conn = new PDO("mysql:host=$servername;dbname=dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //echo "Connected successfully"; 

// call for the row count here.

$w='YES';
$rs = $conn->prepare("SELECT   Count(*) As column_name FROM crm_data WHERE column_name='".$w."'");
$rs->execute();
$count = $rs->rowCount();
echo '<p>Total:'.$count.'</p>';
}
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }   

You're not querying the data in your database you're now querying the actual structure of the database, which is concerning.

Nevertheless...

 SELECT SUM(`COLUMN_NAME`) FROM `INFORMATION_SCHEMA`.`COLUMNS` where `COLUMN_NAME` = 'YES' AND `TABLE_SCHEMA` = 'crm_data';

Is the query you are looking for...

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