Return MySQL Count via PHP - php

I have a PHP function that looks like this:
function count_creatives() {
global $db;
$q = "SELECT COUNT(DISTINCT creative) FROM actions";
return $db->query($q);
}
The $db variable contains a PDO object and is set correctly (used successfully elsewhere).
When I try to assign the result of this function to a variable, it only contains the querystring (no results).
Code I'm Running:
$count = count_creatives();
echo $count;
Output:
PDOStatement Object ( [queryString] => SELECT COUNT(DISTINCT creative) FROM actions )
Any idea why I'm not getting the actual count (e.g. 2, 3, 100)?

You're returning the resource object from your function, not the field value. You need to fetch the result and then return that. Please use the following:
function count_creatives()
{
global $db;
$q = "SELECT COUNT(DISTINCT creative) AS `total` FROM actions";
$result = $db->query($q);
$actions = $result->fetchObject();
return $actions->total;
}

PDO::query() returns a PDOStatement object, or FALSE on failure. You need to do something like,
function count_creatives() {
global $db;
$q = "SELECT COUNT(DISTINCT creative) FROM actions";
$query = $db->query($q);
return $query->fetch(PDO::FETCH_NUM)[0];
}

Related

How can i count affected rows in SQLite3 with PDO PHP?

Hi i am trying to check if the IP is in the blocked list or not.
I am using SQLite3 in PHP. my problem is when trying to check with the function bellow it returns always true.
function isBlocked($ip){
global $pdo;
$check = $pdo->prepare("SELECT * FROM blockedUsers WHERE ip='".$ip."'");
$check->execute();
if($check->rowCount() >= 1){
return true;
}else{
return false;
}
}
Use SELECT COUNT(*) rather than SELECT *, since you don't care about the row data, just the count.
Also, use a parameter rather than substituting the variable into the SQL.
function isBlocked($ip){
global $pdo;
$check = $pdo->prepare("SELECT COUNT(*) AS count FROM blockedUsers WHERE ip=:ip");
$check->execute([':ip' => $ip]);
$row = $check->fetch(PDO::FETCH_ASSOC);
return $row['count'] > 0;
}

Is it possible to count number of parameters on a PDO Prepared Statement?

I have to process a few queries using a loop and all queries are the same, except for one which doesn't use the parameter the others do:
$queries = array(
'query1' = "SELECT * FROM table_1 WHERE id=:id",
'query2' = "SELECT * FROM table_2 WHERE id=:id",
'query3' = "SELECT * FROM table_3"
);
$params = array(':id',1);
foreach($queries as $q) {
$st = $pdo->prepare($q);
if($st->execute($params)) {
// do stuff with results
} else {
echo json_encode($st->errorInfo());
}
}
The problem here is that $st->execute($params) will not work on the query with no parameters defined, which is why I would like to know if it is possible to analyze the query before sending it.
This is fake code, and it should work regardless of the query structure as long as there is one parameter (:id) or none.
UPDATE, SOLVED:
How I applied the solution given by #Jonast92:
foreach($queries as $q) {
$st = $pdo->prepare($q);
if($st->execute(substr_count($q,":") > 0 ? $params : null)) {
// do stuff with results
} else {
echo json_encode($st->errorInfo());
}
}
You can use substr_count to count the number of : occurring, indicating the number of arguments to be executed onto the prepared statement.
$itemInArray = "SELECT * FROM table_1 WHERE id=:id";
$count = substr_count($itemInArray, ':'); // 1

Create single PHP Function for similar queries but with different WHERE clauses

I'm not sure if this is doable or not, and I'm not entirely sure how to search for this. I have several dynamic web pages that all link to the same MySQL database table, but pull different results. So for example, a dynamic web page with ID = 5 will run a query like:
SELECT * FROM myTable WHERE category1 = 1
The web page where ID = 7 will run:
SELECT * FROM myTable WHERE category2 = 1
And so on. The queries are all grabbing the data from the same table, but the WHERE clause is different for each query - its not looking at the same column. The page with ID 7 should ONLY be returning results where category2 = 1, and ignoring the results that would be returned for the page with id = 5. My website has about 20 different pages/queries like this which is why I'm looking to see if it can be done in a function instead.
Is there a way I can put that into a function, and if so, how would I set up the parameters correctly? Or is this an instance where I will have to just write out all the queries separately on each page?
function find_results(what to put here?) {
global $connection;
$query = "SELECT * FROM myTable WHERE (how to code this part?)";
$result = mysqli_query($connection, $query);
confirm_query ($result);
return $result;
}
You would add the necessary parameters to your functions argument list, then provide the values at runtime.
function find_results($column, $value)
{
global $connection;
$query = "SELECT * FROM myTable WHERE {$column} = $value";
$result = mysqli_query($connection, $query);
confirm_query ($result);
return $result;
}
//Usage:
$result = find_results("category2", 1)
If the value you are returning records by ever ends up being a string make sure your wrap $value in single quotes.
if its a constant relation between pageId and categoryId, you can just create an array to hold it indexed by pageId like:
$pageIdToCategoryMapping = [
1 => 'cateogory1',
2 => 'category5',
...
]
and then just use it to pass data to your function like
find_results($pageIdToCategoryMapping[$pageId])
function find_results($category) {
(...)
$query = "SELECT * FROM myTable WHERE ({$category} = 1)";
(...)
}
I have been using class and object methods for mysql operations. source code available in github
I would recommend you to pass array as an argument and can return query or result as array in format you required. And this function will work any number or condition
<?php
$arg['db']="database";
$arg['tabe']="table";
$arg['search']['id1']="id1";
$arg['search']['id2']="id2";
//
function searchAndReturnResultAsArray($arg)
{
$return = NULL;
$query="SELECT * FROM ".$arg['table'];
$flag=false;
foreach($arg['search'] as $key=>$value)
{
if($flag)
$query.=" AND ";
else
$flag=true;
$query.= $key." = '".$value."' ";
}
$row = mysqli_num_rows($query);
$field = mysqli_fetch_object($query);
if($row >= 1)
{
while($data = mysqli_fetch_array())
{
$return[] = $data;
}
}
return $return;
}
?>
Or alternatively you can just return query once it is ready.

mysql WHERE clause a variable which holds multiple values - is not working

I have fetched a column values in a variable from table1 and trying to use that variable to fetching another column values from table2 with WHERE clause.
I'm trying the below code, where $theseOpCode is holding the OpCode column values from user_profile table. I want to fetch values from $table WHERE OpCode='$theseOpCode'. I also tried WHERE IN ($theseOpCode) but no luck.
Someone please show me the right way.
index.php
$query=mysql_query("SELECT * FROM user_profile WHERE email='$thisEmail'") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
$theseOpCode = $row['OpCode'];
$_SESSION['Op'] = $theseOpCode;
}
I m trying to get the $theseOpCode as a session, and use this variable in WHERE clause in another file where my show class is.
showClass.php
class showClass{
public function showUser($table){
$theseOpCodeVal = $_SESSION['Op'];
$query=mysql_query("SELECT * FROM $table WHERE OpCode='$theseOpCodeVal'") or die(mysql_error());
$data=NULL;
if(mysql_num_rows($query)>0){
while($rows=mysql_fetch_assoc($query)){
$data[]=$rows;
}
return $data;
}else{
echo '<span class="text-info success">No Account Found.</span>';
exit();
}
}
}
My code is working but only showing the last value from WHERE clause. But I have 6 values in the $theseOpCodeVal variable. I want to fetch all values that matches $theseOpCodeVal variable values not only the last value that matched.
Why not use your relational database as was intended (using PDO, just because)...
class showClass {
private $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
public function showUser($table, $email) {
$stmt = $this->pdo->prepare("
SELECT a.* FROM `$table` a
INNER JOIN user_profile b ON a.OpCode = b.OpCode
WHERE b.email = ?");
$stmt->execute([$email]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
$pdo = new PDO('mysql:host=localhost;dbname=whatever;charset=utf8', 'username', 'password', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
$showClass = new showClass($pdo);
$thisEmail = 'wherever you got the value from in the first place';
$table = 'some_table';
$data = $showClass->showUser($table, $thisEmail);
First store all opCodes
$query=mysql_query("SELECT * FROM user_profile WHERE email='$thisEmail'") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
$theseOpCode = $row['OpCode'];
$_SESSION['Op'][] = $theseOpCode;
}
Next, query with IN operator
$query=mysql_query("SELECT * FROM $table WHERE OpCode IN ('".implode("','", $theseOpCodeVal)."')") or die(mysql_error());
First thing you have to make '$theseOpCodeVal' commas separated value and then use 'IN' operator like:
'WHERE OpCode IN ($theseOpCodeVal)'; instead of WHERE IN.

php functions within functions

ihave created a simple project to help me get to grips with php and mysql, but have run into a minor issue, i have a working solution but would like to understand why i cannot run this code successfully this way, ill explain:
i have a function,
function fetch_all_movies(){
global $connection;
$query = 'select distinct * FROM `'.TABLE_MOVIE.'` ORDER BY movieName ASC';
$stmt = mysqli_prepare($connection,$query);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt,$id,$name,$genre,$date,$year);
while(mysqli_stmt_fetch($stmt)){
$editUrl = "index.php?a=editMovie&movieId=".$id."";
$delUrl = "index.php?a=delMovie&movieId=".$id."";
echo "<tr><td>".$id."</td><td>".$name."</td><td>".$date."</td><td>".get_actors($id)."</td><td>Edit | Delete</td></tr>";
}
}
this fetches all the movies in my db, then i wish to get the count of actors for each film, so i pass in the get_actors($id) function which gets the movie id and then gives me the count of how many actors are realted to a film.
here is the function for that:
function get_actors($movieId){
global $connection;
$query = 'SELECT DISTINCT COUNT(*) FROM `'.TABLE_ACTORS.'` WHERE movieId = "'.$movieId.'"';
$result = mysqli_query($connection,$query);
$row = mysqli_fetch_array($result);
return $row[0];
}
the functions both work perfect when called separately, i just would like to understand when i pass the function inside a function i get this warning:
Warning: mysqli_fetch_array() expects
parameter 1 to be mysqli_result,
boolean given in
/Applications/MAMP/htdocs/movie_db/includes/functions.inc.php
on line 287
could anyone help me understand why?
many thanks.
mysqli_query failed to run your query:
Returns FALSE on failure. For
successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will
return a result object. For other
successful queries mysqli_query() will
return TRUE.
Before running mysqli_fetch_array test $result... Something like:
if ($result !== false)
$row = mysqli_fetch_array($result);
else
return false;
Seems like a variable scope issue within your SQL statement. Outputting the SQL should show you the "true" error.
You may want to try using classes with your functions, for example:
class getInfo {
function fetch_all_movies(){
global $connection;
$query = 'select distinct * FROM `'.TABLE_MOVIE.'` ORDER BY movieName ASC';
$stmt = mysqli_prepare($connection,$query);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt,$id,$name,$genre,$date,$year);
while(mysqli_stmt_fetch($stmt)){
$editUrl = "index.php?a=editMovie&movieId=".$id."";
$delUrl = "index.php?a=delMovie&movieId=".$id."";
echo "<tr><td>".$id."</td><td>".$name."</td><td>".$date."</td><td>".get_actors($id)."</td><td>Edit | Delete</td></tr>";
}
}
function get_actors($movieId){
global $connection;
$query = 'SELECT DISTINCT COUNT(*) FROM `'.TABLE_ACTORS.'` WHERE movieId = "'.$movieId.'"';
$result = mysqli_query($connection,$query);
$row = mysqli_fetch_array($result);
return $row[0];
}
}
$showInfo = new getInfo;
//fetch all movies
$showInfo->fetch_all_movies();
//List actors from movie 1
$showInfo->get_actors("1");
In case of an error mysqli_query will return false. You have to handle the error a simple way to do this might be:
$result = mysqli_query($connection,$query);
if (!$result) {
die(mysqli_error($connection));
}
$row = mysqli_fetch_array($result);
Please note that terminating (by doing die() ) usually is no good way to react on an error, log it, give the user anice error page etc. It's alsonogood practice to give the low level error message toauser, this might motivate users to try to exploit a possile security issue.
Last remark: you were writing
$query = 'SELECT DISTINCT COUNT(*) FROM `'.TABLE_ACTORS.'` WHERE movieId = "'.$movieId.'"';
you should properly escape the movieId there.

Categories