$result=mysql_query(" UPDATE xxxxxx_users SET User_Password='$Password' WHERE FstName='$First' AND LstName='$Last'",$db) or die ("Password update successful!");
echo "Update failed, unknown user";
This correctly updates the db when the first and last names match and the db is not affected when they don't. My only issue is I always display the Update failed, unknown user message. what did I do wrong? Thanks.
The mysql_query function returns true when an SQL query is successful:
For other type of SQL statements,
INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success
or FALSE on error.
Your code is assuming that the query returns the number of rows effected. Use the mysql_affected_rows function for this purpose:
$result=mysql_query(" UPDATE xxxxxx_users SET User_Password='$Password' WHERE FstName='$First' AND LstName='$Last'",$db)
if (mysql_affected_rows() > 0)
die ("Password update successful!");
else
echo "Update failed, unknown user";
You probably need to do this the other way round...
$result=mysql_query(" UPDATE xxxxxx_users SET User_Password='$Password' WHERE FstName='$First' AND LstName='$Last'",$db)
or die ("Update failed, unknown user");
echo "Password update successful!";
If the first part (mysql_query) evaluates to true, there is no need to evaluate the second or part (die). You can use and instead.
And, please, read about SQL Injections.
A suggestion to your coding style:
Something like this:
if ($result)
...success
else
...fail
is much more readable.
Related
<?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");
}
I am trying to get the number of rows affected in a simple mysql update query. However, when I run this code below, PHP's mysql_affected_rows() always equals 0. No matter if foo=1 already (in which case the function should correctly return 0, since no rows were changed), or if foo currently equals some other integer (in which case the function should return 1).
$updateQuery = "UPDATE myTable SET foo=1 WHERE bar=2";
mysql_query($updateQuery);
if (mysql_affected_rows() > 0) {
echo "affected!";
}
else {
echo "not affected"; // always prints not affected
}
The UPDATE statement itself works. The INT gets changed in my database. I have also double-checked that the database connection isn't being closed beforehand or anything funky. Keep in mind, mysql_affected_rows doesn't necessarily require you to pass a connection link identifier, though I've tried that too.
Details on the function: mysql_affected_rows
Any ideas?
Newer versions of MySQL are clever enough to see if modification is done or not. Lets say you fired up an UPDATE Statement:
UPDATE tb_Employee_Stats SET lazy = 1 WHERE ep_id = 1234
Lets say if the Column's Value is already 1; then no update process occurs thus mysql_affected_rows() will return 0; else if Column lazy had some other value rather than 1, then 1 is returned. There is no other possibilities except for human errors.
The following notes will be helpful for you,
mysql_affected_rows() returns
+0: a row wasn't updated or inserted (likely because the row already existed,
but no field values were actually changed during the UPDATE).
+1: a row was inserted
+2: a row was updated
-1: in case of error.
mysqli affected rows developer notes
Have you tried using the MySQL function ROW_COUNT directly?
mysql_query('UPDATE myTable SET foo = 1 WHERE bar = 2');
if(mysql_result(mysql_query('SELECT ROW_COUNT()'), 0, 0)) {
print "updated";
}
else {
print "no updates made";
}
More information on the use of ROW_COUNT and the other MySQL information functions is at: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_row-count
mysqli_affected_rows requires you to pass the reference to your database connection as the only parameter, instead of the reference to your mysqli query. eg.
$dbref=mysqli_connect("dbserver","dbusername","dbpassword","dbname");
$updateQuery = mysqli_query($dbref,"UPDATE myTable SET foo=1 WHERE bar=2");
echo mysqli_affected_rows($dbref);
NOT
echo mysqli_affected_rows($updateQuery);
Try connecting like this:
$connection = mysql_connect(...,...,...);
and then call like this
if(mysql_affected_rows($connection) > 0)
echo "affected";
} else { ...
I think you need to try something else in update then foo=1. Put something totaly different then you wil see is it updating or not without if loop. then if it does, your if loop should work.
You work this?
$timestamp=mktime();
$updateQuery = "UPDATE myTable SET foo=1, timestamp={$timestamp} WHERE bar=2";
mysql_query($updateQuery);
$updateQuery = "SELECT COUNT(*) FROM myTable WHERE timestamp={$timestamp}";
$res=mysql_query($updateQuery);
$row=mysql_fetch_row($res);
if ($row[0]>0) {
echo "affected!";
}
else {
echo "not affected";
}
This is because mySql is checking whether the field made any change or not,
To over come this, I created a new TINY field 'DIDUPDATE' in the table.
added this to your query 'DIDUPDATE=DIDUPDATE*-1'
it looks like.
$updateQuery = "UPDATE myTable SET foo=1, DIDUPDATE=DIDUPDATE*-1 WHERE bar=2";
mysql_query($updateQuery);
if (mysql_affected_rows() > 0)
{
echo "affected!";
}
else
{
echo "not affected";
}
it works fine!!!
Was My Tought !
I was just about to tell to check if the function's being called many times !
Just a little advice:
try using isset() & POST / GET or something like that;
if ( isset( $_POST['Update'] == 'yes' ) ) :
// your code goes here ...
endif;
Hope it was clear and useful, Ciao :)
Hey hello everyone,i have a slight problem with my small delete function in php,below is my code
function delete()
{
$q = "DELETE FROM example WHERE **author='frank'";**
$r = mysql_query($q) or die (mysql_error());
if($r)
{
echo 'done';
}
else
{
echo 'not done';
}
}
Now i don't have any author with that name Frank so that means it is not deleting anything
from the database but still shows that done msg
I am not sure why????can anyone please help me
That's because there was no error, delete did execute, it just didn't do anything. You want:
if(mysql_affected_rows() > 0) {
echo "done";
}
There is no error in your query. It will complete successfully. If you read the documentation you will see:
"For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error."
As there is no error in your query it will return TRUE even though nothing has actually been deleted. Deleting nothing is not considered an error.
A delete query will always succeed, even if no rows are actually deleted. If you want to determine how many rows were affected by an insert, update or delete operation, use mysql_affected_rows()
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();
?>