I have the variable
$sql1 .= "Brukertype";
Which gets information set from an already-filled textbox. It can either have the value Administrator or the value Iskjører.
What is the best way to change these values before inserting them into SQL?
The Administrator value should get changed to the value 1 and Iskjører gets changed to the value 2.
I can't use a select function (dropdown list) on the question because it needs to be enabled/disabled on my command.
This is a reasonable place to use a switch statement. You want a 'marshaling' function, like this:
function marshal_input($input) {
$result = 0;
switch ($input){
case 'Administrator':
$result = 1;
break;
case 'Iskjører':
$result = 2;
break;
case 'SomethingYouHaventThoughtOfYet':
$result = 3;
break;
default:
$result = 0;
break;
}
}
However, the implementation of the marshaling function can be almost anything:
function marshal_input($input) {
$options = array("Administrator" => 1, "Iskjører" =>2);
return $options[$input];
}
The point is that you need some code that maps from the human-readable form to the numerical representation the db needs. Then you just call it like so:
$sql_version = marshal_input($sql1);//Doesn't overwrite the variable
//...or...
$sql1 = marshal_input($sql1);//Note this overwrites the variable.
Since you have stated:
It can eighter have the value "Administrator" or the value "Iskjører"...
we only check whether the value is 'Administrator' or not.
Try this:
$val = 'Administrator'; // user input variable
$sql_val = ($val == 'Administrator') ? 1 : 2;
If value is 'Administrator' set $sql_val to 1, else set $sql_val to 2
Related
I've written a switch which needs to match any combinations in the predefined array but now its matching only if all the combination from the given array is succeeded. But I want to match any combination from the array.
example : if my combination consists only 'man','cisman' then also my combination needs to succeed and needs to return $result = "male.png";. But if any item otherthan the given combination needs to rejected and needs to return default case.
Working demo
$menCombo = ['man','cisman','transmasculine','transman'];
$womanCombo = ['woman','ciswoman','transfeminine','transwoman'];
switch($genderdetail) {
case count(array_intersect($menCombo, $genderdetail)) === count(($menCombo)):
case "man":
case "cisman":
case "transman":
case "transmasculine":{
$result = "male.png";
break;
}
case count(array_intersect($womanCombo, $genderdetail)) === count(($womanCombo)):
case "woman":
case "ciswoman":
case "transfeminine":
case "transwoman":{
$result = "female.png";
break;
}
default: {
$result = "others.png";
break;
}
}
As mentioned in the comments, if $genderdetail isn't an array, you make it one. Now, if array difference of 2 arrays returns empty, it sure has to belong to the haystack array in comparison.
<?php
$genderdetail = ['man','cisman'];
$menCombo = ['man','cisman','transmasculine','transman'];
$womanCombo = ['woman','ciswoman','transfeminine','transwoman'];
$result = 'others.png';
if(!is_array($genderdetail)){
$genderdetail = [ $genderdetail ];
}
if(empty(array_diff($genderdetail, $menCombo))){
$result = 'male.png';
}else if(empty(array_diff($genderdetail, $womanCombo))){
$result = 'female.png';
}
echo $result;
What about changing the count condition to
case count(array_intersect($menCombo, $genderdetail)) === count(($genderdetail)):
you count the array mayches and not the long array of poszibilities. Same for the female count.
So basically i'm trying to create a complex timetable and i have these two methods that each perform a different check function for me:
Checks if i have a unique array
function tutorAllot($array,$check,$period){
//check for clashes and return non colliding allotment
shuffle($array);
$rKey = array_rand($array);
if(array_key_exists($array[$rKey]['teacher_id'], $check[$period])) {
return $this->tutorAllot($array,$check,$period);
}
return $tutor = array($array[$rKey]['teacher_id'] => $array[$rKey]['subject_code']);
}
checks that each subject does not appear more than twice in a day
function checkDayLimit($data,$check){
//check double day limit
$max = 2;
$value = array_values($check);
$tempCount = array_count_values($data);
return (array_key_exists($value[0], $tempCount) && $tempCount[$value[0]] <= $max) ? true : false;
}
I'm calling the functions from a loop and populating timetable array only if all conditions area satisfied:
$outerClass = array();
foreach ($value as $ky => $val) {
$innerClass = array(); $dayCount = array();
foreach ($periods[0] as $period => $periodData) {
$innerClass[$period] = array();
if(!($periodData == 'break')){
$return = $this->Schedule->tutorAllot($val,$clashCheck,$period);
if($return){
//check that the returned allocation hasnt reached day limit
if($this->Schedule->checkDayLimit($dayCount,$return)){
$innerClass[$period] += $return;
$clashCheck[$period] += $return;
}else{
}
}
}else{
$innerClass[$period] = '';
}
}
//debug($innerClass);
$outerClass[$ky] = $innerClass;
}
My requirements
If the checkDayLimit returns false , i want to go back and call tutorAllot function again to pick a new value.
I need to do this without breaking the loop.
I was thinking maybe i could use goto statement but only when am out of options.
Is there a way i can achieve this without using goto statement.
PHP v5.5.3 Ubuntu
Your architecture seems overly complex. Instead of
pick at random >> check limit >> if at limit, go to re-pick...
Why not incorporate both checks into a single function? It would
Filter out data that is not eligible to be picked, and return an array of legitimate choices
Pick at random from the safe choices and return the pick
addendum 1
I don't think there is any need for recursion. I would use array_filter to pass the data through a function that returns true for eligible members and false for the rest. I would then take the result of array_map and make a random selection from it
foreach ($_POST as $nazwa_checkboxa=>$id) {
$s = "SELECT uprawnienie FROM user WHERE Id_user=".$id;
$helpdesk = 0;
if ($s == 0) {
$helpdesk = 1;
}
$z = "UPDATE user SET uprawnienie = ".$helpdesk." WHERE Id_user=".$id;
$wynik = $polaczenie->query($z);
$zmienione++;
}
Column uprawnienie return 0 = normal user and 1 = administrator
The update always set value to 1 and I can change user to administrator (0 to 1) but it doesnąt work 1 to 0
Actually, you can do it using one query, e.g.:
update user
set uprawnienie = (SELECT if(uprawnienie=1,0,1) FROM user WHERE Id_user = '<id>')
where Id_user = '<id>'
Looks like you haven't actually run the query() for $s. Therefore, the if ($s==0) is not checking the query results, but rather whether "SELECT..."==0. Per the PHP docs, "Strings will most likely return 0" when cast to integers for such comparisons.
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
}
I have an MySQL syntax where I return some data for a user. Is any better way of executing the following query, where I just want to know if there is data for user X in category y.
$search_sql = " SELECT id FROM sn_news WHERE id_category = $category AND id_client = $client ";
$search_query = mysql_query($search_sql);
$search_query_result = mysql_fetch_assoc($search_query);
if($search_query_result)
{
$search_result = TRUE;
}
else
{
$search_result = FALSE;
}
I just what to get a TRUE if there is data for my query, or a FALSE if not, to later use that result in a $.post() to know what to print out and what to remove.
Note: I haven't tried the code, but I guess it works
$search_sql = " SELECT id FROM sn_news WHERE id_category = $category AND id_client = $client ";
if ($search_query = mysql_query($search_sql))
{
$search_result=(mysql_num_rows($search_query) ? TRUE : FALSE);
}
or, to actually retrieve the data too
$search_sql = " SELECT id FROM sn_news WHERE id_category = $category AND id_client = $client ";
$search_query_result=array(); // initialise empty return array
if ($search_query = mysql_query($search_sql))
{
switch mysql_num_rows($search_query)
{
case 0:
$search_result=FALSE;
break;
default: // got something
$search_result=TRUE;
while ($row=mysql_fetch_assoc($search_query)
{
$search_query_result[]=$row;
}
break;
}
}
This checks the number of returned rows and sets the variable accordingly using the useful little side effect that a integer value of 0 is equivalent to FALSE.
I would also add some checks to see if the query worked in the first place. It's always useful to check in case you've got a syntax error in your SQL or there's a problem with the server itself (see my code)
mysql_fetch_assoc() returns FALSE when there is no row to fetch. You can check the return value like this:
$search_result = mysql_fetch_assoc($search_query) !== FALSE;
Tell you what, this is essentially the same as what you are doing in your original code.