I have this function in a linked file:
function getNumberOfHerps() {
$sql = "SELECT COUNT(ID)
FROM HERPES;";
return DBIface::connect()->query($sql);
}
I can call on this function from any other page in the website. What I want to do is to be able to use the result of the COUNT function in my php code on various pages, because I need to know how many herps there are in the database on several occasions in the code.
I tried this:
$result = getNumberOfHerps();
$numberOfHerps = $result['COUNT'];
But it caused a parse error on the second line, saying this:
Cannot use object of type PDOStatement as array.
Please tell me how I can use the result of a Count function in php code. Thanks :D
You are actually facing 2 separate items here that need your attention:
You can't access the COUNT(ID) returned from your query and
You are attempting to access data of a PDOStatement object as an array
So:
You can create an ALIAS for the value returned from the COUNT() function:
$sql = "SELECT COUNT(ID) as COUNT...";
This will provide to your result set a new column named COUNT that you can access your row count from.
Secondly, you need to perform a fetch operation on the PDOStatement in order to access it's data (this is what is causing your parse error). You have several options for accessing the result set in a PDOStatement:
list ($idCount) = $result->fetch();
// $idCount will now have the value of your COUNT column
or
$results = $result->fetch(PDO::FETCH_ASSOC);
// you can then access your COUNT as $results['COUNT'];
or even
$results = $result->fetch(PDO::FETCH_OBJ);
// you can then access your count as $results->COUNT
There are actually several additional FETCH_* styles available to use. The ones I've described though would likely be the most common. You can find more information about fetching PDO result sets at
http://us1.php.net/manual/en/pdostatement.fetch.php
I worked it out for myself, so I'll put my answer up for anyone else who finds this question:
I changed the function to this:
function getNumberOfHerps() {
$sql = "SELECT COUNT(1)
FROM HERPES";
return DBIface::connect()->query($sql)->fetchColumn(0);
}
So what the function now returns is the actual count value (the first column of the query). That means that in the webpage php file, you can access it in this way:
$numberOfHerps = getNumberOfHerps();
Much more simple.
Related
I am new to php and mysqli and have been going through and trying to understand how a lot of these built in functions work. I have read the documentation and many tutorials/examples.
I have something like:
$conn = new mysqli(vars); <br />
$sql = "Select * from Users where name ='$name'";
$result = $conn->query($sql);
$pass = result->fetch_assoc()['Pass'];
//check password stuff
that works fine, however if I then try to use $result->fetch_assoc()['ID'] it returns null. If I swap the order of ID and Pass then the id returns and pass comes back null.
I don't understand why this is the case. What I think (which is clearly wrong) is that result should store the whole row (which it does) and then when i fetch assoc I should just be pulling data from the row. However it seems to be overwriting result when I fetch assoc. What's up with that?
My work around is to call the query multiple times for each data point i need to start a session and store variables, and I know I can use prepared statements, but I feel like there's a better way and I'm missing it.
Can someone please explain?
Every time you call fetch_assoc(), it fetches the next row. There'll presumably only be one user with a specific name, so the result of the second fetch_assoc() call will be null.
Store the value of $result->fetch_assoc() and you can do what you want with it afterwards.
$user = $result->fetch_assoc();
echo $user['ID'];
echo $user['Pass'];
I have quite an issue I can not seem to solve. I am trying to get a row count from a select statement.
I should start by saying I have tried most all methods resulting from google searches on this issue.
I am using the result set so I would prefer not to make a second query.
The query uses a prepared select statement which seems to be a main issue if I understand it correctly.
I decided to try a simple approach using PHP's native count() function. Which lead me here because I finally reached the end of the rope on this.
On to the details...within a class of mine, I make the query like this.
// Create database connection
$database = DatabaseFactory::getFactory()->getConnection();
// Set and execute database query
$sql = "SELECT * FROM `service_orders` WHERE `agency_id` = :agency_id $filter ORDER BY $sort $order $per_page";
$query = $database->prepare($sql);
$query->execute($query_array);
// If results
if ($query->rowCount() > 0) {
$results = $query->fetchAll();
self::$order_count = "Count: " . count($results);
return $results;
}
// Default, return false
return false;
Findings
If I perform count($results) like I did above, I get the total rows in the database (Let's say 50).
If I print_r($results), it shows the array with the proper number of entries (Let's say 10) that of course differs from the total rows in the database.
How can these two differ? It's as if the count($results) is misreading the result array.
More Findings
Within my actual php page, I call the class to retrieve the data like this.
$results = OrderModel::getServiceOrders();
echo count($results);
Strangely enough, if I then perform count($results) it gives me the correct reading of the result array (which in my example here would be 10).
I am perplexed by this as the count function is being performed on the exact same array. The only difference is one is called on the array within the class, and the other is called on the array returned from the class.
Does anyone have any ideas on how to solve this or why there is the discrepancy when using count() in this instance?
Thank you all in advance!
James
Additional Info
This is another mind numbing scenario. If I return the count along with the actual results, I can access it on the page with the correct value (10 rows). Yet, if I set it into a session variable, and access it that way, the count is the whole data set (50 rows). How is it even possible these two values are not the same?!
$results = $query->fetchAll();
Session::set("order_count", $total[0]); // Yields 50 (incorrect)
return [
"results"=> $results,
"count"=> $total[0], // Yields 10 (correct)
];
I'm a beginner who has problems with PHP :(
I have a PHP function which shows all the rows from the database table. Now I have to create paging to show only limited number of rows per one page.
I have a problem with retrieving a COUNT result from query. I want to create a condition where PHP & MySQL use LIMIT if number of rows is bigger than needed on one page. The following code:
$count = "SELECT COUNT(*) FROM articles";
$countq = $db->query($count);
$countrs = mysql_fetch_array($countq);
echo $countrs;
should display a number of rows. However, it does not. What am I doing wrong? I want to see a result to make sure that everything else will work fine. But I can't get it working.
Error: mysql_fetch_array() expects parameter 1 to be resource, object given
$db contains database connection information (server, user...) and is working
Use PDO for MySQL query.
$db = new PDO('mysql:host=#YOUR HOST#;dbname=#YOUR DB#;charset=utf8', '#YOUR LOGIN#', '#YOUR PASSWORD#');
$query = $db->query('SELECT COUNT(*) AS count FROM articles');
$countq = $query->fetch();
$query->closeCursor();
echo $countq['count'];
I hope this will help you
You will have to set the limit in the query like
$count = "SELECT COUNT(*) FROM articles LIMIT 5,10";
where 5 is the starting point and 10 is the total number of results you want.
You mention: $db but not what $db is? i mean is it a database object class? this will work directly if you are using the a database class, and if that's the case the class will also have functions which will allow you to query data without using mysql_fetch_array (actually mysqli_fetch_array).
I am trying to retrieve a specific field from the first row of my query results. The following works just fine...
$result = $db->query($query);
$firstrow = $result->fetch();
$desired_field = $firstrow["field"];
My question is, can i do this in one step without storing the first row of results in a variable? Thanks in advance!
You can use fetchColumn() to return a single column from the next row in the result set. If there is only one column in the result set, do:
$desired_field = $result->fetchColumn();
If there are multiple columns in the result set, specific the numeric index of the one you want:
$desired_field = $result->fetchColumn(1);
Take notice of the warning provided in the fetchColumn() documentation:
There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data.
You can use something like $firstrow = $db->query($query)->fetch() but this is not good practice to do with functions that aren't guaranteed to return an object.
The query() function can return FALSE on error, and the dynamic call to fetch() would be a fatal error. You can't call ->fetch() on a scalar FALSE value.
For example, try the following and your script will explode:
$firstrow = $db->query("SELECT * FROM table_that_does_not_exist")->fetch();
PDO does support a mode to throw exceptions instead of returning FALSE, so in that case you are guaranteed either query()->fetch() works, or else query() will throw an exception, so you will never reach the fatal error. But you might not be using PDO's exception mode.
The answer from #GeorgeCummins points out that there's a fetchColumn() method that you can use once you have a PDOStatement object, that's a good way to get a single column. If you only need one column, name that column as the only column in your select-list, and then always use fetchColumn(0):
$oneValue = $db->query("SELECT oneColumn FROM table")->fetchColumn(0);
Otherwise if you use fetch(), this returns an array. PHP 5.4 supports array dereferencing:
$oneValue = $db->query("SELECT oneColumn FROM table")->fetch()[0];
But if you're using PHP 5.3 or earlier this is not supported. And I've never tried it with the array returned by PDOStatement so if it's actually returning an ArrayObject or something this might not work anyway.
This is guarantee to work if and only if your query is correct and there is at least one row data.
$db->query($query)->fetch(PDO::FETCH_OBJ)->field;
I am trying to figure out the proper way to get file location data (for display/editing) from MySQL with PHP. So far I've got these three parts. $resfile is a resource getting the actual array. Would I then test with an if statement, or would I have to use a while loop to iterate over the array (which, as far as I know, should only have ONE value)
First part:
$resfile = mysql_query('SELECT file_loc WHERE org_id = '.$org);
Do I use this?
if (!$resfile) {
}
Or this?
while ($filerow = mysql_fetch_array($resfile)) {
}
Or both?
The mySQL library has a function for counting the rows of a result set:
if (mysql_num_rows($resfile) > 0) .......
You need to use both. If the query returns false, then there was an error executing your query. If there is no data returned in the query, (it will still return true) then you need to use fetch_array to get the data.