This is similar question to MySQL and PHP - insert NULL rather than empty string but I'm still encountering the problem.
I'm trying to create a function so that an empty string is inserted as a NULL into MySQL.
I create the function IsEmptyString:
function IsEmptyString($val){
if (trim($val) === ''){$val = "NULL";}
}
Before inserting the the variable, I escape it and then I call the function above. I've also tried $val = NULL;
What am I doing wrong? Also should I call the function before escaping?
You need to return $val at the end of the function:
function IsEmptyString($val){
if (trim($val) === ''){$val = "NULL";}
return $val;
}
You're not returning the value. This should work
function IsEmptyString($val){
if (trim($val) === ''){$val = "NULL";}
return $val;
}
Also you're assigning your variable to a string and not null.
This line $val = "NULL";
should be
$val = null;
Also see PHP's isset() and empty() functions.
alternativly, you can pass val as reference.
function IsEmptyString(&$val){
if (trim($val) === ''){$val = "NULL";}
}
however, be carefull not to send "'".$val."'" to the database;
Either you can return the result with return...
function IsEmptyString($val)
{
if (trim($val) === '')
return 'NULL';
else
return $val;
}
...or you have to pass the variable as reference (note the & before the $val)
function IsEmptyString(&$val)
{
if (trim($val) === '')
$val = 'NULL';
}
Looks like a good candidate for a ternary operator:
function valOrNull($val) {
return (trim($val) === '') ? NULL : $val;
}
Related
How to replace this :
if( $this->getInfo() ){
$value = $this->getInfo();
}else{
$value = $this->getAnotherInfo();
}
This would be nicer solution :
$value = $this->getInfo() ? $this->getInfo() : $this->getAnotherInfo();
But we repeat $this->getInfo().
Here is the fun:
$value = $this->getInfo() ? : $this->getAnotherInfo();
If it bothers you having to repeat the expression you could write a function that returns the first truthy value.
$value = which ($this->getInfo(), $this->getAnotherInfo());
function which () {
if (func_num_args()<1) return false;
foreach (func_get_args() as $s) if ($s) return $s;
return false;
}
A nasty option would be this:
if (!($value = $this->getInfo())) $value = $this->getOtherInfo();
If the assignment returns false assign the other value.
But aside from this looking disgusting, it is still repetitive, albeit in a different way.
As of PHP 5.3, you can leave out the middle part of the ternary operator and avoid the repetition:
$value = $this->getInfo() ? : $this->getOtherInfo();
Which does what you want.
In Python I can use "get" method to get value from an dictionary without error.
a = {1: "a", 2: "b"}
a[3] # error
a.get(3, "") # I got empty string.
So I search for a common/base function that do this:
function GetItem($Arr, $Key, $Default){
$res = '';
if (array_key_exists($Key, $Arr)) {
$res = $Arr[$Key];
} else {
$res = $Default;
}
return $res;
}
Have same function basicly in PHP as in Python?
Thanks:
dd
isset() is typically faster than array_key_exists(). The parameter $default is initialized to an empty string if omitted.
function getItem($array, $key, $default = "") {
return isset($array[$key]) ? $array[$key] : $default;
}
// Call as
$array = array("abc" => 123, "def" => 455);
echo getItem($array, "xyz", "not here");
// "not here"
However, if an array key exists but has a NULL value, isset() won't behave the way you expect, as it will treat the NULL as though it doesn't exist and return $default. If you expect NULLs in the array, you must use array_key_exists() instead.
function getItem($array, $key, $default = "") {
return array_key_exists($key, $array) ? $array[$key] : $default;
}
Not quite. This should behave the same.
function GetItem($Arr, $Key, $Default = ''){
if (array_key_exists($Key, $Arr)) {
$res = $Arr[$Key];
} else {
$res = $Default;
}
return $res;
}
The first line in your function is useless, as every code path results in $res being overwritten. The trick is to make the $Default parameter optional as above.
Keep in mind that using array_key_exists() can cause significant slowdowns, especially on large arrays. An alternative:
function GetItem($Arr, $Key, $Default = '') {
return isset($Arr[$Key]) ? $Arr[$Key] : $Default;
}
There is no base function to do that in my mind.
Your GetItem is a good way to do what you wanna do :)
Yes. or
function GetItem($Arr, $Key, $Default) {
return array_key_exists($Key, $Arr)
? $Arr[$Key]
: $Default;
}
php7 is out for a long time now so you can do
$Arr[$Key] ?? $default
I am learning php and read this example in this http://www.php.net/manual/en/language.types.boolean.php tutorial,
I want to understand what occur when assigning the return value of method to a variable, why it may change?? please see my questions in the code.
<?php
public function myMethod()
{
return 'test';
}
public function myOtherMethod()
{
return null;
}
if($val = $this->myMethod())
{
// $val might be 1 instead of the expected 'test'
** why it may returns 1??**
}
if( ($val = $this->myMethod()) )
{
// now $val should be 'test'
}
// or to check for false
if( !($val = $this->myMethod()) ) **what happens here????**
{
// this will not run since $val = 'test' and equates to true
}
// this is an easy way to assign default value only if a value is not returned:
if( !($val = $this->myOtherMethod()) ) **what happens here????**
{
$val = 'default'
}
?>
In this case:
if($val = $this->myMethod())
{
// $val might be 1 instead of the expected 'test'
}
I don't think that's true. $val should be 'test' here. Maybe in older versions of PHP there could have been a bug.
if(!($val = $this->myMethod()))
{
// this will not run since $val = 'test' and equates to true
}
Here myMethhod() is executed and returns 'test' which is assigned to $val. Then the result of that assignment is boolean negated. Since the string 'test' evaluates to true, !('test') evalutes to false and the if statement doesn't run.
if(!($val = $this->myOtherMethod()))
{
$val = 'default';
}
This is the opposite case. $val becomes null. And null evaluates to boolean false, so !(null) evaluates to true and the code in the block executes. So after this code runs $val contains 'default'; This poster is showing this as a way of assigning a default value to $val in the case that $this->myOtherMethod() fails to return anything useful.
why it may returns 1? It is not returning 1 but the actual value that is 'test' but since this value is assigned properly because this is not NULL, false or empty. the if statement evaluates to true.
// or to check for false
if( !($val = $this->myMethod()) ) **what happens here????**
{
// this will not run since $val = 'test' and equates to true
}
What is happening here? The if statement here will test if non NULL value has been assigned to $val i.e. $val is not null similar to if(!$val). Since its value is not NULL nor false The code inside if will not execute.
if( !($val = $this->myOtherMethod()) ) **what happens here????**
{
$val = 'default'
}
What is happening here? since the assignment to the $val inside if statement failed because function returned NULL, and since $val is NULL if statement evaluates true and code inside executes. It wouldn't execute if the function had returned other than NULL or false.
Sorry guys, but i think the previous answers are wrong. I'm not sure if this is a typo or a trick question, but with
if($val = $this->myMethod())
you're actually SETTING $val to whatever $this->myMethod() returns, so your if() statement always equals true here. if you want to compare it you would have to use
if($val == $this->myMethod())
Notice the '==' in here!
Try This:
public function myMethod()
{
return 'test';
}
public function myOtherMethod()
{
return null;
}
if($val = myMethod())
{
Do Something
}elseif ($val != myMethod()){
Do Something Else
}elseif ($val == myOtherMethod())
{
$val = 'default';
}
?>
I have a form that passes something like in a URL
?choice=selection+A&choice=selection+C
I'm collecting it in a form with something like (I remember that $_GET is any array)
$temp = $_GET["choice"];
print_r($temp);
I'm only getting the last instance "selection C". What am I missing
I am assuming 'choice' is some kind of multi-select or checkbox group? If so, change its name in your html to 'choice[]'. $_GET['choice'] will then be an array of the selections the user made.
If you don't intend to edit the HTML, this will allow you to do what you're looking to do; it will populate the $_REQUEST superglobal and overwrite its contents.
This assumes PHP Version 5.3, because it uses the Ternary Shortcut Operator. This can be removed.
$rawget = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : false;
$rawpost = file_get_contents('php://input') ?: false;
$target = $rawget;
$_REQUEST = array();
if ($target !== false) {
$pairs = explode('&',$rawget);
foreach($pairs as $pair) {
$p = strpos($pair,'=');
if ($p === false && !empty($pair)) {
$_REQUEST[$pair] = null;
}
elseif ($p === 0 || empty($pair)) {
continue;
}
else {
list($name, $value) = explode('=',$pair,2);
$name = preg_replace('/\[.*\]/','',urldecode($name));
$value = urldecode($value);
if (array_key_exists($name, $_REQUEST)) {
if (is_array($_REQUEST[$name])) {
$_REQUEST[$name][] = $value;
}
else {
$_REQUEST[$name] = array($_REQUEST[$name], $value);
}
}
else {
$_REQUEST[$name] = $value;
}
}
}
}
As it stands, this will only process the QueryString/GET variables; to process post as well, change the 3rd line to something like
$target = ($rawget ?: '') . '&' . ($rawpost ?: '');
All that having been said, I'd still recommend changing the HTML, but if that's not an option for whatever reason, then this should do it.
Is there a better way to do this simple task below? Like with an array or even another method?
<?PHP
// current way
if ($city != NULL) {
$city = FilterALLHTML($city);
}
if ($state != NULL) {
$state = FilterALLHTML($state);
}
if ($title != NULL) {
$title = FilterALLHTML($title);
}
if ($division != NULL) {
$division = FilterALLHTML($division);
}
?>
Here is my current function
function FilterALLHTML($document) {
//old array line //"'<[\/\!]*?[^<>]*//?//>'si",// strip html
$text = strip_tags($document);
$search = array ("/f.?u.?c.?k/i",
"/(s|$).?h.?i.?t/i",
'/(potspace|mycrib|palbolt)/i');
$text = preg_replace ($search, '', $text);
return $text;
}
UPDATE - Ok my new function after the suggestions from this post thanks guys
function FilterALLHTML($var) {
//old array line //"'<[\/\!]*?[^<>]*//?//>'si",// strip html
if ($var != null){
$text = strip_tags($var);
$search = array ("/f.?u.?c.?k/i",
"/(s|$).?h.?i.?t/i",
'/(potspace|mycrib|palbolt|pot space)/i');
$text = preg_replace ($search, '', $text);
return $text;
}
return null;
}
Change your FilterALLHTML function to do the null check and have it return null?
Then you can throw away all the ifs.
Example:
function FilterALLHTML($input)
{
if ($input === null)
return null;
// Original code, I'll just use strip_tags() for a functional example
return strip_tags($input);
}
Edit:
I felt like sharing an alternative to variable variables, as I don't really like the idea of using string literals instead of variable names. References all the way :)
function FilterALLHTML(&$text)
{
if ($text !== null)
{
// Omitted regex bit for simplicity
$text = strip_tags($text);
}
}
$city = "<b>New York</b>";
$state = null;
$title = "<i>Mr.</i>";
$fields = array(&$city, &$state, &$title);
foreach ($fields as &$var)
FilterALLHTML($var);
(note: FilterALLHTML implementation differs from first example)
Yes, use PHP's variable variables.
$vars = array('city','state','title','division');
foreach($vars as $v) {
if ($$v != null) $$v = FilterAllHTML($$v);
}
If you know for a fact that all the variables have been previously defined, then you don't need the null check. Otherwise, the null check will prevent E_NOTICE errors from triggering.
foreach (array('city', 'state', 'title', 'division') as $var) {
if ($$var != null) {
$$var = FilterALLHTML($$var);
}
}
Like Thorarin I'd suggest having your FilterALLHTML function check for null instead though.
zombat's answer is the best, but I'd add that you shouldn't really be checking for null either. If for some reason FilterAllHTML has a problem with null values, which it shouldn't, put the check for null in the FilterAllHTML function definition.
$vars = array('city', 'state', 'title', 'division');
foreach($vars as $var) {
$$var = FilterAllHTML($$var);
}
Well, you could already consider writing a function because you do exactly the same thing four times.
Assuming FilterALLHTML is not a custom function.
function Filter($var)
{
if ($var != null)
{
return FilterALLHTML($var);
}
return null;
}
Or just include the null check in the FilterALLHTML function and return null from there, if needed.
So, if you can change FilterALLHTML then you'd do it like this:
function FilterALLHTML($var)
{
if ($var == null)
{
return null;
}
else
{
//do your filtering
return $filteredVar;
}
}
Adding to Thorarin's answer, you can change your filterall function in order to accept an array as input, and passing it by reference it will modify the arrays' content.
$tofilter = array($city,$state,$division,$title);
filterall($tofilter);
I didn't see it mentioned, you could always pass the parameters by reference to skip the repeated assignments:
function FilterALLHTML(&$var)
{
if ($var == null)
{
$var = null;
}
else
{
$var = strip_tags($var);
}
}
I believe you can also store references in the array but i haven't tried it.
foreach (array(&$city, &$state, &$title, &$division) as $var)
{
FilterALLHTML($var);
}
I don't think you can improve the performance, but you can shorten the syntax, but it will end up being the same to the interpreter
<?PHP
$city = ($city == NULL) ? "default value" : FilterALLHTML($city);
$state = ($state == NULL) ? "default value" : FilterALLHTML($state);
$title = ($title == NULL) ? "default value" : FilterALLHTML($title);
$division = ($division == NULL) ? "default value" : FilterALLHTML($division);
?>
"default value" should be replaced with what you would like the value to be if the variable is null