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

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

Related

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

PHP MySQL SELECT statement return null [duplicate]

This question already has answers here:
Understanding SUM(NULL) in MySQL
(2 answers)
Closed 4 years ago.
I want to select data from MySQL with a a where condition.
I'm sure the condition is false that's why it shouldn't return any data or any row but it returns null. I checked it with $stmt2->num_rows > 0 and this condition is true.
How can i prevent this from happening?
How my code suppose to work : this condition should be false for the first time and be true after I insert some data.
I think it's for SUM() that is used in select statement. How can I do that?
$q2="SELECT SUM(liked), SUM(disliked) FROM like_dislike WHERE post_id=?";
$stmt2 = $conn->prepare($q2);
$stmt2->bind_param('i', $post_id);
$stmt2->execute();
$stmt2->store_result();
$stmt2->bind_result($like_status, $dislike_status);
if ($stmt2->num_rows > 0 ) {
$stmt2->fetch();
}
else {
$like_status =0;
$dislike_status =0;
}
My select statement result in phpmyadmin:
According to the documentation :
SUM([DISTINCT] expr)
Returns the sum of expr. If the return set has no rows, SUM() returns NULL. The DISTINCT keyword can be used to sum only the distinct values of expr.
If there are no matching rows, SUM() returns NULL.
So you will always have NULL as result if you have no data.

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

Check if PDO prepare(), execute() returns at least one row

Before moving to PDO, I used
$result = mysqli_query ($conn, 'SELECT * FROM mytable WHERE id = 54');
if (mysqli_num_rows($result) >= 1) { ... }
to check if the query returns at least one result.
Now with PDO, I've seen in many SO questions (like get number of rows with pdo) that there is no direct function in PDO to check the number of rows of a query (there are warnings about the use of$result->rowCount();), but rather solutions like doing an extra query:
SELECT count(*) FROM mytable WHERE id = 54
But this is maybe too much for what I want : in fact, I don't need the exact number of rows, but just if there is at least one.
How to check if a prepared statement query returns at least one row ?
$stmt = $db->prepare('SELECT * FROM mytable WHERE id = 54');
$stmt.execute();
... // HOW TO CHECK HERE?
$stmt = $db->prepare('SELECT * FROM mytable WHERE id = 54');
$stmt.execute();
... // HOW TO CHECK HERE?
It's so simple, you're almost there already.
$stmt = $db->prepare('SELECT * FROM mytable WHERE id = 54');
$stmt.execute();
$result = $stmt->fetchAll(); // Even fetch() will do
if(count($result)>0)
{
// at least 1 row
}
And if you just want Yes/No answer then you should also add a LIMIT 1 to your query so mysql doesn't waste trying to look for more rows.

PHP mysqli query to check if a row exist [duplicate]

This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 8 years ago.
I have a mysql table, I want to check if a row exists where columnA=$a and $columnB=$b. I dont need to select anything from there. What should be efficient query for that? Currently Im doing like,
if ($stmt = mysqli->prepare("SELECT * FROM TABLE WHERE columnA=? && columnB= ? LIMIT 1")) {
$stmt->bind_param("ss", $a, $b);
$stmt->execute();
$stmt->store_result();
$count=$stmt->num_rows;
$stmt->close();
}
return ($count > 0 ? true : false);
Try with this:
if ($stmt = $mysqli->prepare("SELECT COUNT(*) FROM TABLE WHERE columnA=? && columnB=?")) {
$stmt->bind_param("ss", $a, $b);
$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch();
$stmt->close();
}
return ($count > 0 ? true : false);
Now you should be able to get it done
That is efficient query if you want to improve that query you should select one column only to speed up the query.
if ($stmt = mysqli->prepare("SELECT id FROM TABLE WHERE columnA=? && columnB= ? LIMIT 1")) {
Select just one field from the row instead of all of them (*). Even though you're not using them, mysql still has to fetch them from storage and get them ready for transmission.
SELECT columnA FROM table WHERE ...
Otherwise there's not much else you can do to improve things, other than putting indexes on columnA and columnB to make the searching go faster.

Categories