How to get number of results from a mysqli query? - php

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;

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

execute() gets no results

I have two queries here, $check_perms and $get_projects. The former seems to work, but not the latter. There's no error, just no results, yet I know there should be.
$sessionUser = $_SESSION['user_id'];
$check_perms = $db->prepare("SELECT * FROM tasks WHERE id = ?");
$check_perms->bind_param('i', $par);
if ($result = $check_perms->execute())
if ($row = mysqli_fetch_assoc($result))
if ($row['user'] != $sessionUser){
echo "<container>Error. This is not your task.</container>";
exit;
}
$get_projects = Database::connect()->prepare("SELECT * FROM tasks WHERE user = ? ORDER BY weight DESC");
$get_projects->bind_param('i', $sessionUser);
if ($result = $get_projects->execute())
while ($row = mysqli_fetch_assoc($result))
//stuff
Are you sure that tasks.user field is an integer? Try to change:
$check_perms->bind_param('i', $sessionUser);
to
$check_perms->bind_param('s', $sessionUser);

how do i implement update i pdo for the following mysql code?

here is my mysql code and equivalent pdo code i need to know what is wrong
$id = $_POST['id'];
$query1=mysql_query("SELECT Quantity,id FROM `yumyum`.`food` where `food`.`id` LIKE $id");
$r = array();
while($r = mysql_fetch_assoc($query1)) {
$output = $r['Quantity'];
echo $output;
$query2=mysql_query("UPDATE food SET Quantity = Quantity - 1 where `food`.`id` LIKE ".$r["id"]);
PDO code
$stmt = $db->prepare("SELECT * FROM yuymuym WHERE id=:id AND Quantity=:Quantity");
$stmt->execute(array($id, $Quantity));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC)
How about this. I don't know what $_POST['id'] is so you have to figure the rest youself. It updates every item with id in $ids array. So this updates items with id 1,2,3,4 and 5.
$db = new PDO('mysql:host=localhost;dbname=yumyum', 'username_here', 'password_here');
$ids = array(1,2,3,4,5);
foreach($ids as $id){
$stmt = $db->prepare("SELECT Quantity, id FROM `food` WHERE `food`.`id` = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$row = $stmt->fetch();
if($row){
//uncomment to see $row content
//var_dump($row);
$rowId = (int)$row['id'];
$rowQuantity = (int)$row['Quantity'];
echo $rowQuantity;
$ustmt = $db->prepare("UPDATE `food` SET `Quantity` = `Quantity` - 1 WHERE `food`.`id` = :id");
$ustmt->bindParam(':id',$rowId);
$ustmt->execute();
}else{
var_dump($stmt->errorInfo());
}
}
But PDO basics:
Query (Works with select, insert, update, everything else):
$id = (int)$_POST['id'];
$else = $_POST['string'];
// Connect to database
$db = new PDO('mysql:host=HOST_HERE;dbname=DATABASENAME_HERE', 'USERNAME_HERE', 'PASSWORD_HERE');
// First we prepare our query
$stmt = $db->prepare("... WHERE `id` = :id AND `something` = :else");
// We bind values to our prepared query
$stmt->bindParam(':id',$id);
$stmt->bindParam(':else',$else);
// We execute our query
$success = $stmt->execute();
// If we want to fetch only one row:
$row = $stmt->fetch();
echo $row['id'];
// If we want to fetch all rows:
$rows = $stmt->fetchAll();
foreach($rows as $row){
echo $row['id'];
}
These are very basics, if you don't understand what is really happening here, you should learn some more.

Categories