I'm trying to find a smarter way to validate my inputs with PHP. If the array finds an empty field, it has to add a new element to the array and display an error message.
So far, I haven't succeeded.
The code behind
$felter = array();
if(isset($_POST['submit'])) {
$produktnavn = $_POST['produktnavn'];
$kategori = $_POST['kategori'];
if( !empty( $felter ) ) {
foreach ($felter as $felt) {
if ($felter == '') {
$fejl = true;
}
}
}
else {
$sql = "UPDATE produkt SET produkt_navn = '$produktnavn', fk_kategori_id = '$kategori' WHERE produkt_id=$id";
mysqli_query($db, $sql);
echo "Produktet blev opdateret";
}
Input form
<input type="text" class="form-control" name="produktnavn" value="<?php echo $produktnavn; ?>">
The code starts with $felter = array(); which initializes an empty array.
Then, without changing the array itself, you're checking for non-emptiness of $felter
if( !empty( $felter ) ) {
foreach ($felter as $felt) {
if ($felter == '') {
$fejl = true;
}
}
}
You're trying to iterate over an array that has not gotten any elements pushed into it. And the logic statement if( !empty ($felter)) will also not work as expected either.
As a test, before the check for !empty, put something in the array with $felter[] = 'Test word'; and then, underneath it... (if you're looking for a non-empty array, the logical checker could be if(count($felter)) { before iterating over the array with foreach ($felter as $felt) { if ($felt == '')
$felter = array();
$felter[] = 'Test word';
if(isset($_POST['submit'])) {
$produktnavn = $_POST['produktnavn'];
$kategori = $_POST['kategori'];
if( count( $felter ) ) {
foreach ($felter as $felt) {
if ($felt == '') {
$fejl = true;
}
}
}
Related
I'm trying to pass variables from a foreach function that fetch a mysql query to an array, to another function.
I declare the array before the foreach to make it global but no data are passed to the function.
here is my code. If you have any idea of what i'm doing, thanks by advance for your help.
Of course if I replace the called function by what's inside it, everything works like a charm.
but as I'll have to use it several times I would prefer to set my variables in a function.
function fillStuInfos() {
global $studFName, $studLName,c$dateStart, $dateEnd;
$studFName = $EventsGt['fName'];
$studLName = $EventsGt['lName'];
$dateStart = $EventsGt['startDate'];
$dateEnd = $EventsGt['endDate'];
}
$email = $_POST['email'];
$EventsGt = array();
$getEventsQry = 'SELECT * FROM Companies WHERE Email_Company = "'.$email.'" ORDER BY startDate';
foreach ($bddPDO->query($getEventsQry) as $EventsGt) {
$intCur = date_diff(date_create($today), date_create($EventsGt['endDate']));
$intFut = date_diff(date_create($today), date_create($EventsGt['startDate']));
echo intval($intCur->format('%r%a'));
if (intval($intCur->format('%r%a')) <= 4 && intval($intCur->format('%r%a')) > 0 ) {
fillStuInfos();
} else if ( intval($intFut->format('%r%a')) <= 4 && intval($intFut->format('%r%a')) > 0 ){
fillStuInfos();
} else {
echo 'No Datas!';
exit();
}
}
echo $studLName;
Forget that exists global and pass params to function.
function fillStuInfos($data) {
$studFName = $data['fName'];
$studLName = $data['lName'];
$dateStart = $data['startDate'];
$dateEnd = $data['endDate'];
}
...
foreach (...) {
if (intval($intCur->format('%r%a')) <= 4 && intval($intCur->format('%r%a')) > 0 ) {
fillStuInfos($EventsGt);
} else if ( intval($intFut->format('%r%a')) <= 4 && intval($intFut->format('%r%a')) > 0 ){
fillStuInfos($EventsGt);
} else {
echo 'No Datas!';
exit();
}
}
Your variable you want to be global is $EventsGt, not $studFName, $studLName, $dateStart, $dateEnd
With that said, I would recommend passing the event array as a parameter or passing the individual values as parameters instead.
I made this function to check for expected request variables. It was working great until I realized that if two values (Not keys) were the same, it would return a positive number as though a key was missing. Consider the following code:
function requestCheck($expectedAr)
{
if(isset($_GET) && isset($_POST))
{
$requestAr = array_unique(array_merge($_GET, $_POST));
}elseif(isset($_GET)){
$requestAr = $_GET;
}elseif(isset($_POST)){
$requestAr = $_POST;
}else{
$requestAr = array();
}
$diffAr = array_diff_key(array_flip($expectedAr),$requestAr);
if(count($diffAr) > 0)
{
returnError("Missing variables: ".implode(',',array_flip($diffAr)).".");
}else {
return $requestAr;
}
}
$requestAr = requestCheck(['name','password']);
if 'name' and 'password' both hold the same value, it will run returnError(). Not seeing why.
Here's a dump of $_POST:
array (
'poolName' => 'xpool',
'userPrefix' => 'xpool'
)
array_unique will strip unique values so you'll end up with either name or password but not both.
Solution:
function requestCheck($expectedAr) {
if(isset($_GET) && isset($_POST)) {
$requestAr = $_REQUEST;
}elseif(isset($_GET)) {
$requestAr = $_GET;
}elseif(isset($_POST)) {
$requestAr = $_POST;
}else{
$requestAr = array();
}
$diffAr = array_diff_key(array_flip($expectedAr),$requestAr);
if(count($diffAr) > 0)
{
returnError("Missing variables: ".implode(',',array_flip($diffAr)).".");
}else {
return $requestAr;
}
}
$requestAr = requestCheck(['name','password']);
I think it's safe to also do the following:
function requestCheck($expectedAr) {
$requestAr = isset($_REQUEST) && is_array($_REQUEST)?$_REQUEST:array();
$diffAr = array_diff_key(array_flip($expectedAr),$requestAr);
if(count($diffAr) > 0) {
returnError("Missing variables: ".implode(',',array_flip($diffAr)).".");
}else {
return $requestAr;
}
}
$requestAr = requestCheck(['name','password']);
Look at my script:
if((isset($_POST['unma']) && isset($_POST['livi'])) && (isset($_POST['cont']) &&
isset($_POST['phone']))){
if(
(
(
(
(isset($_POST['fnma']) && isset($_POST['lnma']))
&&
(isset($_POST['occ']) && isset($_POST['hom']))
)
&&
(
(isset($_POST['town']) && isset($_POST['dist']))
&&
(isset($_POST['dispmb']) && isset($_POST['fbc']))
)
)
&&
(
(
(isset($_POST['gp']) && isset($_POST['twt']))
&&
(isset($_POST['ins']) && isset($_POST['flc']))
)
&&
(
(isset($_POST['ile']) && isset($_POST['cam']))
&&
(isset($_POST['cam_co']) && isset($_POST['prof_phr']))
)
)
)
&&
isset($_POST['awards'])
){
// Codes here
}
How can I short this isset functions. I found an solution with foreach but they are not checking the post isset, rather they are checking if the posted values are not empty
You can use
if (isset($_POST['a'], $_POST['b'], $_POST['c'], ...))
and so on. If any of the variables is not set then you will get false.
$expectedKeys = ['fnma', 'lnma', ...];
if (!array_diff_key(array_flip($expectedKeys), $_POST)) {
// all keys are set
}
I think something like this would work:
// add all names of the values that needs to be set in the `$_POST` array
$values = array('fnma', 'lnma');
function checkSet($array) {
foreach($array as $value) {
if(!isset($_POST[$value])) return false;
}
return true;
}
if(checkSet($values)) {
// your code
}
put required fields in a array and check for it using loop,it is easy and easy to add required fields.
$req_values = array('fnma','lnma','occ','hom','town','dist','dispmb','fbc','gp','twt','ins','flc','ile','cam','cam_co','prof_phr');
foreach($req_values as $key) {
if (empty($_POST[$key])) {
echo $key .'is required';
exit;
}
}
Knowing that isset can take multiple values, you could do this:
if (isset($_POST['unma'], $_POST['livi'], $_POST['cont'], $_POST['phone'], $_POST['fnma'], $_POST['lnma'], $_POST['occ'], $_POST['hom'], $_POST['town'], $_POST['dist'], $_POST['dispmb'], $_POST['fbc'], $_POST['gp'], $_POST['tat'], $_POST['ins'], $_POST['flc'], $_POST['ile'], $_POST['cam'], $_POST['cam_co'], $_POST['prof_phr'], $_POST['awards'])) {
// Codes here
}
But that seems nightmarish. I would make the $_POST keys an array & then do the following:
// Set an array of post values.
$post_values = array('unma','livi','cont','phone','fnma','lnma','occ','hom','town','dist','dispmb','fbc','gp','tat','ins','flc','ile','cam','cam_co','prof_phr','awards');
// Set '$post_valid' to an array.
$post_valid = array();
// Roll through the post values.
foreach ($post_values AS $post_key => $post_value) {
// If the value is set, set '$post_valid' to TRUE or else set it to FALSE.
// $post_valid = isset($_POST[$post_key]) ? TRUE : FALSE; // Not really needed. Simple `isset` should work.
$post_valid[$post_key] = !empty($_POST[$post_key]);
}
// Now if '$post_valid' values are all true, do something.
$post_valid_values = array_values($post_valid);
if (!empty($post_valid_values) && (count($post_valid_values) == count($post_values))){
// Codes here
}
I'm just wondering if there's a way to simplify this code?
foreach ($parent_data as $ind_port_record) {
if ( isset($ind_port_record['port_name']) && (strtoupper($ind_port_record['port_name']) == 'GI/2' || strtoupper($ind_port_record['port_name']) == 'G2' || strtoupper($ind_port_record['port_name']) == 'GI2') ){
$record_to_include['remote_id'] = $ind_port_record['remote_id'];
$record_to_include['remote_name'] = $ind_port_record['remote_name'];
$record_to_include['remote_object_id'] = $ind_port_record['remote_object_id'];
$record_to_include['remote_object_name'] = $ind_port_record['remote_object_name'];
break;
}
}
//make sure you have something in remote object details
if ( ! isset($record_to_include['remote_id']) ){
$record_to_include['remote_id'] = '';
$record_to_include['remote_name'] = '';
$record_to_include['remote_object_id'] = '';
$record_to_include['remote_object_name'] = '';
}
I just need to make sure the values inside the $record _to_include are not uninitialized or NULL.
Thanks.
First off, simplify the if()
You currently have a lot of conditions
(strtoupper($ind_port_record['port_name']) == 'GI/2' || strtoupper($ind_port_record['port_name']) == 'G2' || strtoupper($ind_port_record['port_name']) == 'GI2')
Let's make that check an array
in_array( strtoupper($ind_port_record['port_name'], array('GI/2','G2','GI2')) )
Now to check if $record_to_include are not uninitialized or NULL
Let's loop through the array and do a simple check.
foreach($record_to_include as $record => $value) {
$record_to_include[$record] = is_null($value) OR !isset($record_to_include[$record]) ? '' : $value;
}
$record = array_filter($parentData, function (array $record) {
return isset($record['port_name']) && preg_match('!^(GI/2|G2|GI2)$!i', $record['port_name']);
});
$recordToInclude = $record ? current($record) : array(
'remote_id' => null,
'remote_name' => null,
'remote_object_id' => null,
'remote_object_name' => null
);
$gi_constraint = array('GI/2', 'G2', 'GI2'); // you are checking one and the same variable for different values, so you can use in_array here
foreach ($parent_data as $ind_port_record) {
if (isset($ind_port_record['port_name']) && in_array(strtoupper($ind_port_record['port_name']), $gi_constraint)){
foreach ($ind_port_record as $k=>$v) {
$record_to_include[$k] = $v; // as they have the same keys, you can specify the key and assign to the value of $in_port_record
}
break;
}
}
//make sure you have something in remote object details
if (!isset($record_to_include['remote_id']) ){
foreach ($record_to_include as $k => &$v) {
$v = ''; // when using reference, it will change the original array
}
}
Explanations in the code
Try
$arr = array('remote_id','remote_name','remote_object_id','remote_object_name');
if ( isset($ind_port_record['port_name']) && (strtoupper($ind_port_record['port_name']) == 'GI/2' || strtoupper($ind_port_record['port_name']) == 'G2' || strtoupper($ind_port_record['port_name']) == 'GI2') ){
foreach($arr as $ar){
$record_to_include[$ar] = (isset($ind_port_record[$ar]) && isset($record_to_include['remote_id']))?$ind_port_record[$ar]:NULL;
}
}
I know that my question could be very similar to anothers in Stackoverflow. I have found some similar questions but actually I couldn't get the right solution for my problem;
I am writing shopping cart using Sessions and ajax-json.
My products
structure is a bit complicated. It has name, size, type, colour and a
specific price for each type and size. The main point is that I can't
increment the item quantity if the name, size, type, color and price are
the same, if I'm adding the same product. Here is my code. I think I
am writing right, but I can't understand what is the problem.
Actually it increments the item quantity, but just one time, and when
I am checking the array, it's item quantity has not been incremented.
$data = json_decode($_POST['jsonData'], true);
$pr_type = $data['pr_type'];
$pr_size = $data['pr_size'];
$pr_link = $data['pr_link'];
$pr_color = $data['pr_color'];
$pr_price = $data['pr_price'];
$products_s = $this->getSession()->get('prof_cart');
$product = array();
if (empty($products_s)) {
$products_s = array();
} else {
$products_s = $products_s;
}
$products = Model::factory('Client_Product')->getProductById($pr_link);
$type = Model::factory("Client_Product")->getProductTypeByLink($pr_type);
$size = Model::factory("Client_Product")->getProductSizeById($pr_size);
if ($pr_type != 'undefined') {
$product['type'] = $type[0]['title'];
} else {
$product['type'] = "";
}
$isCreate = true;
foreach ($products_s as $id) {
if ($id['price'] == $pr_price &&
$id['title'] == $products[0]['title'] &&
$id['size'] == $size[0]['size'] &&
$id['type'] == $type[0]['title']) {
$id['quant']++;
$isCreate = false;
}
}
if ($isCreate) {
$product['quant'] = 1;
$product['size'] = $size[0]['size'];
$product['title'] = $products[0]['title'];
$product['price'] = $pr_price;
$product['color'] = $pr_color;
array_push($products_s, $product);
}
$sum = 0;
foreach ($products_s as $id) {
$sum += $id['price'] * $id['quant'];
}
//echo $sum;
echo "<pre>";
var_dump($products_s);
echo "</pre>";
$this->getSession()->set('prof_cart', $products_s);
$this->getSession()->set('prof_sum', $sum);
You need to increase quantity in your main product array like below.
foreach ($products_s as $key => $id) {
if ($id['price'] == $pr_price &&
$id['title'] == $products[0]['title'] &&
$id['size'] == $size[0]['size'] &&
$id['type'] == $type[0]['title']) {
$products_s[$key]['quant']++;
$isCreate = false;
}
}
try this :
foreach ($products_s as $id) {
if ($id['price'] == $pr_price &&
$id['title'] == $products[0]['title'] &&
$id['size'] == $size[0]['size'] &&
$id['type'] == $type[0]['title']) {
$id['quant'] = $id['quant']++;
$isCreate = false;
}
}