Get the individual answer from a sql count() into php - 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'];
}
}

Related

I need to fetch the data from mysql database using the employee id from the table

I need to fetch the data from the table using the employee id,
there are two tables
1."user_info" which contains id, name,password,email,ScheduleDate,etc!
2."fetch" which contains id,ScheduleDate,starttime,endtime,hours,employeeid.
if i give the name and the password it takes the id of the particular user from "user_info" and it should send the id as the employee id to the table "fetch" and it should fetch the data from that employee id.
User_info database
fetch database
for example if i give the input as name :rajesh password:1995 in user_info,it should take the id of this user and it should send the id as employee id as 15 to the "fetch" table.
when i tried to send the id as employee id it doesn't print anything,and didn't show any error.
<?php
require "init.php";
$name = "surya";
$password = "1995";
$Sql = "SELECT * FROM `user_info`
WHERE `name`='".$name."' AND
`password`='".$password."';";
$result = mysqli_query($con, $Sql);
$retrive = array();
while($row = mysqli_fetch_array($result))
{
$user_id = $row['id'];
$sql = "SELECT id, ScheduleDate, StartTime,Endtime, Hours,Employeeid
FROM empdet WHERE Employeeid ='".$user_id."' ";
$result = $con->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$id=$row["id"].
$date=$row["ScheduleDate"];
$start=$row["StartTime"];
$end=$row["Endtime"];
$hour=$row["Hours"];
$Employeeid=$row["Employeeid"];
list($year,$month,$day) = split("-",$date);
$data[] = array("year"=>$year,
"month"=>$month,
"day"=>$day,
"StartTime"=>$start,
"Endtime"=>$end,
"Hours"=>$hour );
}
$response = $data;
} else
{
echo "0 results";
}
}
echo json_encode(array("user_data"=> $response));
?>
i need to fetch all the 3 data from the "fetch" table using the employee id 15.can anyone help to find it out this?
From my understanding your code is correct till second query. In that query execution, you will get multiple records. So you need to use loop for that.
See below example code:
while ($rows = $result->fetch_assoc()) {
$date=$rows["ScheduleDate"];
$start=$rows["StartTime"];
$end=$rows["Endtime"];
$hour=$rows["Hours"];
list($year,$month,$day) = split("-",$date);
$data[] = array("year"=>$year,
"month"=>$month,
"day"=>$day,
"StartTime"=>$start,
"Endtime"=>$end,
"Hours"=>$hour );
}
$response = $data;
Let me know if it helps.
I would use 'INNER JOIN' to achieve what you want:
$sql = "SELECT fetch.ScheduleDate, fetch.StartTime, fetch.Endtime, fetch.Hours"
." FROM fetch INNER JOIN user_info ON fetch.id = user_info.id"
." WHERE user_info.name = ? AND user_info.password = ? ";
//Prepare statement
$stmt = $mysqli_prepare($con, $sql);
//Bind parameter (id)
mysqli_stmt_bind_param($stmt, ss, $name, $password);
//Execute statement
mysqli_stmt_execute($stmt);
//Bind results
mysqli_stmt_bind_result($stmt, $date, $start, $end, $hour);
//Fetch values (puts the values into the variables)
mysqli_stmt_fetch($stmt);

How to get number of results from a mysqli query?

So I'm doing this query:
'SELECT * FROM Album WHERE id = ?;'
using a prepare sql statement, and I was wondering how to get the number of results this query returns? B/c since every album id is unique this query should only return 1 album and I want to make sure that its doing that.
Code
$stmt = $mysqli->prepare('SELECT * FROM Album WHERE id = ?;');
$id = 2;
$stmt->bind_param('i', $id);
$executed = $stmt->execute();
$result = $stmt->get_result();
if($row = $result->fetch_assoc()){
$info['id'] = $row['id'];
$info['title'] = $row['title'];
$info['date_created'] = $row['date_created'];
$info['creator'] = $row['creator'];
}
// Send back the array as json
echo json_encode($info);
You can get it using $result->num_rows:
if ($row = $result->fetch_assoc()) {
$info['id'] = $row['id'];
$info['title'] = $row['title'];
$info['date_created'] = $row['date_created'];
$info['creator'] = $row['creator'];
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
}
You can find more details on PHP Documentation.
I want to make sure that its doing that
In your code you are already doing that. The following condition
if($row = $result->fetch_assoc()){
does exactly what you want.
Just use COUNT(*)
SELECT COUNT(*) FROM Album WHERE id = ?;
Reference:
https://dev.mysql.com/doc/refman/5.7/en/counting-rows.html
Another way
$query = $dbh->prepare("SELECT * FROM Album WHERE id = ?");
$query->execute();
$count =$query->rowCount();
echo $count;

My SQL return always a 1

I have this query. However, it does not work properly. The echo returns always a 1, but there are 3 rows in the db
<?php
include "db_connect.inc.php";
$sql = "SELECT COUNT(id) FROM profiles";
$res = mysqli_query($con, $sql);
$num = mysqli_num_rows($res);
if ($num == 0)
echo "0";
echo $num;
mysqli_close($con);
?>
You're doing an aggregate query, which means you'll ALWAYS get one row of results - one row containing the count() value you requested. Even if that count() is 0, you'll STILL get one row of results.
If you want to check the value of the count, you have to fetch that row and check the field's value, e.g.
$sql = "SELECT COUNT(id) AS cnt FROM profiles";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
$row = mysqli_fetch_assoc($result);
if ($row['cnt'] == 0) { die("No profiles"); }
Your query returns 1 row with value 3
To see what you do expect you need something like:
<?php
include "db_connect.inc.php";
$sql = "SELECT COUNT(id) myCount FROM profiles";
$res = mysqli_query($con, $sql);
if ($row = mysqli_fetch_array($res, MYSQLI_ASSOC) ) {
echo $row['myCount'];
} else {
echo "0";
}
mysqli_close($con);
?>

Query inside while loop repeats results from 2 tables

I am not sure if the title expresses the problem accurately or not. Anyways, here is the explanation:
I have 2 tables, the first one holds users IDs, the other one holds their posts.
The fist query selects user IDs from the fist table, and it loop through the second table to find the users (IDs) posts.
The problem is that when the query finds eg. 5 results (user IDs 1, 6, 999.. etc) in the fist table, then it loops 5 times to search in the second table, it shows 5 results even if the real results is 2 post only created by user 1 and 6.
How can I avoid this repeatation?
Here is the code:
$stmt = $conn->prepare('select userid from table where para=?');
$stmt->bind_param('i', $para);
$stmt->execute();
$result = $stmt->get_result();
while( $row = $result->fetch_assoc()) {
$userid = $row["userid "];
$qname = "select postid,title from posts where uid='$userid'";
$result2 = $conn->query($qname);
$row2 = $result2->fetch_array(MYSQLI_ASSOC);
if ($row2 > 0) {
$postid= $row2['postid'];
$title= $row2['title'];
}
echo $postid." ".$title."<br>";
}
Try
$qname = "select postid,title from posts as P left join table as T on T.userid=P.uid where where para=?";
Or
You can store the results in a common array during the loop.
like
$tempResult = array();
while( $row = $result->fetch_assoc()) {
$userid = $row["userid "];
$qname = "select postid,title from posts where uid='$userid'";
$result2 = $conn->query($qname);
$row2 = $result2->fetch_array(MYSQLI_ASSOC);
if ($row2 > 0) {
$tempResult[$userid][] = $row2['postid'];
$tempResult[$userid][] = $row2['title'];
}
}
you can try this query using a JOIN MYSQL.
SELECT u.userid,p.postid,p.title FROM TABLE `user` u
JOIN posts p ON
p.uid = u.userid
WHERE para=?
You can avoid it by only running one query that joins the two tables together. Something like this:
<?php
$stmt = $conn->prepare('select posts.* from table t inner join posts p on t.userid = p.uid where t.para = ? order by uid');
$stmt->bind_param('i', $para);
$stmt->execute();
$result = $stmt->get_result();
while( $row = $result->fetch_assoc()) {
// $row now has userid, and all post details
}
?>

count rows and echo the result

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";

Categories