php mysql function for inserting records - php

I have this piece of code that I am studying but don't see the purpose of a certain line.
public function insertRecords($table, $data){
//setup some variables for fields and values
$fields = "";
$values = "";
//populate them
foreach($data as $f => $v){
$fields .= "`$f`,";
$values .= (is_numeric($v) && (intval($v) == $v)) ? $v . "," : "'$v',";
}
//remove our trailing ,
$fields = substr($fields, 0, -1);
//remove our trailing ,
$values = substr($values, 0, -1);
$insert = "INSERT INTO $table ({$fields}) values({$values})";
//echo $insert
$this->executeQuery($insert);
return true;
}
I don't see the purpose of:
intval($v) == $v))
In the ternary operator. What I understand is, if the integer value of $v is the same as $v do blah. Of course the integer value of $v is going to be equal to $v. It's the current value in the current iteration. Is my understanding incorrect?
I already know that if intval() doesn't return a integer it defaults to a string in the ternary operator.

You are correct in your assumption.
That line is merely a method of checking whether the variable $v is indeed an integer. Because if it is any other data-type the value would differ from that intval() operation.

It is using intval() just because it's checking for the value entered to be an integer rather than a string wich would not be allowed in your query either for column datatype and for security purpose
intval — Get the integer value of a variable

is_numeric($v) returns true if $v is a number (e.g. 234233) or numeric string (e.g. "234233"), whereas intval($v) == $v returns true if $v is an integer.
The first makes sure $v is a numeric in any way and seconds checks if $v is an integer.
I guess you could drop is_numeric($v)

Related

Unable to populate cell by zero value from $_GET array

I am having an issue - I am unable to get a td cell when my $v value is 0. For all other numbers it is fine, but with zero value I just don't get then td.. What could be wrong? I am using $_GET array with a foreach loop, taking data from two inputs, one for name, one for value.
<table border = "1" >
<?php
print_r($_GET);
foreach ($_GET as $k=>$v){
if($v){
if ($rowFinished) echo "<tr>";
if (preg_match("/{$inputVardas}/i", $k))
{
echo "<td>$v</td>";
$rowFinished = false;
}
else if (preg_match("/{$inputSkaicius}/i", $k) and is_numeric($v))
{
if ($v < 10)
{
$color="green";
}
else if ($v > 10)
{
$color="red";
}
else if( $v == 10){
$color="yellow";
}
echo "<td style='color: $color'>$v</td>";
$rowFinished = true;
}
if ($rowFinished) echo "</tr>";
}
}?></table>
I've tried to do some print_r of an array, there I can see a value, but in my loop it just doesn't work. Maybe it has to do something with the case that php treats it as empty, but I am unable to find a way to use it.
[vardas0] => jonas [value0] => 0
Directly after the foreach you have a if ($v), and if the value is 0, it will not run.
I've found a way by improving the following line from
if($v){
to
if($v or (is_numeric($v) and $v == 0)){
It looks like you're using this
if ($v) {
to check that $v has a value. You can use
if (strlen($v)) {
instead.
Everything in $_GET will be a string, but a string '0' will evaluate as false just like an int 0 as you have discovered. Checking the length of the string instead will tell you whether or not that URL parameter has any value, including '0'.
You may also want to consider trimming the value before checking it if you want to exclude values containing only whitespace.
$v = trim($v);
if (strlen($v)) {
I honestly would suggest using isset()instead of all the provided suggestions so far. The reason is that to me it is best practice to have your conditionals be a boolean expression or something that explicitly evaluates to true or false. This avoids ambiguity and unintended side effects as evidenced by this question.
I would personally use:
if(isset($v)){

Why does casting a string as an integer not work?

// EDIT: The end goal is to detect whether user-submitted value is a string, or an integer. Because the value is obtained from form input, it is cast as string even when the value provided is an integer number.
I am performing a simple comparison to detect if a string variable is equal to its integer value. The value is passed from an HTML form field.
When the string value is a single letter, it evaluates to true, when it should not.
if ( ($val == (int)$val ) && strlen( $val ) == strlen( (int)$val ) ){
}
I've also tried using intval() rather than casting int variable type.
It is always evaluating as true. But r does not == 0, so how can this be?
$val = 'r';
echo 'Does $val = (int)$val? ' . ($val == (int)$val);
echo '<br/><br/>';
echo '$val was: ' . $val . '<br/>';
echo '(int)$val was: ' . (int)$val;
Output:
Does $val = (int)$val? 1
$val was: r
(int)$val was: 0
To check if your string is actually a number (which is what you want according to your comments), you don't have to hack together some custom test. PHP provides a built-in function for this:
if(is_numeric($val)) {
//do integer stuff
} else {
//do string stuff
}
To check whether string is actually a number, I'd use something like that:
if (strval(intval($val, 10)) == $val)
Note: this will detect only strings with integer numbers, there is also is_numeric which works for decimal and exponential (like +0123.45e6).
Note 2: is_int detects actual type of variable, so for "123" it will return false because it is string.
Note 3: you could have problems when number is submitted with + prefix like +123 - it is up to you whether you want to support such case or not

check php post value is numeric and well formatted

I need to check POST value is numeric and well formatted. My expected format is
number.number
1.0
11.5
If POST value comes without .(DOT) only 1 then I would want that php convert that to 1.0
I tried this code but it doesn't work.
$foo = '2';
$foo = preg_match('/\\d{2}\\:\\d{2}\\.\\d{2}/', $foo);
Thanks :)
Working code
//$value = '22';
$value = $_POST["input_value"];
if (is_numeric($value)) {
$new_value = number_format($value, 1);
} else {
$new_value = "$value is not numeric. <br>";
}
echo $new_value;
You basically want to check if the variable from the POST array is a float/double or not (float/double is a type of number in the format of x.x).
Cheking if a string is a float/double number
To do that, use this php built-in function: is_double or more accurate:is_float, that will tell you if the string is a float/double.
Checking if a string is an integer and converting it to a double/float value
If it's not a double, check if it's an integer (regular number): is_int, and if it's indeed an int, cast it to double by using number_format, look at the usage here: integer to double/float in php.
Example
$final_value;
$value = $_POST["wanted_value"];
if (is_float($value))
{
$final_value = $value;
}
else if (is_int($value))
{
$final_value = number_format($value, 1); // or 2 instead of 1 (2.0 or 2.00)
}
else
{
$final_value = "ERROR";
}
Hope this helps!

Check if all values in array are the same

I need to check if all values in an array equal the same thing.
For example:
$allValues = array(
'true',
'true',
'true',
);
If every value in the array equals 'true' then I want to echo 'all true'. If any value in the array equals 'false' then I want to echo 'some false'
Any idea on how I can do this?
All values equal the test value:
// note, "count(array_flip($allvalues))" is a tricky but very fast way to count the unique values.
// "end($allvalues)" is a way to get an arbitrary value from an array without needing to know a valid array key. For example, assuming $allvalues[0] exists may not be true.
if (count(array_flip($allvalues)) === 1 && end($allvalues) === 'true') {
}
or just test for the existence of the thing you don't want:
if (in_array('false', $allvalues, true)) {
}
Prefer the latter method if you're sure that there's only 2 possible values that could be in the array, as it's much more efficient. But if in doubt, a slow program is better than an incorrect program, so use the first method.
If you can't use the second method, your array is very large, and the contents of the array is likely to have more than 1 value (especially if the 2nd value is likely to occur near the beginning of the array), it may be much faster to do the following:
/**
* Checks if an array contains at most 1 distinct value.
* Optionally, restrict what the 1 distinct value is permitted to be via
* a user supplied testValue.
*
* #param array $arr - Array to check
* #param null $testValue - Optional value to restrict which distinct value the array is permitted to contain.
* #return bool - false if the array contains more than 1 distinct value, or contains a value other than your supplied testValue.
* #assert isHomogenous([]) === true
* #assert isHomogenous([], 2) === true
* #assert isHomogenous([2]) === true
* #assert isHomogenous([2, 3]) === false
* #assert isHomogenous([2, 2]) === true
* #assert isHomogenous([2, 2], 2) === true
* #assert isHomogenous([2, 2], 3) === false
* #assert isHomogenous([2, 3], 3) === false
* #assert isHomogenous([null, null], null) === true
*/
function isHomogenous(array $arr, $testValue = null) {
// If they did not pass the 2nd func argument, then we will use an arbitrary value in the $arr (that happens to be the first value).
// By using func_num_args() to test for this, we can properly support testing for an array filled with nulls, if desired.
// ie isHomogenous([null, null], null) === true
$testValue = func_num_args() > 1 ? $testValue : reset($arr);
foreach ($arr as $val) {
if ($testValue !== $val) {
return false;
}
}
return true;
}
Note: Some answers interpret the original question as (1) how to check if all values are the same, while others interpreted it as (2) how to check if all values are the same and make sure that value equals the test value. The solution you choose should be mindful of that detail.
My first 2 solutions answered #2. My isHomogenous() function answers #1, or #2 if you pass it the 2nd arg.
Why not just compare count after calling array_unique()?
To check if all elements in an array are the same, should be as simple as:
$allValuesAreTheSame = (count(array_unique($allValues, SORT_REGULAR)) === 1);
This should work regardless of the type of values in the array.
Update: Added the SORT_REGULAR flag to avoid implicit type-casting as pointed out by Yann Chabot
Also, you can condense goat's answer in the event it's not a binary:
if (count(array_unique($allvalues)) === 1 && end($allvalues) === 'true') {
// ...
}
to
if (array_unique($allvalues) === array('foobar')) {
// all values in array are "foobar"
}
If your array contains actual booleans (or ints) instead of strings, you could use array_sum:
$allvalues = array(TRUE, TRUE, TRUE);
if(array_sum($allvalues) == count($allvalues)) {
echo 'all true';
} else {
echo 'some false';
}
http://codepad.org/FIgomd9X
This works because TRUE will be evaluated as 1, and FALSE as 0.
You can compare min and max... not the fastest way ;p
$homogenous = ( min($array) === max($array) );
$alltrue = 1;
foreach($array as $item) {
if($item!='true') { $alltrue = 0; }
}
if($alltrue) { echo("all true."); }
else { echo("some false."); }
Technically this doesn't test for "some false," it tests for "not all true." But it sounds like you're pretty sure that the only values you'll get are 'true' and 'false'.
Another option:
function same($arr) {
return $arr === array_filter($arr, function ($element) use ($arr) {
return ($element === $arr[0]);
});
}
Usage:
same(array(true, true, true)); // => true
Answering my method for people searching in 2023.
$arr = [5,5,5,5,5];
$flag = 0;
$firstElement = $arr[0];
foreach($arr as $val){
// CHECK IF THE FIRST ELEMENT DIFFERS FROM ANY OTHER ELEMENT IN THE ARRAY
if($firstElement != $val){
// FIRST MISMATCH FOUND. UPDATE FLAG VALUE AND BREAK OUT OF THE LOOP.
$flag = 1;
break;
}
}
if($flag == 0){
// ALL THE ELEMENTS ARE SAME... DO SOMETHING
}else{
// ALL THE ELEMENTS ARE NOT SAME... DO SOMETHING
}
In an array where all elements are same, it should always be true that all the elements MUST match with the first element of the array. Keeping this logic in mind, we can get the first element of the array and iterate through each element in the array to check for that first element in the loop which does not match with the first element in the array. If found, we will change the flag value and break out of the loop immediately. Else, the loop will continue till it reaches the end. Later, outside the loop, we can use this flag value to determine if all the elements in the array are same or not.
This solution is good for arrays with definite limit of elements (small array). However, I am not sure how good this solution would be for arrays with very large number of elements present considering that we are looping through each and every element to check for the first break even point. Please use this solution at your own convenience and judgement.
$x = 0;
foreach ($allvalues as $a) {
if ($a != $checkvalue) {
$x = 1;
}
}
//then check against $x
if ($x != 0) {
//not all values are the same
}

php, mysql, arrays - if( x == 0 ) { }

I have the following code
while($row = $usafisRSP->fetch_assoc())
{
$hidden_keys = array('Applicantid', 'unique_num', 'regs_time' ....);
$hidden_fields = array_intersect_key($row, array_fill_keys($hidden_keys, NULL));
$hidden_values = array();
foreach ($hidden_fields as $key => $value) {
// fill the values array using the values from fields array
$hidden_values[$value] = "$key = ".base64_decode($value)."";
if(base64_decode($value)== 0)
{
$hidden_values[$value] = "";
}
echo $hidden_values[$value];
The question is about "if($hidden_values[$value] == 0)" ... Basically I want to do not display/echo the $hidden_values[$value] if it's value of $value is 0. Sometimes $value is 0 or some words like (23 avenue).
I think you ran into three catches with PHP type comparisons and equalities:
Any string not beginning with a number will always loosely equal 0. So basically, if(base64_decode($value)== 0) will likely always resolve to true, even if decoded $value is "Adam".
Return value of base64_decode is a string, so if 0 is the result, it will be string 0, not integer 0. This means if(base64_decode($value) === 0) wouldn't even work if decoded $value is "0". Another catch is base64_decode may return false on errors, again failing this strict equality check.
A non-empty string (other than "0") will always loosely equal true. So this is the only comparison you really need for your case.
I think this is what you want, replacing the last 5 lines...
if(base64_decode($value)) echo $hidden_values[$value];
else $hidden_values[$value] = "";
} // closing your for loop
Is this what you're looking for?
foreach( $hidden_values as $value ) {
if( $value !== 0 ) {
echo $value;
}
}

Categories