0

I am trying to make it so that a specific value can only be set once, by making it so that i can only be updated or set if it is equal to null. For some reason, the PHP still echoes success even when the value is equal to something like: "Steve". What am I doing wrong?

PHP:

<?php $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL"); //select a database to work with $selected = mysql_select_db("???????",$dbhandle) or die("Could not select examples"); if(empty($_POST['OrderID']) || empty($_POST['UserName'])){ echo 'Failed. Fill out all fields.'; } else{ $sql = mysql_query("SELECT * FROM orders WHERE order_id = '".$_POST['OrderID']."' AND LENGTH(accepter_name)= 0"); $row = mysql_fetch_row($sql); // get the single row. echo $row['accepter_name']; // display the value. if($row['accepter_name']==''){ $sql = mysql_query("UPDATE orders SET accepter_name= '".$_POST['UserName']."' WHERE order_id='".$_POST['OrderID']."'"); echo "Success"; } else{ echo "Failed"; } } mysql_close($dbhandle); ?> 

When i check on the database, the accepter name value is changed.

9
  • Edited the Code. Still doesnt work. Commented Sep 30, 2014 at 8:20
  • Still Updates even if it has a value. Commented Sep 30, 2014 at 8:32
  • Yes, thats what i want. But for some reason, it updates even if the value has something in it. Commented Sep 30, 2014 at 8:39
  • Tested several times. It inserts regardless. Commented Sep 30, 2014 at 8:46
  • make slqfiddle Commented Sep 30, 2014 at 8:48

2 Answers 2

1

You can use if( mysql_affected_rows($sql) == 1 ) instead of if($sql) because the sql is executed and it's returns no rows affected. So, if you check for affected rows it should return 1 when your sql updated at least one row in your table

Sign up to request clarification or add additional context in comments.

3 Comments

Using this method, it fails to insert anything regardless.
this is not answer. Comment below question.
@Prashant, you may not like this answer, but it is an answer. I appreciate you will have seen experienced members asking answerers to make non-answer comments as comments, but that does not apply in this case, IMO. I'd advise you only to make these comments when it obviously isn't an answer (e.g. seeking clarification, asking a related question) and in those cases you can flag it to moderator.
0

Why not use IS NULL in where clause to check accepter_name?

3 Comments

It still inserts regardless of whether is is empty or not.
this is not answer. Comment below question.
I can't. Not enough reputation points to comment on the question