Lravel return bad response on query - php

I have this function
public function getConditionDescription($search){
$condition = Condition::where("code", $search)->first();
return $condition ? $condition->condition_description : "" ;
}
but when I pass "#" as parameter the query return the first row with code = 0.
in the nex image you can see an example.
Does anyone know how prevent or escape this case?

There are two things you can do with this case,
make a route regex
use parameter type declaration
for the regex, you can check docs here,
and for the second method, you can change your code like so (if the code is integer):
public function getConditionDescription( int $search ){
$condition = Condition::where("code", $search)->first();
return $condition ? $condition->condition_description : "" ;
}

Related

Expanding variables in string passed as argument

I have a situation where I want to check if a lot of strings are empty before I perform an operation on them. I don't want to have to perform this check on every single string manually, so I put it in a function that looks like this:
function format_field($field_name, $format) {
$value = get_field($field_name);
if ($value != "") {
return $format;
}
return "";
}
A call to this function looks like this:
format_field('website', "<p><strong>Website:</strong>$value</p>");
I was hoping that by writing $value in the string passed to format_field() the value of $value would be expanded in the function before it got returned, but that doesn't seem to be the case.
Is this at all possible and I'm just going wrong?
I also know about sprintf(), but since $value can be referenced multiple times in the string it's less than ideal.
The problem with your code is that when passing "<p><strong>Website:</strong>$value</p>" as a function argument, the $value variable doesn't get substituted later in the function block.
So for example if you have $value = 'https://a.b.c'; the value of $format becomes "<p><strong>Website:</strong>https://a.b.c</p>"
What you could try, is substitute a placeholder, for example
pass "<p><strong>Website:</strong>{value}</p>" as the $format argument, then use something like that:
$format = "<p><strong>Website:</strong>{value}</p>";
$value = 'https://www.google.com';
echo preg_replace('#\{value\}#i', $value, $format);
which actually returns: <p><strong>Website:</strong>https://www.google.com</p>

One PHP statement to use result of IF statement for assignment

I have a situation where I have a function that does some database retrieval and either returns a value or an error. I'd like to have a single statement that calls the function and depending on result either assigns the returned value or a default value.
Using the tenary operator I could do something like this:
$val=(getVal($param)!='error' ? getVal($param) : "default");
but I don't want to have to call getVal twice because it excutes database queries and is expensive on performance.
I could also do it in two statements, but if possible I just want one. Appreciate any help.
Try this
$val=(($result=getVal($param))!='error' ? $result : "default");
There are only two ways I am aware of (maybe there is more).
Either you first assign function result to a variable and then use if:
$res = getVal($param);
$val = ($res != 'error' ? $res : "default");
Note: This is possibly the best option both for readability and performance.
Or you modify function from this:
function getVal($param) {
...
return $something;
}
to this:
function getVal ($param, &$result) {
...
$result = $something;
return $something;
}
And use it:
$val = (getVal($param,$res) != 'error' ? $res : "default");
But this looks fishy to me

Creating functions with Array as parameter not work with me

In short, I have a function like the following:
function plus($x, $y){
echo $x+$y;
}
I want to tell the function its parameters as array like the following:
$parms = array(20,10);
plus($parms);
But unfortunately, not work.
I'm tired by using another way as the following:
$parms = array(20,10);
$func_params = implode(',', $parms);
plus($func_params);
And also not work, and gives me Error message:
Warning: Missing argument 2 for plus(), called in.....
And now, I'm at a puzzled.
What can I do to work ?
There is a couple things you can do.
Firstly, to maintain your function definition you can use call_user_func_array(). I think this is ugly.
call_user_func_array('plus', $parms);
You can make your function more robust by taking a variable number of params:
function plus(){
$args = func_get_args();
return $args[0] + $args[1];
}
You can simply accept an array and add everything up:
function plus($args){
return $args[0] + $args[1];
}
Or you could sum up all arguments:
function plus($args){
return array_sum($args);
}
This is PHP, there are 10 ways to do everything.
You need to adapt your function so that it only accepts one parameter and then in the function itself, you can process that parameter:
Very simple example:
function plus($arr){
echo $arr[0]+$arr[1];
}
$parms = array(20,10);
plus($parms);
You can easily adapt that to loop through all elements, check the input, etc.
Heh? The error message is very clear: you ask for two parameters in your function, but you only provide one.
If you want to pass an array, it would be a single variable.
function plus($array){
echo ($array[0]+$array[1]);
}
$test = array(1,5);
plus($test); //echoes 6
Use this:
function plus($arr){
$c = $arr[0]+$arr[1];
echo $c;
}
And the you can invoke:
$parms = array(20,10);
plus($parms);

create_function with default parameter values?

Ok, I'm looking into using create_function for what I need to do, and I don't see a way to define default parameter values with it. Is this possible? If so, what would be the best approach for inputting the params into the create_function function in php? Perhaps using addslashes?
Well, for example, I have a function like so:
function testing($param1 = 'blah', $param2 = array())
{
if($param1 == 'blah')
return $param1;
else
{
$notblah = '';
if (count($param2) >= 1)
{
foreach($param2 as $param)
$notblah .= $param;
return $notblah;
}
else
return 'empty';
}
}
Ok, so how would I use create_function to do the same thing, adding the parameters and their default values?
The thing is, the parameters are coming from a TEXT file, as well as the function itself.
So, wondering on the best approach for this using create_function and how exactly the string should be parsed.
Thanks :)
Considering a function created with create_function this way :
$func = create_function('$who', 'echo "Hello, $who!";');
You can call it like this :
$func('World');
And you'll get :
Hello, World!
Now, having a default value for a parameter, the code could look like this :
$func = create_function('$who="World"', 'echo "Hello, $who!";');
Note : I only added the default value for the parameter, in the first argument passed to create_function.
And, then, calling the new function :
$func();
I still get :
Hello, World!
i.e. the default value for the parameter has been used.
So, default values for parameters work with create_function just like they do for other functions : you just have to put the default value in the list of parameters.
After that, on how to create the string containing the parameters and their values... A couple of string concatenations, I suppose, without forgetting to escape what should be escaped.
Do you want to create an anonymous function? The create_function is used to create the anonymous functions. Otherwise you need to create function normally like:
function name($parms)
{
// your code here
}
If you want to use the create_function, here is the prototype:
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo "New anonymous function: $newfunc\n";
echo $newfunc(2, M_E) . "\n";
// outputs
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
I'm having the same problem, trying to pass an array to a created callback function... I think I'll create a temporary variable... It's ugly but I have better to do then torture myself with slashes, my code is already cryptic enough the way it is now.
So, to illustrate:
global $tmp_someArray;
$tmp_someArray = $someArray;
$myCallback = create_function(
'$arg1',
'
global $tmp_someArray;
// do stuff with $tmp_someArray and $arg1....
return($something);
'
);

Better way to check variable for null or empty string?

Since PHP is a dynamic language what's the best way of checking to see if a provided field is empty?
I want to ensure that:
null is considered an empty string
a white space only string is considered empty
that "0" is not considered empty
This is what I've got so far:
$question = trim($_POST['question']);
if ("" === "$question") {
// Handle error here
}
There must be a simpler way of doing this?
// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
return ($str === null || trim($str) === '');
}
Old post but someone might need it as I did ;)
if (strlen($str) == 0){
do what ever
}
replace $str with your variable.
NULL and "" both return 0 when using strlen.
Use PHP's empty() function. The following things are considered to be empty
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
For more details check empty function
I'll humbly accept if I'm wrong, but I tested on my own end and found that the following works for testing both string(0) "" and NULL valued variables:
if ( $question ) {
// Handle success here
}
Which could also be reversed to test for success as such:
if ( !$question ) {
// Handle error here
}
Beware false negatives from the trim() function — it performs a cast-to-string before trimming, and thus will return e.g. "Array" if you pass it an empty array. That may not be an issue, depending on how you process your data, but with the code you supply, a field named question[] could be supplied in the POST data and appear to be a non-empty string. Instead, I would suggest:
$question = $_POST['question'];
if (!is_string || ($question = trim($question))) {
// Handle error here
}
// If $question was a string, it will have been trimmed by this point
There is no better way but since it's an operation you usually do quite often, you'd better automatize the process.
Most frameworks offer a way to make arguments parsing an easy task. You can build you own object for that. Quick and dirty example :
class Request
{
// This is the spirit but you may want to make that cleaner :-)
function get($key, $default=null, $from=null)
{
if ($from) :
if (isset(${'_'.$from}[$key]));
return sanitize(${'_'.strtoupper($from)}[$key]); // didn't test that but it should work
else
if isset($_REQUEST[$key])
return sanitize($_REQUEST[$key]);
return $default;
}
// basics. Enforce it with filters according to your needs
function sanitize($data)
{
return addslashes(trim($data));
}
// your rules here
function isEmptyString($data)
{
return (trim($data) === "" or $data === null);
}
function exists($key) {}
function setFlash($name, $value) {}
[...]
}
$request = new Request();
$question= $request->get('question', '', 'post');
print $request->isEmptyString($question);
Symfony use that kind of sugar massively.
But you are talking about more than that, with your "// Handle error here
". You are mixing 2 jobs : getting the data and processing it. This is not the same at all.
There are other mechanisms you can use to validate data. Again, frameworks can show you best pratices.
Create objects that represent the data of your form, then attach processses and fall back to it. It sounds far more work that hacking a quick PHP script (and it is the first time), but it's reusable, flexible, and much less error prone since form validation with usual PHP tends to quickly become spaguetti code.
This one checks arrays and strings:
function is_set($val) {
if(is_array($val)) return !empty($val);
return strlen(trim($val)) ? true : false;
}
to be more robust (tabulation, return…), I define:
function is_not_empty_string($str) {
if (is_string($str) && trim($str, " \t\n\r\0") !== '')
return true;
else
return false;
}
// code to test
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
var_export($value);
if (is_not_empty_string($value))
print(" is a none empty string!\n");
else
print(" is not a string or is an empty string\n");
}
sources:
https://www.php.net/manual/en/function.is-string.php
https://www.php.net/manual/en/function.trim.php
When you want to check if a value is provided for a field, that field may be a string , an array, or undifined. So, the following is enough
function isSet($param)
{
return (is_array($param) && count($param)) || trim($param) !== '';
}
use this :
// check for null or empty
if (empty($var)) {
...
}
else {
...
}
empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:
if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {

Categories