count rows and echo the result - php

I am trying to do a row count, I want to count a row (nummer) and if there is more then 1 row with the same number then echo. but no matter how many rows I have in my tabel, it only returs 0
$nummer = $_GET['nummer'];
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $pdo->prepare("select count(*) from rum where nummer=:n");
$result->bindParam(':n', $nummer, PDO::PARAM_INT);
$result->execute();
$rows = $result->fetchAll;
if(count($rows) >1) {
echo "1";}
else {
echo "0";
}

The following statement
$result = $pdo->prepare("select count(*) from rum where nummer=:n");
will always return one row with the count number, so doing
$rows = $result->fetchAll;
will always return one.
You may do as
$result = $pdo->prepare("select count(*) as tot from rum where nummer=:n");
....
....
$rows = $result->fetchAll();
if($rows["tot"] > 0 ){
echo 'something'
}else{
echo 'something else'
}

just use fetch() instead of fetchAll()
$rows = $result->fetch();
if($rows[0]) >1) {
echo "1";
} else {
echo "0";
}

It looks like you're having two mistakes.
First one: If you're querying for COUNT(*) - you are getting a number of rows. For example: You're return will be a field named COUNT(*) with one row containing the number of rows found.
If you replace
$result = $pdo->prepare("select count(*) from rum where nummer=:n");
with
$result = $pdo->prepare("select * from rum where nummer=:n");
Second one:
Replace
$rows = $result->fetchAll;
With
$rows = $result->fetchAll();
fetchAll() is no property but a method.
The other way would be your query but naming the field (MySQL AS keyword) and calling $rows = $result->fetch(); afterwards and checking $rows->fieldName for the number of found rows.

Use PDOStatement::fetchColumn(). It is useful for "one-column" resultsets (which relatively often produced by queries like SELECT COUNT(...) FROM ...). Example:
$nummer = isset($_GET['nummer']) ? $_GET['nummer'] : null;
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT COUNT(*) FROM rum WHERE (nummer = :n)');
$stmt->bindParam(':n', $nummer, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchColumn();
echo $rows > 1 ? "1" : "0";

Related

Replace value in array with result of mysqli_query

I'm having some trouble with php coding. What I want to do is following:
Create an array ($rows) and fil it with the results of a mysqli_query ($query1) --> OK
for each element in that array, replace the value of a certain key (pilot_rule_id) with the result of another mysqli_query ($query2). (the second query will return one row, since the id of the pilot table is the primary key).
So far I have
$id = "96707ac6-ecae-11ea-878d-005056bbb446";
$rows = array();
$query1 = mysqli_query($con, "SELECT * FROM pilot_time_schedule WHERE pilot_id='$id'");
while($r = mysqli_fetch_assoc($query1)) {
$rows[] = $r;
}
foreach($rows as $pilotRuleId) {
$pilotRuleId->$pilot_rule_id;
$query2 = mysqli_query($con, "SELECT name FROM pilot_rule WHERE id='$piloteRuleId'");
while($r = mysqli_fetch_assoc($query2)) {
$result[] = $r;
}
// Don't know how to continue from here
You can something like this:
$id = "96707ac6-ecae-11ea-878d-005056bbb446";
$stmt = $con->prepare('SELECT * FROM pilot_time_schedule WHERE pilot_id=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
foreach ($rows as $row) {
$stmt = $con->prepare('SELECT name FROM pilot_rule WHERE id=?');
$stmt->bind_param('s', $row['pilot_rule_id']);
$stmt->execute();
// replace with the `name` returned from the above statement.
$row['pilot_rule_id'] = $stmt->get_result()->fetch_row()[0] ?? null;
}
However, you really should learn about SQL joins instead. Using SQL joins you can avoid N+1 queries to the database.
$id = "96707ac6-ecae-11ea-878d-005056bbb446";
$stmt = $con->prepare('SELECT pilot_time_schedule.*, pilot_rule.name
FROM pilot_time_schedule
JOIN pilot_rule ON pilot_rule.id=pilot_time_schedule.pilot_rule_id
WHERE pilot_id=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
foreach ($rows as $row) {
echo $row['name']; // contains the name from pilot_rule
}

Get the individual answer from a sql count() into php

I have a sql database where I request the following bit of code;
SELECT albumtype, COUNT(*) FROM albumdata GROUP BY albumtype
The response in phpMyAdmin is the following table
albumtype | COUNT(*)
Album | 4
EP | 1
Single | 1
Then I have in my php file the following code that will return the complete count (6).
$stmt = $con->prepare('SELECT albumtype, COUNT(*) FROM albumdata GROUP BY albumtype');
$stmt->execute() or die("Invalid query");
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$row_cnt = mysqli_num_rows($result);
I used this code on another page, but now I want to select a specific part of the "count()" table.
I tried to display a single result with $row_cnt = $row['Album'];, but as it turns out, this returns "Array" for some reason. Here is my php call:
$stmt = $con->prepare('SELECT albumtype, COUNT(*) FROM albumdata GROUP BY albumtype');
$stmt->execute() or die("Invalid query");
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$row_cnt = $row['Album'];
How can I grab a single row, for example the number of how much the database could find Album (4 times) and put it in a php variable? I tried searching it on here, but didn't get any further.
1.If you want only specific albumType ten you can directly change your query like this:-
$stmt = $con->prepare("SELECT albumtype, COUNT(*) as counts FROM albumdata WHERE albumtype = 'Album'");
$stmt->execute() or die("Invalid query");
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$album_cnt = $row['counts'];
echo $album_cnt;
But if you want all then,you need to do it like below:-
$stmt = $con->prepare('SELECT albumtype, COUNT(*) as counts FROM albumdata GROUP BY albumtype');
$stmt->execute() or die("Invalid query");
$result = $stmt->get_result();
$row_cnt = array();
while($row = $result->fetch_assoc()){
$row_cnt[$row['albumtype']] = $row['counts'];
}
echo "<pre/>";print_r($row_cnt);
// you have all data in array so you can use it now like below
foreach($row_cnt as $key=>$value){
echo "Album type ".$key." has ".$value." counts"."<br/>";
}
//form this all data if you want to compare specific albumType then do like below:-
foreach ($row_cnt as $key=>$value) {
if($key == 'Album'){
echo $value;
}
}
Loop over the rows till you match the type you want to display:
foreach ($row as $srow) {
if($srow['albumtype'] == 'Album'){
print $srow['count'];
}
}

PDO get number of followers

Here is my code
$sql1 = "SELECT * FROM user_follow WHERE user = :user";
$stmt1 = $conexao_pdo->prepare($sql1);
//where clause
$stmt1->bindParam(':user', $username);
$stmt1->execute();
while ($row1 = $stmt1->fetch(PDO::FETCH_ASSOC))
{
echo '</br>Followers: </br>'.$row1['followers'].'</br>';
}
It show the name of the followers but I would like a implementation in PDO to also show the amount in numbers of the $row1['followers']
If you just need the count you can use rowCount() function:
$stmt1->execute();
$count = $stmt1->rowCount();
echo '</br>Followers: </br>'.$count.'</br>';
so it's just echo $count

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't return correct row count from database using php pdo

I am trying to return the row count from a table in my database but continue to get the wrong value. I need the row count to process subset values for pagination. There are 11 items in my table but I am only returning 1 and can't figure out why :(
My external connection file:
try {
$pdo = new PDO('mysql:host=localhost;dbname=name', 'admin', 'password');
} catch (PDOException $e) {
exit('Database error.');
}
My Article class:
class Article {
public function fetch_all_articles($start, $max) {
global $pdo;
$query = $pdo->prepare("SELECT * FROM articles ORDER BY article_timestamp DESC LIMIT $start, $max");
$query->execute();
$articles = $query->fetchAll();
$query->closeCursor();
return $articles;
}
public function fetch_num_rows() {
global $pdo;
$query = $pdo->prepare("SELECT COUNT(*) FROM articles");
$query->execute();
$rowCount = $query->rowCount();
$query->closeCursor();
return $rowCount;
}
}
And my index.php file:
$maxArticles = 4; //Show only 4 articles per page
$page = $_GET['page'] ? $_GET['page'] : 0; //Get current page number or assign $page = 0 if no page number exists
$startRow = $page * $maxArticles; //Get current article subset value
$article = new Article;
$articles = $article->fetch_all_articles($startRow, $maxArticles); //articles array
$numArticles = $article->fetch_num_rows(); //number of articles
$rowCount = $article->fetch_num_rows(); //number of articles
echo $rowCount;
echo $numArticles;
And yes I do need both $rowCount and $numArticles, they are being used for two different purposes.
Can anyone help me?
you should replace
$rowCount = $query->rowCount();
with
$rowCount = $query->fetchColumn();
also, take a look at FOUND_ROWS()
there is no sense in calling fetch_num_rows 2 times, it is enough to do:
$numArticles = $rowCount = $article->fetch_num_rows();
SELECT COUNT(*) FROM tableName just returns a single row. The data in that row is the number of rows in the table. So $query->rowCount() will always be 1. If you want the number of rows, you need to use:
$query = $pdo->prepare("SELECT COUNT(*) ct FROM articles");
$query->execute();
$rowCount = $query->fetch(PDO::FETCH_OBJ)->ct;

Categories