Cannnot fetch contact no. using where clause in php - php

echo $query = "SELECT user_id FROM login WHERE username = '8578896785'";
echo $result = $mysql_query($query);
cannot fetch contact number when use in php
I executed the same query on mysql and it gives results. The same query does not work in PHP.
The column is of varchar(200) datatype and contains data as string,alphanumeric as well as numbers

if u use numeric date to fetch then u have to use
SELECT user_id FROM login WHERE username = 123 withought ''
and when you try to fetch string data
SELECT user_id FROM login WHERE username = 'abc' with ''

you can't output a resource with the echo statement, you have to fetch the data in the result before you can output it.
$query = "SELECT user_id FROM login WHERE username = '8578896785' LIMIT 1";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
echo $row['user_id'];
1st Edit: removed unnecessary echo's
2nd Edit: adding a LIMIT 1 to your query, the username schould be just one time in the table ;)
3rd Edit: removed $ in front of a function (mysql_query())
4th Edit: fetching data from the ressource (as array, for other methods to fetch the data look into the php manuals)
5th Edit: output the userid

Related

Row Count outputting - in front of the number of rows in table

Good day,
i have the following code in php
$sellast2 = "SELECT id, staffid, password FROM staff WHERE staffid=$staffid";
$result4 = $pdo->prepare($sellast2);
$result4->execute();
$rowcount = $result4->rowCount();
echo $rowcount;
I am expecting that the row count would be one since this table only has one record in it.
The variable is outputting -1 and not 1 as expected.
What does the minus mean and why does it output a minus?
I am using Microsoft sql server management studio as the database.
$sellast2 = "SELECT id, staffid, password FROM staff WHERE staffid='$staffid'";
use your $staffid in single quotes like i did, then pass a valid staff id and get your result

issue with SELECT COUNT(id)

I've been using this command to retrieve the number of the fields which have same email address:
$query = $db->query("SELECT COUNT(`user_id`) FROM `users` WHERE `email`='$email'") or die($db-error);
There are 3 records in users table with the same email address. The problem is when I put * instead of COUNT(user_id) it returns correctly: $query->num_rows gives 3 but when I use COUNT(user_id) then $query->num_rows returns 1 all the time. how can I correct this or where is my problem?
When you use $query->num_rows with that query it will return 1 row only, because there is only one count to return.
The actual number of rows will be contained in that query. If you want the result as an object, or associative array give the count a name:
$query = $db->query("SELECT COUNT(`user_id`) AS total FROM `users` WHERE `email`='$email'") or die($db-error);
And in the returned query total should be 3, while $query->num_rows will still be 1. If you just want the value a quick way would be using $total = $query->fetchColumn();.
As others have said though, be careful with NULL user ids, because COUNT() will ignore them.
Emails have to be uinque in users table. Thus, you need no count at all.
You ought to use prepared statements.
You shouldn't post a code that will never run.
Here goes the only correct way to run such a query:
$sql = "SELECT * FROM `users` WHERE `email`=?";
$stm = $db->prepare($sql);
$stm->execute([$email]);
$user = $stm-fetch();
(the code was written due to erroneous tagging. For mysqli you will need another code, but guidelines remains the same.)
Something like this
$sql = "SELECT * FROM `users` WHERE `email`=?";
$stm = $db->prepare($sql);
$stm->bind_param('s',$email);
$stm->execute();
$res = $stm->get_result()
$user = $res->fetch_assoc();
in $user variable you will have either userdata you will need in the following code or false which means no user found. Thus $user can be used in if() statement all right without the need of any counts.
In case when you really need to count the rows, then you use this count() approach you tried. You can use a function from this answer for this:
$count = getVar("SELECT COUNT(1) FROM users WHERE salary > ?", $salary);
That's the correct behaviour: If you use the COUNT function, the result of your select query will be just one row with one column containing the number of data sets.
So, you can retrieve the number of users with the given E-mail address like this:
$query = $db->query("SELECT COUNT(`user_id`) FROM `users` WHERE `email`='$email'") or die($db-error);
$row = $query->fetch_row();
$count = $row[0];
Note that this is faster than querying all data using SELECT * and checking $query->num_rows because it does not need to actually fetch the data.

sqlite3 - efficient way to count rows returned from SELECT statement in PHP without using COUNT()

I'm an SQL noob and learning how to use PDO. I'm doing a course which introduces basic user login functions. In an example of a login page, they check the username/password against a MySQL database. I edited their code slightly to be able to simultaneously check whether the user/pass combo exists and also grab the user's first name:
$sql = sprintf("SELECT firstname FROM users WHERE username='%s' AND password='%s'",
mysql_real_escape_string($_POST["username"]),
mysql_real_escape_string($_POST["password"]));
// execute query
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1) {
$_SESSION["authenticated"] = true;
// get contents of "firstname" field from row 0 (our only row)
$firstname = mysql_result($result,0,"firstname");
if ($firstname != '')
$_SESSION["user"] = $firstname;
}
What I want to do is use SQLite instead and do the same thing. Searching around has only resulted in people saying you should use a SELECT COUNT(*) statement, but I don't want to have to use an extra query if it's possible. Since I'm SELECTing the firstname field, I should only get 1 row returned if the user exists and 0 if they don't. I want to be able to use that number to check if the login is correct.
So far I've got this:
$dsn = 'sqlite:../database/cs75.db';
$dbh = new PDO($dsn);
$sql = sprintf("SELECT firstname FROM users WHERE username='%s' AND password='%s'",
$_POST["username"],
$_POST["password"]);
// query the database and save the result in $result
$result = $dbh->query($sql);
// count number of rows
$rows = sqlite_num_rows($result);
if ($rows == 1) { ...
But this is returning Warning: sqlite_num_rows() expects parameter 1 to be resource, object given.
Is there a way I can do this efficiently like in MySQL, or do I have to use a second query?
EDIT:
I found this, not sure if it's the best way but it seems to work: How to get the number of rows grouped by column?
This code let me do it without the second query:
// query the database and save the result in $result
$result = $dbh->query($sql);
// count number of rows
$rows = $result->fetch(PDO::FETCH_NUM);
echo 'Found: ' . $rows[0];
$rows is an array so I can just count that to check if it's > 0.
Thanks to everyone who commented. I didn't know until now that there were 2 different approaches (procedural & object oriented) so that helped a lot.
Normally, you can use PDOStatement::rowCount(), however, SQLite v3 does not appear to provide rowcounts for queries.
You would need to seperately query the count(*), or create your own counting-query-function.
The documentation comments have an example of this
A bit late, but i tried this with SQLite3 successful:
$result = $db->query('SELECT * FROM table_xy');
$rows = $result->fetchAll();
echo count($rows);

How to pass mysql row count in a variable to android

Using php script to query the mysql database with no problem. However I'm unable to parse the result with JSON and send it back to android. I have no problem encoding/parsing arrays - is a single variable different? Is there a better way to send a row count back to android?
php code:
$result = mysql_query("SELECT * FROM logs WHERE uid = '$uid' AND tableid = '$tid'");
$num_rows = mysql_num_rows($result);
echo json_encode($num_rows);
You can just select the number of rows in your query.
SELECT COUNT(*) ...
I am not sure what you are asking, the above code will just output the number of rows, To make it accessible in android app, you have to make it as key value pair, So that you can access the row number using the key as given below,
$result = mysql_query("SELECT * FROM logs WHERE uid = '$uid' AND tableid = '$tid'");
$num_rows = mysql_num_rows($result);
$output = array("count" => $num_rows);
echo json_encode($output);
This will output {"count":123}

How to get the result of a select count(*) query in PHP?

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.

Categories