unable to get to count - php

$query = $db->prepare("SELECT COUNT(id_u) FROM account");
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
$count = $result['count(id_u)'];
echo $count;
Not sure what I'm doing wrong here. I'm trying to get it to count the amount of registered users we have by counting the amount of id_u's (user id).
Like I said in the comments, It might be similar to other posts but those don't explain how to fix my situation since they are not quite the same.

EDIT:
After testing the issue you are experiencing; I managed to solve why your solution is not working. It appears that it is due to you calling COUNT(id_u) in the SQL query, then in the echo statement you are trying to get count(id_u) which doesn't exist in the array. Try
$count = $result;
$count = $result['COUNT(id_u)'];
To detect where the issue is stemming from I'd suggest you add in a print_r($result);. This will give you an idea what is returning from your SQL query in an array format. Once you see what data is returned and available, you can then determine how you echo/print the result.
My opinion on how this should be done:
The use of prepared statements in this is not necessary in my opinion for counting rows.
What I would do is:
$rowCount = $db->query('SELECT COUNT(*) FROM account')->fetchColumn();
echo $rowCount;

$count = count($result['id_u']);

Related

PHP variable is not working with WHERE clause

My query is not working when I use the variable in the WHERE clause. I have tried everything. I echo the variable $res, it shows me the perfect value, when I use the variable in the query the query is not fetching anything thus mysqli_num_rows is giving me the zero value, but when I give the value that the variable contains statically the query executes perfectly. I have used the same kind of code many times and it worked perfectly, but now in this part of module it is not working.
Code:
$res = $_GET['res']; // I have tried both post and get
echo $res; //here it echos the value = mahanta
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'"; // Here it contains the problem I have tried everything. Note: restaurant name is same as it is in the database $res contains a value and also when I give the value of $res i.e. mahanta in the query it is then working.
$z = mysqli_query($conn, $query);
$row2 = mysqli_fetch_array($z);
echo var_dump($row2); // It is giving me null
$num = mysqli_num_rows($z); // Gives zero
if ($num > 0) {
while ($row2 = mysqli_fetch_array($z)) {
$no = $row2['orders'];
$id = $res . $no;
}
}
else {
echo "none selected";
}
As discussed in the comment. By printing the query var_dump($query), you will get the exact syntax that you are sending to your database to query.
Debugging Tip: You can also test by pasting the var_dump($query) value in your database and you will see the results if your query is okay.
So update your query syntax and print the query will help you.
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'";
var_dump($query);
Hope this will help you and for newbies in future, how to test your queries.
Suggestion: Also see how to write a mysql query syntax for better understanding php variables inside mysql query
The problem is the way you're using $res in your query. Use .$res instead. In PHP (native or framework), injecting variables into queries need a proper syntax.

Number of records returned after using prepared statement

I am currently taking an IT course in which people can bring in their computer(s) and the class works on them to get experience. Right now, the instructor has the customers fill out a sheet of paper giving their name, phone number and the computer's issue(s). However, he would like to use a PHP page to allow the students or himself look back to see what this person's previous issues were (if any). I am using PDO and prepared statements to query the database, but I am having trouble figuring out how to get the number of records returned by the prepared statement. I've tried using stmt_num_rows, but it doesn't appear to be working. Here is the code I have so far:
$custID = $_GET["id"];
$compID = $_GET["compID"];
$stmtIssues = $db->prepare("SELECT IssueID, DateRequested, Issue, ActionsTaken FROM ISSUES WHERE ComputerID=:compID AND CustomerID=:custID ORDER BY DateRequested");
$stmtIssues->bindParam(":custID", $custID);
$stmtIssues->bindParam(":compID", $compID);
$stmtIssues->execute();
$numIssues = stmt_num_rows($stmtIssues);
Am I doing this right?
Any and all help is greatly appreciated.
Chris
You could do a few things:
Solution one, if you just want the count, let the database count for you:
$stmtIssues = $db->prepare("SELECT COUNT(IssueID) FROM ISSUES WHERE ComputerID=:compID AND CustomerID=:custID ORDER BY DateRequested");
$stmtIssues->bindParam(":custID", $custID);
$stmtIssues->bindParam(":compID", $compID);
$stmtIssues->execute();
$numIssues = $stmtIssues->fetchColumn();
Solution two, if you're going to display the results in addition to the count:
$stmtIssues = $db->prepare("SELECT IssueID, DateRequested, Issue, ActionsTaken FROM ISSUES WHERE ComputerID=:compID AND CustomerID=:custID ORDER BY DateRequested");
$stmtIssues->bindParam(":custID", $custID);
$stmtIssues->bindParam(":compID", $compID);
$stmtIssues->execute();
$rows = $db->fetchAll();
$numIssues = count($rows);
foreach ($rows as $row) {
echo $row['IssueID']; // you can add other columns and/or formatting here too.
}
Solution one is quicker and returns only the count. Solution two, on the other hand, returns all details you may want to display.

Displaying users with a php, sql count?

I have a database with users input and was wanting to output a user table (id, username) as a count on a page. The following piece of code is what I've been trying to work with but I've been having no luck and it keeps getting more and more complex - the SQL works perfectly so I'm not sure what's wrong.
mysqli_select_db($db);
$result = $_POST ['$result'] ;
$result = mysqli_query("SELECT COUNT( * )
FROM users");
$row = mysqli_real_escape_string($result,$db);
$total = $row[0];
echo "Total rows: " . $total;
I'm still learning how to properly link SQL in with PHP. The warnings tell me to add an extra parameter however when I do so it still complains.
I originally wanted a simple COUNT but will change the count to a table array if need be. I understand this maybe a little basic and I may have been going about it the wrong way, but I've hit a wall with it and any help on fixing the COUNT would be greatly appreciated
Replace the call to mysqli_real_escape_string to mysqli_fetch_array and your code will works.
mysqli_real_escape_string is only useful for string escaping when you INSERT or UPDATE data to MySQL.
$row = mysqli_fetch_array ($result);
Please try this code:
$sql="SELECT * FROM users";
$result=mysqli_query($con,$sql);
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
$number = count($rows);
Hope this works.

For-loop not returning all values

I'm working on a piece of code that's meant to be implemented in Google Charts, however, not all values I'm looking for are being returned.
I need a couple of dates selected from my database, and I select them as follows:
$dates = mysql_fetch_row(mysql_query("SELECT DISTINCT date FROM participants WHERE subdomein='testdomain'")) or die(mysql_error());
Then I use a for-loop to echo them:
for ($i = 0; $i <= count($dates); $i++)
{
echo $dates[0].' ';
}
In my database there are 3 (distinct) dates: 24-03-2013, 25-03-2013 and 26-03-2013, however the piece of code returns 2x 24-03-2013. What am I doing wrong here?
P.S. I also tried a while-loop but that loops infinitely or crashes my page. Besides that, I tested the query by running it in the database itself and it returns the right results, so the query works fine.
Help is much appreciated!
You need to use mysql_fetch_row() inside a loop in itself:
$result = mysql_query("SELECT DISTINCT date FROM participants WHERE subdomein='testdomain'");
while($date = mysql_fetch_row($result))
{
echo $date[0];
}
You should also note that the mysql_* family of functions are not deprecated. You should avoid using them if possible, and look into alternatives such as MySQLi or PDO.
Try this: mysql_fetch_row() fetches only one row, If you need all the rows use mysql_fetch_assoc()
$sql = mysql_query("SELECT DISTINCT date FROM participants WHERE subdomein='testdomain'");
while($dates = mysql_fetch_assoc() ($sql)){
print_r($dates);
}
Ref: http://php.net/manual/en/function.mysql-fetch-row.php
http://www.php.net/manual/en/function.mysql-fetch-assoc.php
mysql_fetch_row only returns one record from the actual result of your query. You have to call it several times, ontil it returns null :
$res = mysql_query(...);
while (($record = mysql_fecth_row($res)) !== null) {
print_r($record[0]);
}
Please note mysql_* function are deprecated and should not be used anymore, too.

Is mysql_num_rows efficient and/or standard practice?

A while ago I was poking around with SQLite, trying to port some of my sites to use it instead of MySQL. I got hung up on the lack of a function to count results, like PHP's mysql_num_rows(). After searching a little I discovered this mail list, which says (as I understand it) that SQLite doesn't have that functionality because it's inefficient. It states that it is bad form to write code that needs to know how many rows are returned.
I generally use mysql_num_rows to check for empty return results. For example:
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
if (mysql_num_rows($results)) {
while ($row = mysql_fetch_array($results)) {
echo "<p>$row[whatever]</p>";
}
} else {
echo "<p>No results found</p>";
}
The vehement distaste for the concept of mysql_num_rows() in the SQLite community makes me wonder if it's that terribly efficient for regular MySQL in PHP.
Is there a better, more accepted way for checking the size of a MySQL result set in PHP besides mysql_num_rows()?
EDIT:
I'm not just using mysql_num_rows to get the count--I would use a COUNT query for that. I'm using it to check if there are any results before outputting everything. This is useful for something like displaying search results - it's not always guaranteed that there will be results. In SQLite world, I have to send one COUNT query, check if there is something, and then send a SELECT query to get everything.
You already have something that is telling you if you've got results in mysql_fetch_array(). It returns false if there are no more rows to fetch (from php.net).
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
if($results) {
$row = mysql_fetch_array($results);
if($row) {
do {
echo "<p>{$row[whatever]}</p>";
} while($row = mysql_fetch_array($results));
} else {
echo "<p>No results found</p>";
}
} else {
echo "<p>There was an error executing this query.</p>";
}
Regardless of whether or not you actually use what you SELECTed, all of the rows are still returned. This is terribly inefficient because you're just throwing away the results, but you're still making your database do all of the work for you. If all you're doing is counting, you're doing all that processing for nothing. Your solution is to simply use COUNT(*). Just swap COUNT(*) in where you would have your SELECT statement and you're good to go.
However, this mostly applies to people using it as a complete substitute for COUNT. In your case, the usage isn't really bad at all. You will just have to manually count them in your loop (this is the preferred solution for SQLite users).
The reason being is in the underlying SQLite API. It doesn't return the whole result set at once, so it has no way of knowing how many results there are.
As explained on the mailing list you found. It is inefficient to return the count of rows because you need to allocate a lot of memory to hold the entire (remaining) result set. What you could do, is to simply use a boolean to test if you have output anything.
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
$empty_result = true;
while ($row = mysql_fetch_array($results)) {
echo "<p>$row[whatever]</p>";
$empty_result = false;
}
if ($empty_result) {
echo "<p>No results found</p>";
}

Categories