I have the weirdest issue going on. COUNT() is not working from inside my PHP code, but it is working in the SQL input space in the PHPMyAdmin database. For example if I use the following query:
SELECT COUNT(*) FROM posts WHERE category = "coding"
It will return the correct results from the SQL input in the PHPmyadmin part, but from the PHP code it will always return 1. Here is the code I am using for the PHP:
function numberofposts($category, $connection) {
$query = "SELECT COUNT(*) FROM posts WHERE category = :category";
$params = array(':category' => $category);
try{
$stmt = $connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
return $result;
}
echo "Number of Posts: " . numberofposts("art", $connection);
What it is doing is in the first code at the top it will return the correct results, but in the PHP code it is always returning 1. Is there a problem with me PHP? Please just post if you do not understand what I am asking, or if you would like more information.
You are doing a select and you execute the statement, but you are not fetching the row with the results.
You probably want something like:
function numberofposts($category, $connection) {
$query = "SELECT COUNT(*) as cnt FROM posts WHERE category = :category";
^^^ for easy access
$params = array(':category' => $category);
try{
$stmt = $connection->prepare($query);
$stmt->execute($params);
$row = $stmt->fetch();
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
return $row['cnt'];
// if you don't alias the column you can do:
// return $row[0];
}
Related
Order By After Where is not returning results below is the code and screenshot of not running code.
SELECT * from `SalesMessages` where `ThreadId`= ? ORDER BY `id` desc Limit 25;
However if I remove bind params it works fine.
SELECT * from `SalesMessages` where `ThreadId`=63 ORDER BY `id` desc Limit 25;
Below is screen shot from mySql
mysql query and results
HERE IS HOW I WROTE MYSQLI Code
global $conn;
$arr = array();
mysqli_set_charset( $conn, 'utf8'); // ALREADY TRIED COMMENTING THIS LINE
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $ThreadId);
try {
if ($stmt->execute()) {
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
..SOME CODE..
}
if (count($arr) > 0)
return $arr;
} else {
throw "QueryError";
}
} catch (Throwable $e) {
print_r($e);
}
}
Here is the structure of Table
DATA BASE STRUCTURE
I am expecting results from mysql in PHP code as array.
It was connection Error guys Which was using another database which does not had records. Everything else is working fine now. Actually the table in connected database had no record in required table.
I don't know why my code doesn't return true, the while loop works fine, but there's a problem.
$PDO_result = $db_PDO->prepare("SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE '?%' ");
$PDO_result->bindParam(1, $pismenka[$i]);
$PDO_result->execute();
Here when I var_dump() $PDO_result I get one item in array so the following while loop should work:
while($row = $PDO_result->fetch(PDO::FETCH_ASSOC))
but it doesn't.
Working MySQLi:
$result = mysqli_query($connect_to_db, "SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE '$pismenka[$i]%' ");
while($row = mysqli_fetch_array($result))
The most simple solution would be to change $pdo->fetch(PDO::FETCH_ASSOC) to $pdo->fetchAll(PDO::FETCH_ASSOC)
fetchAll returns ALL rows in the requested query, while fetch only gets 1 row (the first)
Example:
<?php
try {
$PDO_result = $db_PDO->prepare("SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE ?");
//Execute by inserting an array:
if (!$PDO_result->execute([$pismenka[$i] . "%" ])) { //Added ."%"
die('Error!');
}
//Fetch rows:
$rows = $PDO_result->fetchAll(PDO::FETCH_ASSOC);
//Go trough each row:
foreach ($rows as $row) {
//Do something
}
//Catch exceptions thrown by PDO
} catch (PDOException $ex) {
print_r($ex);
}
Please could you inform me if this is the correct way to execute the SQL count query to return an integer value using PHP.
I have only been learning PHP for 2 weeks so apologies if this is a noob question.
CODE:
include 'connection.php';
try {
$results = $conn->query("SELECT COUNT(*) FROM users");
}
catch (Exception $e) {
echo "unable to perform SQL Request";
exit;
}
$result = $results->fetchAll(PDO::FETCH_NUM);
echo $result[0][0];
it should be
include 'connection.php';
$result = $conn->query("SELECT COUNT(*) FROM users")->fetchColumn();
echo $result;
I want to put the value of count into a variable and display it on the page.
here's my code:
<?php
try {
$pdo = new PDO('Database info');
} catch (PDOException $e) {
exit('Database error.');
}
$query = $pdo->prepare("select count from counter where count_id=1");
$query->execute();
return $query;
echo $query;
?>
This isn't working... any suggestions on how i should change this to get the count to display in a variable?
Thanks.
Change to:
$query = $pdo->prepare("select count(*) from counter where count_id=1");
$query->execute();
$count = $query->fetchColumn();
echo $count;
Modify the query as follows
$count = $con->query("SELECT COUNT(*) as num from counter where count_id=1")
->fetch(PDO::FETCH_ASSOC);
echo $count['num'];
I just started playing around with PDO and I am trying to create a function that will display all the data for a given table name. After reading a few posts here I found a solution that I can get working (shown below with a hard-coded select statement). However, I can't get my execute statements to work when I bind my field names (I get an exception similar to: Undefined index: person_id). I should mention my class extends PDO:
/*********************************************************************
*Function showTable
*Purpose Display all information for a given table.
*Params $sTable -> Table name
********************************************************************/
public function showTable($sTable)
{
$result;
try
{
if(isset($sTable))
{
//create a result in a table format
$result = "<table>";
//$stmt = $this->prepare('DESCRIBE :sTable');
$stmt = $this->prepare('DESCRIBE ' . $sTable);
//$stmt->bindParam(':sTable', $sTable);
$stmt->execute();
//array version of the column names
$aCols = $stmt->fetchAll(PDO::FETCH_COLUMN);
//string version of the column names
$sCols = implode (", ", $aCols);
//$stmt = $this->prepare('SELECT :fields FROM :sTable');
//$stmt = $this->prepare('SELECT :fields FROM person');
$stmt = $this->prepare('SELECT person_id, first_name, last_name FROM person');
//$stmt->execute(array(':fields'=>$sCols, 'stable'=>$sTable));
//$stmt->execute(array(':fields'=>$sCols));
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
var_dump($row);
$result = $result . "<tr>";
foreach($aCols as $col)
{
//var_dump($row);
$result = $result . " <td>" . $row[$col]. "</td>";
}
$result = $result . "</tr>";
}
$result = $result . "</table>";
}
return $result;
}
catch(PDOException $e)
{
if($this->bDebug)
{
echo $e->getMessage();
}
}
}
Like I said the hard coded select string works but when i comment out the hard coded and uncomment the execute with a bind it throws exceptions.
You cannot insert identifiers or keywords this way.
PDOStatement::execute() will put the value in escaped form inside single quotes. Your query would look like:
SELECT 'col1, col2' FROM person
What is invalid MySQL syntax.
A valid example:
$stmt = $this->prepare('SELECT col FROM person WHERE name = :name');
$stmt->execute(array(':name' => $name));
It works, because it's a value you insert here; and not an keyword or identifier.