Im trying to get the amount of elements in an array using the count() function, the result is a bit puzzling to me, considere the following example.
Assume that the user ID provided is wrong, and therefore had no matches, wouldnt then the result of the count function be 0? yet it is 1. can you explain to me why?
thanks
$q = mysql_query("select password from users where user_name = '" . $userID . "'");
$check = mysql_fetch_array($q);
$result = count($check);
echo "RESULT:" . $result;
That's the wrong way to count rows in a result set. First of all, from the documentation on mysql_fetch_array()
Returns an array of strings that
corresponds to the fetched row, or
FALSE if there are no more rows.
Ergo, if we do this
echo count( false );
We can see the output is 1. Why? Because the count() documentation tells us that as well
If var is not an array or an object
with implemented Countable interface,
1 will be returned.
To do a proper count, use mysql_num_rows()
$q = mysql_query("select password from users where user_name = '" . $userID . "'");
$result = mysql_num_rows( $q );
if ( 0 == $result )
{
// no rows in result
}
use mysql_num_rows instead of count. count returns 1 for the value FALSE
count() returns 1 because in case of failure $check is not an array.
From the documentation:
If var is not an array or an object with implemented Countable interface, 1 will be returned
But you should anyway handle error cases directly (if the query fails your code shouldn't even get to the point where you analize its results). Also as other have correctly said, that's not how you count the number of results a query returns as that's what mysql_num_rows() is for
mysql_fetch_array returns false if there are no more rows. count(false) = 1.
Try using mysql_num_rows if you want to count the number of results.
Related
$total_numMIN = mysqli_query($con,"SELECT MIN(id) FROM view_rating");
$total_numMAX = mysqli_query($con,"SELECT MAX(id) FROM view_rating");
$random_no = mt_rand($total_numMIN, $total_numMAX);
print $random_no;
I'm trying to get a single number randomly generated from the smallest and largest numbers in my database. Right now the error I'm getting is
Warning: mt_rand() expects parameter 1 to be integer, object given in
I'm just not exactly sure why the results of the queries aren't integers
mysqli_query() returns a mysqli_result which is an object and not the numbers you are expecting. You need to get an array of results from your query. The MIN and MAX queries can also be combined into a single query.
$result = mysqli_query($con,"SELECT MIN(id) as min, MAX(id) as max FROM view_rating");
if($result) {
$resultArray = $result->fetch_assoc();
$random_no = mt_rand($resultArray['min'], $resultArray['max']);
print $random_no;
}
There may be a cleaner way to do this. I haven't used PHP in a long time.
change your code like this
$total_numMIN = mysqli_fetch_assoc(mysqli_query($con,"SELECT MIN(id) as min,MAX(id) as max FROM view_rating"));
$random_no = mt_rand($total_numMIN['min'], $total_numMAX['max']);
print $random_no;
because mysqli_query just give you a object. you have to fetch data as an associative array and then you can use it into mt_rand
hope this will work
The mysql_query returns a result - and not a value.
From the documentation on the function: http://php.net/manual/en/mysqli.query.php
Return Values
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
When I'm trying to get the number of rows on a SQL request and if not, the connection that follow fails.
But in any case (also if the request should return 0), it returns 1.
Here's my code :
$str = 'SELECT count(*) FROM admins WHERE mail = ? AND mdp = ?';
$arr = array($mail, $pass);
$rqt = sendRqt($str, $arr);
$tab = $rqt->fetchColumn();
$cnt = count($tab);
echo $cnt;
I don't understand why there's no time it returns 0
The problem is the use of the php function count().
You already have the correct number in your $tab variable as a string (probably, depends on php configuration / version) so you can echo it or cast it to an integer to make sure it is a number.
However, in php:
count(0) === 1
count('0') === 1
See here for example.
You should remove count($tab).
the SQL "COUNT(*)" allways returns a row with the count (quantity) of values, so if you apply the php count() function, always will return 1 because there is one row that contains the value of the COUNT sql function
I believe COUNT() needs a column name.WRONG!! count(*) should count all rows, but I still reccomend a column name like id or something. You could also use an AS to make life a little easier
$str = 'SELECT count(`COLUMNNAME`) AS cnt FROM table WHERE ....
I'm using the following code to find the number of rows returned:
global $wpdb;
$results = $wpdb->get_results("SELECT * FROM list WHERE queue = 1 ORDER BY id ASC LIMIT 0,1");
$rowcount = $results->num_rows;
echo $rowcount;
As you can see, the results are limited to 1 row, and when I run this query in SQL it returns 1 row just fine. But in PHP the $rowcount doesn't return any value at all.
Any ideas what might be wrong? I get no error.
I think you need to use count($results) since the method $wpdb->get_results returns a array of objects/arrays.
Another way to get the number of rows is to use $wpdb->num_rows. Apparently this works for
$wpdb->get_results.
From the docs (http://codex.wordpress.org/Class_Reference/wpdb), it says the following about get_results:
Generic, multiple row results can be pulled from the database with
get_results. The function returns the entire query result as an array.
Each element of this array corresponds to one row of the query result
and, like get_row, can be an object, an associative array, or a
numbered array. If no matching rows are found, or if there is a
database error, the return value will be an empty array. If your
$query string is empty, or you pass an invalid $output_type, NULL will
be returned.
For an application I'm trying to count the total of friends. I want to do this with a function but it isn't returning anything. It tells me this:
Warning: mysqli_query() expects at least 2 parameters, 1 given
But I only need one parameter. I think I'm totally wrong.
This is the function:
public function GetTotalOfFriends($user_id){
$db = new Db();
$select = "SELECT COUNT FROM friendship WHERE (friendship_recipient_id ='" . $user_id ."' OR friendship_applicant_id = '" . $user_id . "') AND friendship_status = 'accepted'";
$result = $db->conn->query($select);
$row = mysqli_query($result);
$total = $row[0];
echo $total;
I'm trying to print it out in this way:
$friend = new Friendship;
$numberoffriends = $friend->GetTotalOfFriends($user_id);
<?php echo $numberoffriends; ?>
You are mixing up a couple of things. The line $result = $db->conn->query($select); already seems to execute a query, but then you try to bypass your database wrapper by passing that query result again to mysqli_query.
Apart from that, I think your query itself is also wrong. COUNT needs a parameter, indicating a field or value to count. Quite often COUNT(*) is used, but COUNT('x') might be more efficient in some cases. You can also use a specific field name, and COUNT will count the non-null values for you.
The result you got is a mysql_result object, which you need to use to get to the actual data of the query result.
The documentation of this object is here and I suggest that you read it thoroughly.
One possible way to do this is using this:
$resultArray = $result->fetch_row();
This will result in the first (and only) row of your query. It is represented as an array, with one value (since your query returns only one column). You can fetch that value like this:
return $resultArray[0];
You could also use any of the other fetch methods if you want your data in a different fashion.
I have been working on this for a while now, I know it's simpler than what I am making it, but I just can't get it. I have some code where I am trying to query an enum either 1 or 0 from my table so this is exactly what I have to do this.
$username = 'test'
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='.$username.'");
Now I have all the connection stuff down I think, I get no errors there, but when I print this thing out in my echo I get this,
Heres my echo:
echo 'Hello, '.$username.', you Result is: '.$passResult.'!';
What I want to get is:
Hello, test, your Result is: 1
or
Hello, test, your Result is: 0
Now what I get is:
Hello, test, your Result is: Resource id #6
Now no matter what I do I get the same thing, I have no idea what I'm doing wrong here guys if someone could point this out that would be awesome. What this enum is being use essentially for a boolean just to see if the user has personally set a password not the computer generated version.
mysql_query returns a result resource, essentially a pointer to the memory where the results are buffered. That result set can contain many rows, as you can select many rows, so you need to fetch the row(s) you want then the column(s) you want from those rows.
/* execute the query and get a result resource back */
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='" . mysql_real_escape_string($username) . "'");
/* retrieve the first row from $passResult */
$row = mysql_fetch_assoc($passResult);
/* assign the usrSetPass column's value from that row to $passed */
$passed = $row['usrSetPass'];
Also, your query is wrong. You enclosed it in double quotes, so you're not actually breaking out of the string and concatenating $username when you use the single quotes and dots inside. I've corrected it above.
mysql_query doesn't return a value, it returns a resource (see here in the manual).
The returned result resource should be passed to another function for dealing with result tables (like mysql_fetch_array() or mysql_fetch_assoc()), to access the returned data.
Example based on your initial code:
$username = 'test';
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='".$username."'");
while ($row = mysql_fetch_assoc($passResult)) {
echo $row['usrSetPass'];
}