if condition comes from a string variable - php

I am making a quiz online for my students and I have a variable
$no_of_questions = 7;
and based on that value I need to generate the condition of my IF statement
if ($row['q1'] === NULL OR $row['q2'] === NULL OR $row['q3'] === NULL OR ....)
That is php code so I can't echo and I can't put a string into IF and work as wanted. Any ideas on how to solve it?

You can simply achieve this with a for()-loop.
for($i = 1; $i <= $no_of_questions; $i++) {
if($row['q'.$i] === NULL) {
//do something if one question is NULL
}
}

From what i understand from your question. This will work.
$i=1;
if( $a['q'.$i] === NULL)

Related

How to break a for loop from inside of a fuction

i have the following code
function do_function($name, $value, $age){
$sql = mysql_fetch_array(mysql_query("INSERT into `table` Values('','$name','$value','$age')"));
if (!$sql) {
// basicly will return false on duplicate key
//do something to break the calling for_loop ?
//i`ve tried break(); and continue(); but this will break/skip just the
//function not the for loop
}
}
$presetnumber = 25;
for($x = 0; $x <= $presetnumber; $x++){
do_function($name[$x], $value[$x], $age[$x]);
//return something on duplicate key to break the for loop ???
}
so i wannt to be able to just skip the entire loop if there is a duplicate key not just the function?
How can i do this, i don`t seem to understand quite entirely why break(); or continue(); is not working.
Please note that this is just a sample code to give you an ideea what i am trying to achieve.
Just return TRUE or FALSE in your function and then you can do a simple check in your loop like this:
(Pseudo code):
function do_function($name, $value, $age) {
//your stuff
if(!$sql)
return TRUE;
return FALSE;
}
for($x = 0; $x <= $presetnumber; $x++){
if(do_function($name[$x], $value[$x], $age[$x])) //breaks the loop if you return TRUE
break;
}
break will not work outside of the for loop. It must be inside the loop to be activated. So you could add a function like:
for(foo; bar; baz) {
if (checkForBreak()) {break};
}
Also, if you're working in PHP then break is a statement, not a function. So it's break;, not break();.
I believe your SQL query is always returning TRUE. Replace this:
$sql = mysql_fetch_array(mysql_query("INSERT into `table` ... "));
With this:
$sql = mysql_query("INSERT into `table` Values('','$name','$value','$age')");
I would also suggest for you to start using mysqli rather than mysql since it is deprecated

check value for multiple array in loop

i have three array sure[],maybe[] and notify[] that are displaying in a loop like this:
sure[0] maybe[0] notify[0]
sure[1] maybe[1] notify[1]
sure[2] maybe[2] notify[2]
sure[3] maybe[3] notify[3]
And so on...
Now what I want that is in form post I get all arrays and there should be minimum one value of sure[0] or maybe[0] or notify[0] true or checked means horizontally`.
In this process will be same for all next rows and each row must contain minimum one true or checked value although can all selected or checked.
I am trying to solve this problem from past three days .
How can I do this please check it and give me idea.
thanks in advance
You can check whether at least one of the three is set by doing this:
$oneSet = $sure[0] || $maybe[0] || $notify[0];
If you want to do this in a loop, you can do something like this (assuming each list is equally long)
$oneSetInEach = true;
for( $i = 0 ; $i < count($sure) ; $i++ ) {
$thisSet = $sure[$i] || $maybe[$i] || $notify[$i]; // check if one is set here
$oneSetInEach = $oneSetInEach && $thisSet; // if all the previous ones are ok, and this is ok, we are still ok
}
// $oneSetInEach will now be true or false depending on whether each row has at least 1 element set.
If all array count() are same
<?php
$i = 0;
while ($i < count($sure)) {
if ((isset($sure[$i]) AND $sure[$i] == true) OR ( isset($maybe[$i]) AND $maybe[$i] == true) OR ( isset($notify[$i]) AND $notify[$i] == true)) {
// your code
}
$i++;
}
?>
Maybe:
$res = true;
for( $i=0 ; $i<count($sure) ; $i++ ) {
$res &= $sure[$i] || $maybe[$i] || $notify[$i];
}

Correct Method for setting/using a NULL value in PHP 'Greater than or equal' IF ELSE

i have a simple if else statement and wondered if theres a better way of writing the code than I have listed below, the $price_data and $api_price are normally set but in some cases could be null / empty values, so if there is a empty value I need to revert back to $old_price
// now double the price compare api price and current price use highest value
if ($price_data >= $api_price) {
$price_double = $price_data;
// If we encounter a null or empty value for $price_data use old price data
if ($price_double == null){
$price_double = $old_price;
}
} else {
$price_double = $api_price;
// If we encounter a null or empty value for $price_data use old price data
if ($price_double == null){
$price_double = $old_price;
}
}
$useprice = ($price_double * 2);
I think this will do what you want:
if ((floatval($price_data) === 0) || (floatval($api_price) === 0)):
$price_double = $old_price;
else:
$price_double = ($price_data >= $api_price)?$price_data:$api_price;
endif;

Optimized code for mysql insert query

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.
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.
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']);
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
}

PHP/MySQL Checking for null

$sql = 'SELECT * FROM `phpbb_profile_fields_data`';
$result = $db->sql_query($sql);
while ($row = $db->sql_fetchrow($result)) {
if ($row['pf_kp_em_no_bonethr'] == '1') {
echo " Was 1";
} else if ($row['pf_kp_em_no_bonethr'] == '2') {
echo "Was 2";
} else {
echo "Was Neither 1 or 2";
}
}
$db->sql_freeresult($result);
I am curios, In my example I am checking the field for either a value of 1 or 2 but how do I check it for a value of NULL. Would it be any of the following three:
if ($row['pf_kp_em_no_bonethr'] == '')
if ($row['pf_kp_em_no_bonethr'] == '-1')
if ($row['pf_kp_em_no_bonethr'] == 'NULL')
Normally I would just try it out but I am not at home and wont be for the foreseeable future it has been bugging me. I am pretty sure it's not the second but I have seen -1 used for a null value in other languages. So can someone verify how I would indeed check for a NULL value please.
if ($row['pf_kp_em_no_bonethr'] === NULL)
Something like this should work.
if (is_null($row['pf_kp_em_no_bonethr'])) {
echo "Is NULL";
}
MySQL will return NULL values to PHP as actual PHP NULL. In this situation, what you need is:
// Notice lack of quotes around NULL
// And use === to distinguish type properly between integer 0 and NULL
if ($row['pf_kp_em_no_bonethr'] === NULL)
However, it would be more appropriate to check it in the query if NULL values are what you need to work with in PHP.
$sql = 'SELECT * FROM `phpbb_profile_fields_data` WHERE pf_kp_em_no_bonethr IS NULL';
Or to find all three values:
$sql = 'SELECT * FROM `phpbb_profile_fields_data`
WHERE pf_kp_em_no_bonethr IS NULL
OR pf_kp_em_no_bonethr IN (1,2)
';
I'd recommend to be very carfull with this one: I have seen
<?php
$field=$row['fieldname'];
if ($field===null) {
//Do something
}
?>
fail intermittently, especially on windows. This is why I prefer
SELECT
IFNULL(fieldname,'some_safe_value') AS fieldname
...
FROM
...
and the resulting trivial null-check.
Use is_null or === NULL.
if(is_null($row['pf_kp_em_no_bonethr'])){
}
or
if($row['pf_kp_em_no_bonethr'] === NULL){
}

Categories