Jump to content

Question About Mysql Update Query


eldan88

Recommended Posts

Hey,

 

I have wrote a simple mysql update statment below. However when I enter a duplicate username and password, there obviously isn't any mysql_affected_rows. So how do create another condition that checks to see if there has been a duplicate?

 

Thanks

 

if(empty($errors))
{
$id= $_POST['id']
$username= $_POST['username'];
$password = $_POST['password'];

$query = "UPDATE tablename SET
username = '{$username}',
password = '{$password}'
WHERE id = '{$id}'";


$result_set = mysql_query($query,$connection);
if (mysql_affected_rows() == 1 ) {
// mysql_affected_rows is succesful
}// end of if condition for the mysql_affected rows
else {
echo "Username and Password Creation Failed" . "<br />";
echo mysql_error();
  } // End of else condition if mysql_affected_rows did not succeed
 } // End of if(empty($errors)) {

Link to comment
Share on other sites

$query = "UPDATE tablename t1 SET
t1.username = '{$username}',
t1.password = '{$password}'
WHERE t1.id = '{$id}' AND !EXISTS(
SELECT *
FROM tablename t2
WHERE t2.account = '{$account}' AND t2.id != '{$id}'
)"

 

This checks if there does not exist another row with that username that you want to set. But it does exclude the row you want to update, because that may be the same username.

Edited by Langstra
Link to comment
Share on other sites

$query = "UPDATE tablename t1 SET
t1.username = '{$username}',
t1.password = '{$password}'
WHERE t1.id = '{$id}' AND !EXISTS(
SELECT *
FROM tablename t2
WHERE t2.account = '{$account}' AND t2.id != '{$id}'
)"

 

This checks if there does not exist another row with that username that you want to set. But it does exclude the row you want to update, because that may be the same username.

 

Oh gotcha. That makes a whole lot of sense. Thank you!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.