I need to break an if statement somehow. Here is the code
public function userData($data) {
//checks if user is in the database
if (self::checkUserExist($data)==false) {
$userInfo = array();
$userInfo['id'] = (isset($data->id)) ? $data->id : break;
$userInfo['email'] = (isset($data->email)) ? $data->email : break;
$this->conn->insert($userInfo, $Table); // inserts data!
}
}
The break doesn't work here. I need to return some kind of error. I could say that the input data is invalid or something, the main point for this is to avoid data insertion in database if the data is invalid.
Use:
public function userData($data) {
if (self::checkUserExist($data)==false && isset($data->id) && isset($data->email)) { //checks if user is in the database
$userInfo = array('id' => $data->id,'email' => $data->email);
$this->conn->insert($userInfo, $Table); // inserts data!
}
}
Or return
or to make it even worse: goto
.
break breaks while/for loops. use return false
You cannot break the if
; If that is your whole code, you may use the return
statement; Also, you should not combine it with a ternary operator
(? :
') as that will cause a parse error:
PHP Parse error: syntax error, unexpected 'break' (T_BREAK)
PHP Parse error: syntax error, unexpected return (T_RETURN)
Another approach, would be to use goto (I can hear the bashing coming, but take a look at this question: Examples of good gotos in c or c++)
Also there are obscure hacks like do { ... } while(0);
that allows you to use break
, but don't use that - this is stupid :)
Try below code:
public function userData($data) {
if (self::checkUserExist($data)==false) { //checks if user is in the database
$userInfo = array();
$userInfo['id'] = (isset($data->id)) ? $data->id : break;
$userInfo['email'] = (isset($data->email)) ? $data->email : break;
if(!$this->conn->insert($userInfo, $Table)){
$message = 'Error';
}else{
$message = 'Success';
}
}
}