Hello i am writing a module for inserting data in MySQL table. It is very easy but in my module i am receiving four mobile number. The first one is user's mobile no and other three are reference mobile number. User's mobile no is mandatory field but reference are not. this time i am checking each reference mobile no by using isset()
and empty()
function in PHP. but i have to write multiple if-else block. like
if(isset($_POST['mobileno_1']) && !empty($_POST['mobileno_1'])){
$mobileno1 = $_POST['mobileno_1'];
}else{
$mobileno1 = 0;
}
if(isset($_POST['mobileno_2']) && !empty($_POST['mobileno_2'])){
$mobileno2 = $_POST['mobileno_2'];
}else{
$mobileno2 = 0;
}
if(isset($_POST['mobileno_3']) && !empty($_POST['mobileno_3'])){
$mobileno3 = $_POST['mobileno_3'];
}else{
$mobileno3 = 0;
}
$sql = "INSERT INTO refferencemobile(mobileno, mobile1, mobile2, mobile3) VALUES($mobileno, $mobileno1, $mobileno2, $mobileno3)";
is there any optimized way to do this.so that it can reduce number of if-else block.
Something like this perhaps:
$mobileno3 = (isset($_POST['mobileno_3']) && !empty($_POST['mobileno_3']))
? $_POST['mobileno_3']
: 0;
You can even turn it into a function.
function GetMobileNo($mobileNo)
{
return (isset($mobileNo) && !empty($mobileNo)) ? $mobileNo : 0;
}
$mobileno3 = GetMobileNo($_POST['mobileno_3']);
empty
already checks if a variable isset so this simplifies the if statments.
You can also use ternary conditions. These look like:
$someCondition ? 'a' : 'b';
Which will evaluate to 'a' if $someCondition
is true and 'b' otherwise.
Putting this together we can get:
//If $_POST['mobileno_1'] isset and has a non false value use $_POST['mobileno_1']
$mobileno1 = !empty($_POST['mobileno_1']) ? $_POST['mobileno_1'] : 0;
$mobileno2 = !empty($_POST['mobileno_2']) ? $_POST['mobileno_2'] : 0;
$mobileno3 = !empty($_POST['mobileno_3']) ? $_POST['mobileno_3'] : 0;
As user1281385 pointed out in the comments you are using posted values directly in a query. You need to make sure these are sanitised or, better yet, use prepared statements.
sample/test code here http://codepad.org/5ybUcmcN
$mobileno1 = getMobileNo($_POST['mobileno_1']);
$mobileno2 = getMobileNo($_POST['mobileno_2']);
$mobileno3 = getMobileNo($_POST['mobileno_3']);
/* example
$mobileno1 = getMobileNo('abc');
$mobileno2 = getMobileNo('111');
$mobileno3 = getMobileNo('');
*/
$sql = "INSERT INTO refferencemobile(mobileno, mobile1, mobile2, mobile3) VALUES($mobileno, $mobileno1, $mobileno2, $mobileno3)";
function getMobileNo($mobileNo){
// check for if its set or not OR empty OR not an integer
if(!isset($mobileNo) || empty($mobileNo) || !is_int($mobileNo)){
return 0;
}
return $mobileNo; // valid number
}