Fetching rows with a certain enum status [duplicate] - php

This question already has an answer here:
Trying to access array offset on value of type bool
(1 answer)
Closed 1 year ago.
I am trying to have a display (Completed Repairs = ?) on my admin dashboard that displays the number of laptop repairs completed based on the status column.
<?php
$pdo = new PDO(
'mysql:host=127.0.0.1;dbname=MYAPP',
'MYUSERNAME',
'MYPASSWORD'
);
//The COUNT SQL statement that we will use.
$sql = "SELECT COUNT(*) FROM repairs WHERE current_status > Repair Completed";
//Prepare the COUNT SQL statement.
$stmt = $pdo->prepare($sql);
//Execute the COUNT statement.
$stmt->execute();
//Fetch the row that MySQL returned.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//The $row array will contain "num". Print it out.
echo $row['num'];
?>
But i am getting this error: Notice: Trying to access array offset on value of type bool in PATH_TO_PHP_FILE.php on line 208
Line 208 is:
echo $row['num'];
I am a complete newby so i have no idea what to do here.
I am using "num" cause i want to get the number of rows that have a status of "Repair Completed".
I have looked around on stackoverflow but i am not really understanding any of it.
What am i missing from my code? Any help will be greatly appreciated.

Your sql request seems wrong so it returns false try
$sql = "SELECT COUNT(*) FROM repairs WHERE current_status = 'Repair Completed'"
And after that do a var_dump of $row

Related

Same query but different results in phpMyAdmin and PHP [duplicate]

This question already has an answer here:
PDO, MySQL SELECT statement returning boolean true?
(1 answer)
Closed 11 months ago.
I have seen similar posts to this one already existing but none of them have helped.
When I run this PHP code with $retrievestat = 1, I get a value of 1 return by the search query in php:
$retrievestat = $_POST["statIdentifier"];
echo $retrievestat;
// Retrieve The Player With The Most Rounds Won With Their Rounds
if ($retrievestat == 1)
{
$checkuniquequery = "SELECT COUNT(*) FROM playerstats WHERE roundswon = (SELECT MAX(roundswon) FROM playerstats);"; // Get number of rows that have a roundswon value equal to the max in the table
$stmt = $conn->prepare($checkuniquequery);
echo ($stmt->execute());
if ($stmt->execute() == 1) // If only one row has the max roundswon then get the username + roundswon
{
$mostroundswonquery = "SELECT username, MAX(roundswon) FROM players, playerstats WHERE players.id = playerstats.id";
$stmt = $conn->prepare($mostroundswonquery);
//echo ($stmt->execute());
}
However, when I run this query in phpMyAdmin:
"SELECT COUNT(*) FROM playerstats WHERE roundswon = (SELECT MAX(roundswon) FROM playerstats);"
I get 2 returned as the output.
Any ideas why this is happening and how to fix it?
The execute method on PDO statement ($stmt->execute()) does return either true (if execution was successful) or false if not. It does not return the return value of the SQL statement. On a side node: $stmt->execute() == 1 does behave the same as $stmt->execute() == true !
To get the actual return value you need to fetch the result after execution.
E.g. you can use $stmt->fetch() to get actual result.
Have a look at the documentation to learn more: https://www.php.net/manual/en/class.pdostatement.php

SELECT COUNT(*) returns an object instead of an integer [duplicate]

This question already has answers here:
Count rows from results of a "mysql_query"
(9 answers)
MySQL - count total number of rows in php
(11 answers)
count number of rows in table using php
(6 answers)
How can I count the numbers of rows that a MySQL query returned?
(12 answers)
PHP SQL get SELECT COUNT(user) to variable
(5 answers)
Closed 4 years ago.
I have a database table timestamps_sessions containing timestamps of when a user begins an exercise on my webpage, and which is only updated when the user actually finishes it. Therefore, every row always has a value in the started column, but not always in the finished column. The latter is NULL by default.
My SELECT COUNT() statement works perfectly when I query it in Sequel Pro, and returns the correct integer of 11. That is to say: there are indeed only eleven rows that have values in both started and finished.
Yet when I execute it in PHP, it returns an object containing
{
current_field: null,
field_count: null,
lengths: null,
num_rows: null,
type: null
}
The statement I successfully query in Sequel Pro is the following:
SELECT COUNT(finished) FROM timestamps_sessions
The statement I unsuccessfully use in PHP is the following:
$sql = "SELECT COUNT(finished) FROM timestamps_sessions";
$result = $conn->query($sql);
$exercise['clears'] = $result;
There are several other SELECT queries being performed to the same database and same table without issue. It's only the COUNT() statement that seems to be malfunctioning.
What am I doing wrongly, and how should I do it instead?
My goal is to count the number of rows with a non-empty finished column, without passing on the actual data in order to preserve bandwidth. All I need is the integer.
First of all, $result is an object as expected. It's the result returned by the mysqli::query() method. Before you can access the data from this query, you need to fetch it. It will be easier if you give an alias to the count, as it will become easier to access the count.
$sql = "SELECT COUNT(finished) as cnt FROM timestamps_sessions";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$exercise['clears'] = $row['cnt'];
mysqli::query() docs
mysqli::fetch_assoc() docs
you have missing code mysql_fetch_array in order to fetch first record
$sql = "SELECT COUNT(finished) totals FROM timestamps_sessions";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$total = $row['totals'];
The argument passed to the count function can be anything, since you just want the number of rows, not their data.
SELECT COUNT(1) FROM timestamps_sessions WHERE finished IS NOT NULL;
$sql = "SELECT COUNT(finished) AS count_finished FROM timestamps_sessions";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $exercise['clears'] = $row['count_finished'];
Give the count an alias like count_finished. Then from the result object you need to fetch the row. The row has your data in it.
Take a look at this https://www.w3schools.com/php/php_mysql_select.asp

Show last id of database in PDO [duplicate]

This question already has answers here:
PDO get the last ID inserted
(3 answers)
Closed 5 years ago.
I am trying to get the last id number of Database. But It's showing only 0.
I am learning PDO. Can anyone tell me how can I do it?
if($_SERVER['REQUEST_METHOD']=='POST'){
$sql = "SELECT * FROM tablename";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt ->fetch();
$showid = $pdo->lastInsertId();
echo $showid;
}
lastInsertId will return the ID of a row that was inserted by the same connection. You can't use it outside of that context.
The easiest way to fetch the last ID would be to run something like,
SELECT max(id) FROM tablename
If you're using this in order to work out which ID should be inserted next, consider using an auto-increment column for your ID instead.
lastInsertId() works only after a INSERT query - since you're only doing a select, it will always return string(1) = 0
So either you perform this code after an INSERT statement, or you can do the following:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
Refering here to: PDO get the last ID inserted
Visit this thread, you'll find my samplecode provided by Corbin and much more informations on this topic.

mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement in PHP [duplicate]

This question already has answers here:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 1 year ago.
I am trying to do a username search [which I seemingly finished and working as well] but when you've searched for the username, the information about the account will show up. For example, I've searched for virtualAnon, his name and information such as first_name will show up after his username.
I've tried to fix it by replacing $query = "SELECT username FROM users WHERE username like ? LIMIT 1"; to $query = "SELECT * FROM users WHERE username like ? LIMIT 1"; but after I've tried that, the error
mysqli_stmt::bind_result(): Number of bind variables doesn't match
number of fields in prepared statement in PHP
shows up.
This is the PHP file to fetch usernames and database:
<?php
if($_GET['keyword'] && !empty($_GET['keyword']))
{
$conn = mysqli_connect('localhost','root','','loginsecure'); //Connection to my database
$keyword = $_GET['keyword'];
$search = $_GET['keyword'];
$keyword="%$keyword%";
$query = "SELECT * FROM users WHERE username like ? LIMIT 1";
# When I tried to SELECT *, It gives me the error of: Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement in ...\fetch.php on line 22
$statement = $conn->prepare($query);
$statement->bind_param('s',$keyword);
$statement->execute();
$statement->store_result();
if($statement->num_rows() == 0) // so if we have 0 records acc. to keyword display no records found
{
echo '<div id="item">Sorry, but there is no user "'.$search.'" found in our database :(</div>';
$statement->close();
$conn->close();
}
else {
$statement->bind_result($name); # There is a error i'm encountering when I try to Select * from the line 8.
while ($statement->fetch()) //outputs the records
{
echo "<div id='item'>$name</div>";
# It supposed to show more information about the user, by using $name['first_name'] or $name['last_name']
};
$statement->close();
$conn->close();
};
};
?>
The problem that you're getting is that mysqli_stmt::bind_result will try to bind each column in the result set to a variable. Which means that you need the same amount of variables as you've got columns. If you've got two columns being returned, you need to bind them to two variables.
In $statement->bind_result($name);, you're saying "There's only going to be one column, so bind it to $name" whereas your query (SELECT * FROM users WHERE username like ? LIMIT 1) is fetching all the columns for that table.
So the solution is to only select the singular column you want in this instance. Replace
SELECT name
with
SELECT *

Variable not holding data from MYSQL query [duplicate]

This question already has an answer here:
PHP not displaying result from MYSQL query
(1 answer)
Closed 6 years ago.
I have the following code
# connect to sql server
$sql = new PDO('mysql:dbname=random;host=localhost', 'root', '');
# perform the query
$query = 'SET #uid := (SELECT Channel_Location FROM channels WHERE Used = 0 ORDER BY RAND() LIMIT 1);'.PHP_EOL
.'UPDATE channels SET Used = 1 WHERE Channel_Location = #uid;'.PHP_EOL
.'SELECT * FROM channels WHERE Channel_Location = #uid';
$result = $sql->query($query);
$row = $result->fetch();
$id = $row['Channel_Location'];
var_dump($row);
Now the query works its tested returns what i need it to but when i var_dump($row) i get Boolean false and when i var_dump($id) i get null as the errors, now the database has plenty of entries it can select from but nothing passes through to PHP yet if i run the query in my client i get a return value.
can anyone guide me to a possible solution?
You can't run multiple queries in one using PDO, try running one query at time and check to see what happens

Categories