I have this query to use in PHP:
mysql_query("select count(*) from registeredUsers where email=".$_SESSION["username"]);
When I use echo to print out the result, nothing gets printed. What exactly is the return value from the above statement?
Your code doesn't include any fetch statement. And as another answer notes, you need single quotes around $_SESSION["username"].
$result = mysql_query("select count(*) from registeredUsers where email='{$_SESSION['username']}'");
// Verify it worked
if (!$result) echo mysql_error();
$row = mysql_fetch_row($result);
// Should show you an integer result.
print_r($row);
mysql_query returns a result resource. You can read the result with mysql_result
$res = mysql_query("select count(*) from registeredUsers where email='".mysql_real_escape_string($_SESSION["username"])."'");
echo mysql_result($res,0);
You need single quotes around the session variable in your query
$result = mysql_query("SELECT COUNT(*)
FROM registeredUsers
WHERE email = '".$_SESSION['username']."' ");
The count query will always return a value, which is 0 if no records are returned, or an integer above 0 if records match it.
It should at least be printing out 0, the query you posted means:
Get the number of records where the email address is equal to the session username
This might not make sense, do you mean to do where username = ".$_SESSION["username"] or something similar?
You may want to echo out the query itself to determine that it is returning what you expect.
mysql_query() returns a resource used to get information from the result set. Use a function such as mysql_fetch_array() to retrieve rows from the result set. In this case, there will only be one row.
It should give you the amount of registere users who have the email address that you provide as the parameter to this query. (Might be a check if the given email address is already registered for another user.)
If the email address is not yet registered, an empty field will be returned. (That might be the reason why nothing gets printed out in your case. Try it with an email address that you are certain of to be in the database.)
$resultemp = mysql_query("select count(*) AS count from registeredUsers where email='{$_SESSION['username']}'");
// Verify mySQL Query Rresult
if (!$resultemp) echo mysql_error();
// Convert mySQL Result for PHP
$counter=mysql_fetch_assoc($resultemp);
$counter=$counter['count'];
// Print Total Employees
echo $counter;
You need to use mysql_fetch_array() to return value in a user defined variable. Then have to print the returned value.
$result=mysql_query("select count(*) from registeredUsers where email='{$_SESSION['username']}'")
$COUNT_NUMBER=mysql_fetch_array($result);
echo "<br>1.Count=" .$COUNT_NUMBER[0];
Try casting it to string before echoing it. As an int, 0 will display as an empty string.
Related
I have a query which is to check data from two different tables everything is working fine though. When i paste the query in cPanel then result is showing like this
MySQL returned an empty result set (i.e. zero rows). (Query took 0.0005 sec)
but when i count the query in php it is returing 1 instead of 0 don't know why
Here is my Sql query
SELECT mobile, emailid
FROM tbl_users
WHERE mobile =9653878051
AND emailid = 'rawat#gmail.com'
GROUP BY mobile
UNION ALL SELECT mobile, email
FROM tbl_addusr
WHERE mobile =9653878051
AND email = 'rawat#gmail
.com'
LIMIT 0 , 30
and i am counting it like this i am storing the sql result in data variable
$result = mysql_num_rows($data);
echo count($result)>0?1:0;
and it is resulting 1 instead of 0
You do not need to count anything. mysql_num_rows gives you the number of rows.
Use like this:
$result = mysql_query($query);
echo mysql_num_rows($result);
1: Stop using mysql_* functions. Use mysqli or PDO instead.
2: Use SQL Count: http://www.w3schools.com/sql/sql_func_count.asp
Oh yes, just as advise: don't use variable names like $aaaaaa ... names like this one just say nothing about what the variable is and when you repopen the project in a few month you won't understand anything what you've done.
You are using the count() function of PHP, which from the manual states:
Returns the number of elements in array_or_countable. If the parameter is not an array or not an object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable is NULL, 0 will be returned.
So on your case, it will return 1. Just remove the count() function and compare the value of $result itself in your ternary operator.
mysql_num_rows — Get number of rows in result not array
Description
int mysql_num_rows ( resource $result )
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
Parameters
result
The result resource that is being evaluated. This result comes from a call to mysql_query().
Return Values
The number of rows in a result set on success or FALSE on failure.
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query(" SELECT mobile, emailid
FROM tbl_users
WHERE mobile =9653878051
AND emailid = 'rawat#gmail.com'
GROUP BY mobile
UNION ALL SELECT mobile, email
FROM tbl_addusr
WHERE mobile =9653878051
AND email = 'rawat#gmail
.com'
LIMIT 0 , 30", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
echo $num_rows>0?1:0;//compare like this
?>
check doc http://php.net/manual/en/function.mysql-num-rows.php and http://php.net/manual/en/function.count.php
I have been trying to show a summaries of a column with the SUM() function in PHP.
I'm using $pointsummary= "SELECT SUM(points) FROM result WHERE id=$val"; to call my SUM function but i cant show it in my PHP. I've tried $test = mysqli_fetch_array($pointsummary); and then echo $test[0]; but it wont work.
When i do this i get:
mysqli_fetch_array() expects parameter 1 to be mysqli_result
What should i do?
Your error is caused by the fact that $pointsummary is a string and not a mysqli_result object. you need to use mysqli_query first and use what that returns. eg.
$resultObj = mysqli_query($con, $pointsummary); // <--- $con is what you got from mysqli_connect()
$resultArr = mysqli_fetch_array($resultObj);
Another note is that with SELECT SUM(points) FROM result i would suggest aliasing SUM(points) with a name you'll recognize so that instead of having to var_dump the key/values of the mysqli_fetch_array to find what the array key is for SUM(points) you'll know before hand.
to do this use AS. ie
SELECT SUM(points) AS `summary` FROM result
#Memor-X answer is good but I have a feeling that you have missed at least one step in the normal flow of event when querying a database in PHP using mysqli_
// create a query as a text string
$pointsummary = "SELECT SUM(points) as `tot_points`
FROM result
WHERE id=$val";
// issue the query to the MySQL Server for execution
// this should create a result set as long as the query is valid
$result = mysqli_query($con, $pointsummary);
// Check that the query had no errors
if ( ! $result ) {
echo mysqli_error($con);
exit;
}
// request the first row from the result set
// as we know this query will only return one row
// we dont need to do this in a loop
$row = mysqli_fetch_assoc($result);
echo $row['tot_points'];
I have this:
$query = "SELECT time FROM table_schedule GROUP BY time ORDER BY count(*) desc LIMIT 1 ";
then I stored it in:
$result = mysql_query($query);
I will output the value by <?php echo $result ?> but I am always getting this value Resource id #20.
I am new in sql so I hope someone can help me with my problem.
You are trying to show the result in a unproper way. In PHP mysql_query() will execute a query. In order to get the result, you should use
$result = mysql_query($query);
$row=mysql_fetch_array($result); // fetches the result of the query and stores in an associative array
$time=$row['time']; // get the result from the associate array with field name as the index
You can also use ,
$row=mysql_fetch_row($result);
$time=$row[1];
which will fetch the result as an enumerated array where you want to display each fields with the column number starting from 0.
For reference
if($sql = $db->query("Count (*) FROM post_items")){
echo mysqli_num_rows($sql);
}
what's wrong with my code? is this the correct way to echo the total of row in a table?
Your query should be
select count(*) FROM post_items
but echoing
mysqli_num_rows($sql);
will always give 1 as the ans, because count function returns only one row.
Rather fetch the details and show the count
$row = $sql->fetch_row();
echo $row[0];
No it is not; you will always get a return value of 1.
Why? Because you are in essence double-counting. The query executes a COUNT aggregate on the table returning a single row with the counted number. mysqli_num_rows is then counting the number of rows in this result set - the single row - and returns 1.
Try, the following line instead, which should fetch the first (only) column returned of the first (only) row in the result set.
echo $sql->fetch_row()[0]
Note you're also missing a SELECT keyword in your SQL statement.
It should be
if($sql = $db->query("select count(*) FROM post_items")){
echo mysqli_num_rows($sql);
}
I have two different functions:
function user_count(){
global $db;
$query = mysqli_query($db,"SELECT COUNT(user_id) FROM users");
if($result = $query){
$user_count = mysqli_num_rows($result);
mysqli_free_result($result);
return $user_count;
}
}
In this function, I query the database to tell me how many users there are, and in PHP I use user_count(). The result of this function is 1. Which is correct, because I only have only 1 users in the database at the moment.
However when I use the same code for a different function such as:
function user_exists($username){
global $db;
sanitize($username);
$query = mysqli_query($db,"SELECT COUNT(user_id) FROM users WHERE username=".$username) or die ("Doesn't work");
if($result = $query){
$user_exists = mysqli_num_rows($result);
mysqli_free_result($result);
return $user_exists;
}
}
Not to mention I have also tried to comment out the sanitize($username). But even with it commented out I still am getting an error.
And I use the function user_exists("superadmin"), I get the error "Doesn't work". I am wondering what am I doing wrong in the second function where the first function would return the number of rows, where as second function would return an error.
I know for certain that:
Database is connecting
String sanitization is working
User does exists on the database
If would much appreciated if you reply using the procedural style.
To paraphrase a wise man, "This is not the count you are looking for"
mysqli_num_rows will return the number of rows in the result set which, in this case, will always be 1.
To get the actual count, you will have to use $row=mysqli_fetch_row($result) and then the count you want is in $row[0];
Also, you're not creating your query properly - the query should have single quote marks around the variable. Even better, look at using prepared statements as they will take care of all the escaping and quoting for you
You're asking for the number of user_ids in the table users, so the MySQL server will return something like this:
mysql> SELECT COUNT(user_id) FROM users;
+----------+
| count(*) |
+----------+
| 36 |
+----------+
1 row in set (0.00 sec)
Then, you're using mysqli_num_rows which checks the result of the query to see how many rows were returned. But, as you can see, there's "1 row in set" - so you're getting back the number of rows in the result of the query, not the number of user_ids.
What you want to do is something like this:
$row = mysqli_fetch_row($result);
$num_user_ids = $row[0];
Because $row[0] contains the first field in the row, which is 36 in my example.
As for the second part, you'll want to bind parameters, like this:
$stmt = $mysqli->prepare("SELECT COUNT(user_id) FROM users WHERE username = ?");
$stmt->bind_param('s', $username);
The s means that you're replacing the ? in the first row above with a string, which is given in the second argument.
You could also do what you do, but you'll have to surround $username with single quotes, because the query won't do it for you.
You are only getting one row from mysqli_num_rows in the first function because there is only one row in the result set (the row with the COUNT value in it). If you want to get the value you need to actually read the result set. Alternatively you could not use the COUNT function in the first case and then use mysqli_num_rows.
In the second function, my guess is that you need to add single quotes around the username value you are searching for. You should look at your actual errors returned from the query though and work from that.