<?php
$uname=$_POST['uname'];
$pwd=$_POST['pwd'];
$result="";
echo($uname.'</br>');
echo($pwd);
$con=mysql_connect("localhost","root","");
mysql_select_db("user_login_test",$con);
$sql="SELECT * FROM userlogin WHERE username='".$uname."'";
if($result=mysql_query($sql))
{
echo($result);
echo("Extracted<br>");
}
else
{
echo("NOT Extracted");
}
while($row = mysql_fetch_array($result))
{
echo $row['username'] . " " . $row['password'];
echo "<br />";
}
?>
I am doing above code for extracting values. If Username matches it show the value but if I give wrong input text it also shows "Extracted" with no value why? Please help me???
As explained in the PHP manual entry for the mysql_query() function:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
Your $result variable therefore holds a MySQL resource irrespective of whether there is a match on the username column: testing such a resource using if will always evaluate to TRUE (unless the query itself threw an error).
The manual goes on to explain:
The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.
Use mysql_num_rows() to find out how many rows were returned for a SELECT statement or mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.
In your case, you could test using mysql_num_rows() to determine whether any records were returned by the query (i.e. whether the WHERE condition was satisfied).
You have write wrong logic for extract username.
I have modify your code check it.
$sql="SELECT * FROM userlogin WHERE username='".$uname."'";
$result=mysql_query($sql)
if(mysql_num_rows($result)>0)
{
echo("Extracted<br>");
}
else
{
echo("NOT Extracted");
}
Related
How can I call a MySQL function and store the return value in a PHP variable?
I have tried this:
$ret = mysqli_query($connection, "call FP_USER_EXISTS('$emailid')");
if ($ret==1)
{
echo "User already exists \n";
}
else
{
echo 'Inserted successfully';
}
Unfortunately, this does not provide the boolean return value that I expect. I want it to retrieve whether the user exists, but it's returning the success/fail status of the mysqli_query. The docs indicate this is TRUE for this type of query.
How do I get the return code from the actual MySQL function?
The MySQLi Stored Procedures documentation gives some specific guidance on calling stored procedures with MySQLi:
Stored procedures can return result sets. Result sets returned from a stored procedure cannot be fetched correctly using mysqli_query(). The mysqli_query() function combines statement execution and fetching the first result set into a buffered result set, if any. However, there are additional stored procedure result sets hidden from the user which cause mysqli_query() to fail returning the user expected result sets.
Result sets returned from a stored procedure are fetched using mysqli_real_query() or mysqli_multi_query(). Both functions allow fetching any number of result sets returned by a statement, such as CALL. Failing to fetch all result sets returned by a stored procedure causes an error.
Given this information, it's better to use the mysqli_real_query function to retrieve the results that you need. Use this code, instead:
$ret=mysqli_real_query($connection,"call FP_USER_EXISTS('$emailid')");
if($ret==1)
{
echo "Error: " . mysqli_error();
}
else
{
if ($row = mysqli_fetch_array($result)) {
if ($row[0]) {
echo 'Inserted successfully';
} else {
echo "User already exits";
}
} else {
echo "No result returned";
}
}
This code assumes that the stored procedure returns TRUE if a new record is inserted, or FALSE if it is not. If this is not the case (because these details are not present in the question), you will have to adjust accordingly. The additional error handling is used to make sure that the statement itself was successfully executed, and that at least one result row was returned.
Here is a simple scenario I am contemplating. I have a query that is executed on a MySQL database from PHP. I would like to check if any data was returned from the query. However, in order to perform that check, it pulls out one of the rows of returned data.
Look at this example, and its comments:
$booksGrabber = ("SELECT * FROM table");
if (!$booksGrabber) {
//Query failed, perhaps a syntax error
exit;
}
if (!mysql_result($booksGrabber, 0)) {
//No data was returned :(
exit;
}
while ($book = mysql_fetch_assoc($booksGrabber)) {
//mysql_result() stole the first row of returned data
//So if I was expecting the loop to display 4 results,
//I only get 3...
}
How can I check if data was returned from the database without running two queries (one to check, the other to display all of the data) or having one of the rows stolen?
Use mysql_num_rows. It was as simple as it looked.
EDIT: If you want more complicated, add mysql_data_seek($booksGrabber,0).
Simple: mysql_query() function that runs the query will return false on error and then you can use mysql_num_rows() for the count. So you can do something like:
$result = mysql_query('SELECT * FROM table');
if (!$result) {
print('Invalid query: ' . mysql_error());
} elseif (mysql_num_rows() == 0) {
print("no results");
} else {
// You can use safely data from the query :)
}
I want to use PHP to find out if no matches are found. I tried the following, but "is_resource()" always returns true.
$result = mysql_query('...');
if(is_resource($result)){
// Results are found
}
mysql_num_rows() will do the trick.
if (mysql_num_rows($result)>0) {
//Results are found
}
http://php.net/manual/en/function.mysql-num-rows.php
So $result will always be a resource as long as you have proper access to the database. And mysql_num_rows() assumes that the query itself ran successfully. I'd say try something like this:
if($result === FALSE) // Query failed due to not having proper permissions on the table
die('Invalid query: ' . mysql_error());
else if(mysql_num_rows($result) >0)) // We have more than 1 row returned which means we have data
// INPUT RESULTS PROCESSING HERE
else // No rows were returned therefore there were no matches
echo 'No rows returned';
Hope that helps a little =)
Look here for more information if you need: http://www.php.net/manual/en/function.mysql-query.php
This is what you want: mysql_num_rows()
If the query fails it mysql_query will return false so you can check your code like this:
if ( $stmt = mysql_query("...") )
{
// Do some things
}
else
{
// Do some other things
}
Or you could use mysql_num_rows like the people above have stated.
But you should really be looking into MySQLi it's a built in database class. Learn it and use it. Your life will be so much easier.
Ok so the problem is... i m a newbie and i m trying to understand what is happening.Im sending through an html form this data(name,email) using POST in a database.I understand the logic behind it all but what basically happens is that everytime I enter a name,any name,it echoes the else statement:"there is already a user with that name". and it sends back the first name in the database.when there s nothing,it sends nothing. So here's the chunk:
$query= "SELECT* from users where username='".$_POST['name']."'";
$result = mysql_query($query);
if (!$result){
$query = "INSERT into users (username, email, password) values
('".$_POST["name"]."', '".$_POST["email"]."',
'".$passwords[0]."')";
$result = mysql_query($query);
if ($result){
echo "It's entered!";
} else {
echo "There's been a problem: ".mysql_error();
}
} else {
echo "There is already a user with that name: <br />";
$sqlAll = "select * from users";
$resultsAll = mysql_query($sqlAll);
$row = mysql_fetch_array($resultsAll);
while ($row) {
echo $row["username"]." -- ".$row["email"]."<br />";
$row = mysql_fetch_array($result);
You may want to check mysql_num_rows() rather than checking for !$result, I think that if the query is sucsesfull you'll get a resource back, even though it contains zero rows.
You may also want to read up on: http://php.net/manual/en/security.database.sql-injection.php
ESCAPEEEEE
Firstly, you need to learn about escaping.
Have you never heard of little Johnny DROP TABLES?
http://xkcd.com/327/
Serious business
The reason why it always returns, is because the response in $result is actually a resource data type. And that will always when cast as a boolean be true. (And since your query shouldn't fail).
You should fetch the result. For example. (This isn't the best way, but it is a way to do it).
mysql_fetch_row(result)
Per the manual, mysql_query will return false when there is an error - "For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error."
see no violation in your code. first mysql_query executes with no error and always returns true. try to test returned rows count like this:
if (mysql_num_rows($result) == 0) {
//insert record
} else {
// show alreay exists
}
First of all, you are testing for:
if (!$result)
which will evaluate to true only if the query fails.
You should also sanitize all input before using it in SQL queries.
Just learning PHP and I'm having some trouble understanding mysql_query. My understanding is that mysql_query is supposed to return FALSE if the record is not found. However, it seems that it always returns true because "FOUND!" is always the result:
$q = "SELECT * FROM users WHERE username = 'doesnotexist'";
$r = mysql_query($q);
if (!$q) {
echo "<p>NOT FOUND!</p>";
} else {
echo "<p>FOUND!</p>";
}
mysql_close();
Thanks in advance for any light you can shed.
mysql_query returns false if there is an error, not if there are no results found. From the documentation:
For SELECT, SHOW, DESCRIBE, EXPLAIN
and other statements returning
resultset, mysql_query() returns a
resource on success, or FALSE on
error.
For other type of SQL statements,
INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success
or FALSE on error.
mysql_query() will also fail and
return FALSE if the user does not have
permission to access the table(s)
referenced by the query.
If you want to check to see if there were results returned by your query, use mysql_num_rows(). See the documentation:
Use mysql_num_rows() to find out how
many rows were returned for a SELECT
statement or mysql_affected_rows() to
find out how many rows were affected
by a DELETE, INSERT, REPLACE, or
UPDATE statement.
You are checking the '$q' variable (your sql statement) instead of the '$r' variable (the mysql result)
if (empty($r)) {
echo "<p>NOT FOUND!</p>";
} else {
echo "<p>FOUND!</p>";
}
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Ok i have worked out the answer to this.
This is the version for updating a database that tells you if a record was valid.
$updatequery = "update `mydb` set `userid` = '$arr[0]', `name` = '$arr[1]' where `age` = '$arr[2]'";
$updatequeryresult= mysql_query($updatequery);
$howmanyupdatedrecords = mysql_affected_rows();
if ($howmanyupdatedrecords == 0) {
echo("The update didn't update any records as no one matched an age of " .$arr[2]");
}
This will iterate through the DB updating all people with the specified age, if the age does not exist in the DB a message will be displayed showing you the age that does not exist. Also something to note, even if the mysql query matches a record, it won't update the record if the data already matches what it is being updated to. This causes the script to return "no one matched an age" even though there are people who did match. Can only attribute that to a bug in mysql. I told MySQL to update the information I don't see why it should take it upon itself to not bother doing as i told it. ;)
Your 'if (!$q)' should be 'if (!$r)' I think.
if that dosen't work, try this:
<?php
$q = "SELECT * FROM users WHERE username = 'doesnotexist'";
$r = mysql_query($q);
if (!mysql_num_rows($r) >= 1) {
echo "<p>NOT FOUND!</p>";
} else {
echo "<p>FOUND!</p>";
}
mysql_close();
?>