shorter way to get number of rows in a table - php

$sql = "select id from images";
$st = $db->prepare($sql);
$st->execute();
$total = $st->rowCount();
echo $total;
Do I really need all the above to get number of rows in a table? Is there a shorter way?

Use count to retrieve the number of rows in a table.
$st = $db->query('SELECT COUNT(*) FROM images');
$total = $st->fetchColumn();
echo $total;
(Thanks to Funk Forty Niner for the hint to remove the prepare/execute completely)

Related

How to sum of MySQL table column in php?

I want to get the sum total of the table columns in my database.
I've tried using the following code but have not been successful.
$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);
$result = mysqli_query($link,'SELECT SUM(value) AS value_sum FROM User_Table');
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
echo $sum;
Thank you very much!!
I hope you try to find total number of record of a table of User_Table
$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);
$result = mysqli_query($link,'SELECT SUM(your_column_name) AS value_sum FROM User_Table');
//or like the query for return last row that indicate total number of record
// id auto increment
$result = mysqli_query($link,'SELECT * FROM User_Table ORDER BY id DESC LIMIT 1;');
$row = mysqli_fetch_assoc($result);
$sum = $row['id'];
echo $sum;
// or using count
$result = mysqli_query($link,'SELECT COUNT(*) total_row FROM User_Table;');
$row = mysqli_fetch_assoc($result);
$sum = $row['total_row '];
echo $sum;
As of my understanding you need count the number of columns your database have. If I am not wrong, you may please use the query below
select * from information_schema.columns
where table_schema = '<YOUR DATABASE NAME>'
order by table_name,ordinal_position
Hope this helps. Thanks

Count total sum of rows in while loop

Okay so I have a query like this one
$get_downlines = "SELECT * FROM referrals WHERE ref_upline = :rupline";
$get_downlines = $pdo->prepare($get_downlines);
$get_downlines-> bindValue(':rupline', $sessionid);
$get_downlines-> execute();
while($fetch_downlines = $get_downlines->fetch()){
$rdownline = $fetch_downlines['ref_downline'];
$dr = "SELECT * FROM `ads_viewed` WHERE av_user = :user";
$dr = $pdo->prepare($dr);
$dr-> bindValue(':user', $rdownline);
$dr-> execute();
echo $dr_count = $dr->rowCount();
}
The code above gives me the row counts as say 3456 (all are separate counts like 3,4,5,6). Now I want to sum up all these rows here and get the result as 3+4+5+6 = 18. And assign it to a global variable which can be used anywhere outside while loop (if possible). How can this be done?
You could do the following:
$get_downlines = "SELECT * FROM referrals WHERE ref_upline = :rupline";
$get_downlines = $pdo->prepare($get_downlines);
$get_downlines-> bindValue(':rupline', $sessionid);
$get_downlines-> bindValue(':direct', "direct");
$get_downlines-> execute();
$totalrows;
while($fetch_downlines = $get_downlines->fetch()){
$rdownline = $fetch_downlines['ref_downline'];
$dr = "SELECT * FROM `ads_viewed` WHERE av_user = :user";
$dr = $pdo->prepare($dr);
$dr-> bindValue(':user', $rdownline);
$dr-> execute();
echo $dr_count = $dr->rowCount();
$totalrows+= $dr->rowCount();
}
echo $totalrows;
First you create the $totalrows; variable outside of the loop. You can increment this variable with the amount of rows in your query using $totalrows += $dr->rowCount(); inside of the while loop
This can be done with a single query:
$stmt = $pdo->prepare("
SELECT COUNT(*) AS cnt
FROM referrals
JOIN ads_viewed ON ads_viewed.av_user = referrals.ref_downline
WHERE ref_upline = :rupline
");
$stmt->execute(['rupline' => $sessionid]);
$dr_count = $stmt->fetchColumn();
Note: Everytime you execute an SQL query in a while-fetch-loop you probably better use a JOIN. And everytime you use SELECT * just to get the number of rows, you are wasting resources and should use COUNT(*) instead.

How can I add other data after the resulting query

I have this query.
$stmt = $this->getconnection()->prepare("SELECT * FROM detailuser where id = ?");
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
and I want to add amount in the result after the dateadded, but I am confuse how to add the amount. the amount is in another table and I have no reference on the first table (detailuser)
$amount = 100;
$rec = array(
'data'=>$result,
);
echo json_encode($rec);
{"data":[{"firstname":"Alex","friendname":"Alice","amount_due":"600.00","dateadded"
:"2015-09-14 13:30"},{"firstname":"Annie","friendname":"Karren","amount_due":"600
.00","dateadded":"2015-09-14 13:30"},{"firstname":"Helen","friendname":"Alice","amount_due":"600.00","dateadded":"2015-09-14 13:30"}]}
Thank you in advance
You can prepare a SELECT statement to fetch all rows and in that statement, you can add your dummy column.
SELECT *, 100 AS 'amount' FROM table_name
Instead of abusing your SELECT statement you can also loop over your result set.
foreach ( $result as $row ){
$row['amount'] = 100;
}
//encode and output
Use PDO prepare and then fetchAll() results!
$stmt= $dbh->prepare("SELECT firstname, friendname, amount_due, dateadded, "100" AS amount FROM yourTable");
$stmt->execute();
$result = $stmt->fetchAll();

count the number of rows in a query

i have this function separated in my working page.
public function countRow(){
$id = $_SESSION['id'];
$num = 1;
$query = "SELECT count(*) from `auditsummary` where bizID=? AND statusID=?";
$sql = $this->db->prepare($query);
$sql->bindParam(1,$id);
$sql->bindParam(2,$num);
$sql->execute();
}
what i'm really trying to do in this function is to count the number of rows that are results of the query but i don't know how to do it and also how to return the value.
As you use a PDOStatement for your query, after the execute, you can use
$count = $sql->rowCount();
More information:
http://php.net/manual/en/pdostatement.rowcount.php
And to return the result, you can just do:
return $count;
Information for this:
http://php.net/manual/en/function.return.php
Use
$query = "SELECT count(*) AS getCount from `auditsummary` where bizID=? AND statusID=?";
And get the values as you normally does
$count = $row["getCount"];
Here's how I do it:
$count = "SELECT * FROM yourtable WHERE x='x' and y='y'";
$result = $dbconn->prepare($count);
$result->execute();
$t_count = $result->rowCount();
echo $t_count;

can i merge those 2 queries in one query

hello can i merge those 2 queries in one query my first query get the number of articles in database and second query get the sum of all visits of all article whats the best method to make it one query
$stmt = $db->query('SELECT * FROM stories');
$story_count = $stmt->rowCount();
$stmt = $db->query("SELECT sum(visits) FROM stories");
$total_visits = $stmt->fetchColumn();
Try like
$stmt = $db->query('SELECT COUNT(*) as total_cnt,
SUM(visits) as total_visits FROM stories');
then excute your query,you will get result from "total_cnt" and "total_visits"
SELECT COUNT(*) as total, SUM(visits) as total_visits FROM stories;
SELECT Story.*, COUNT(*) as total, SUM(Story.visits) as total_visits FROM stories AS Story;
If you want to get other fields along with SUM and COUNT use .*.
Yes try this:
$stmt = $db->query('SELECT count(*),sum(visits) FROM stories');
$result = $stmt->fetch_array(MYSQLI_NUM);
$story_count = $result[0];
$total_visits = $result[1];

Categories