isset method not working returns nothing - php
I am trying to map a collection of JSON files into a database but my isset check is not working in my PHP :
<?php
$con = mysqli_connect("localhost", "root", "", "json_map");
$response = array();
$res = array();
$result = '';
foreach(glob('C:\xampp\htdocs\laravel\awsconfig\app\views\*.json') as $filename)
{
$json = file_get_contents($filename);
if ($json != null)
{
$decoded = json_decode($json, true);
// $decode= var_dump($decoded);
// $ss=$decode["array"];
// echo $decoded['number'];
if (is_array($decoded["configurationItems"]))
{
foreach($decoded["configurationItems"] as $configurationItems)
// for($i=0;$i>sizeof($decoded["configurationItems"]);$i++)
{
$cfi = isset($configurationItems["configuration"]) ? $configurationItems["configuration"] : '';
if (isset($cfi["instanceId"]) && isset($cfi["imageId"]) && isset($cfi["privateDnsName"]) && isset($cfi["publicDnsName"]) && isset($cfi["keyName"]) && isset($cfi["stateTransitionReason"]) && isset($cfi["amiLaunchIndex"]) && isset($cfi["instanceType"]) && isset($cfi["launchTime"]) && isset($cfi["kernelId"]) && isset($cfi["subnetId"]) && isset($cfi["vpcId"]) && isset($cfi["privateIpAddress"]) && isset($cfi["architecture"]) && isset($cfi["rootDeviceType"]) && isset($cfi["rootDeviceName"]) && isset($cfi["virtualizationType"]) && isset($cfi["clientToken"]) && isset($cfi["sourceDestCheck"]) && isset($cfi["hypervisor"]) && isset($cfi["ebsOptimized"]))
{
$instanceId = $configurationItems["configuration"]["instanceId"];
echo "instanceId:", $instanceId, "<br />";
$imageId = $configurationItems["configuration"]["imageId"];
echo "imageId:", $imageId, "<br />";
$privateDnsName = $configurationItems["configuration"]["privateDnsName"];
echo "privateDnsName:", $privateDnsName, "<br />";
$publicDnsName = $configurationItems["configuration"]["publicDnsName"];
echo "publicDnsName:", $publicDnsName, "<br />";
$keyName = $configurationItems["configuration"]["keyName"];
echo "keyName:", $keyName, "<br />";
$stateTransitionReason = $configurationItems["configuration"]["stateTransitionReason"];
echo "stateTransitionReason:", $stateTransitionReason, "<br />";
$amiLaunchIndex = $configurationItems["configuration"]["amiLaunchIndex"];
echo "amiLaunchIndex:", $amiLaunchIndex, "<br />";
$instanceType = $configurationItems["configuration"]["instanceType"];
echo "instanceType:", $instanceType, "<br />";
$launchTime = $configurationItems["configuration"]["launchTime"];
echo "launchTime:", $launchTime, "<br />";
$kernelId = $configurationItems["configuration"]["kernelId"];
echo "kernelId:", $kernelId, "<br />";
$subnetId = $configurationItems["configuration"]["subnetId"];
echo "subnetId:", $subnetId, "<br />";
$vpcId = $configurationItems["configuration"]["vpcId"];
echo "vpcId:", $vpcId, "<br />";
$privateIpAddress = $configurationItems["configuration"]["privateIpAddress"];
echo "privateIpAddress:", $privateIpAddress, "<br />";
$architecture = $configurationItems["configuration"]["architecture"];
echo "architecture:", $architecture, "<br />";
$rootDeviceType = $configurationItems["configuration"]["rootDeviceType"];
echo "rootDeviceType:", $rootDeviceType, "<br />";
$rootDeviceName = $configurationItems["configuration"]["rootDeviceName"];
echo "rootDeviceName:", $rootDeviceName, "<br />";
$virtualizationType = $configurationItems["configuration"]["virtualizationType"];
echo "virtualizationType:", $virtualizationType, "<br />";
$clientToken = $configurationItems["configuration"]["clientToken"];
echo "clientToken:", $clientToken, "<br />";
$sourceDestCheck = $configurationItems["configuration"]["sourceDestCheck"];
echo "sourceDestCheck:", $sourceDestCheck, "<br />";
$hypervisor = $configurationItems["configuration"]["hypervisor"];
echo "hypervisor:", $hypervisor, "<br />";
$ebsOptimized = $configurationItems["configuration"]["ebsOptimized"];
echo "ebsOptimized:", $ebsOptimized, "<br />";
$result = mysqli_query($con, "INSERT INTO configuration(instance_id, image_id, private_dns_name, public_dns_name, key_name, state_transition_reason, ami_launch_index, instance_type, launch_time, kernel_id, subnet_id, vpc_id, private_ip_address,architecture, root_device_type, root_device_name, virtualisation_type, client_token, source_dest_check, hypervisor, ebs_optimised)
VALUES('$instanceId','$imageId', '$privateDnsName' , '$publicDnsName', '$keyName', '$stateTransitionReason', '$amiLaunchIndex', '$instanceType', '$launchTime', '$kernelId', '$subnetId', '$vpcId', '$privateIpAddress', '$architecture', '$rootDeviceType', '$rootDeviceName', '$virtualizationType', '$clientToken', '$sourceDestCheck', '$hypervisor', '$ebsOptimized')") or die("Insert Failed " . ((is_object($con)) ? mysqli_error($con) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));;
} // check if row inserted or not
if ($result)
{
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully updated config table ";
// echoing JSON response
echo json_encode($response);
}
else
{
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
}
}
?>
when I use
$cfi = isset($configurationItems["configuration"]) ? $configurationItems["configuration"] : '';
I get oops an error occured no explanation of error
when I use
$cfi = $configurationItems ["configuration"];
I get as above plus undefined index configuration (the error)
isset() will return FALSE if testing a variable that has been set to NULL.
For more details refer link
Instead of having to use isset for every single key that is required for your criteria, you can build a validation array with the required keys and then check if your designated array contains all those keys.
$required_keys = ['instanceId',
'imageId',
'privateDnsName',
'publicDnsName',
'keyName',
'stateTransitionReason',
'amiLaunchIndex',
'instanceType',
'launchTime',
'kernelId',
'subnetId',
'vpcId',
'privateIpAddress',
'architecture',
'rootDeviceType',
'rootDeviceName',
'virtualizationType',
'clientToken',
'sourceDestCheck',
'hypervisor',
'ebsOptimized'];
.........
if (isset($configurationItems['configuration'])) {
if (count(array_intersect_ukey($configurationItems['configuration'], array_flip($required_keys), function($a, $b) {
return -1 * ($a < $b) + ($a > $b);
})) === count($required_keys)) {
.....
}
}
bracket was in wrong place used
$cfi = isset($configurationItems["configuration"]) ? $configurationItems["configuration"] : '';`
works a treat
Related
first loop through everything, than if 1 is true do something
So I have this foreach loop that checks if $testsubject is equal to the results from the array. But I want it to check all the results first and if one is true than go further and check the date and else just echo that the voucher is not corect. the purpose of the code is that the user puts in a voucher code which for now is $testsubject than I check if the voucher exists in the system if that is true I check if it is not expired with the date function and then I cut the discount for the price $testamount. image of the echo's https://imagebin.ca/v/3xQuiAClVsAG index.php function display() { $arrContextOptions = [ "ssl" => [ "verify_peer" => false, "verify_peer_name" => false, ], ]; $getVoucherList = "https://www.planyo.com/rest/?method=list_vouchers&api_key=yourkey&resource_id=110556"; $cleanVoucherList = preg_replace("/ /", "%20", $getVoucherList); $voucherlist = file_get_contents("$cleanVoucherList", false, stream_context_create($arrContextOptions)); $voucherList = json_decode($voucherlist, true); $testsubject = "TESTVOUCHER"; $testamount = "5,00"; foreach ($voucherList['data']['results'] as $testVoucher => $testVoucherArr) { if ($testsubject == $testVoucherArr['code']) { echo $testsubject . " is not equal to " . $testVoucherArr['code'] . "<br>"; echo $testVoucherArr['rental_end_date'] . "<br>"; echo $testVoucherArr['discount_value'] . "<br>"; if (date("Y-m-d") <= $testVoucherArr['rental_end_date']) { echo "this code can be used <br>"; echo $testamount - $testVoucherArr['discount_value'] . "<br>"; } else { echo "this code cannot be used"; } ; } else { echo $testsubject . " is not equal to " . $testVoucherArr['code'] . "<br>"; } } } if (isset($_POST['submit'])) { display(); }
Would this work for you? If the code is valid, then you enter a function which checks the date. After the function has ended, the foreach loop will end by using "break;" function testVoucherDate($voucher) { if (date("Y-m-d") <= $testVoucherArr['rental_end_date']) { echo "this code can be used <br>"; echo $testamount - $testVoucherArr['discount_value'] . "<br>"; } else { echo "this code cannot be used"; }; } foreach ($voucherList['data']['results'] as $testVoucher => $testVoucherArr) { if ($testsubject == $testVoucherArr['code']) { echo $testsubject . " is not equal to " . $testVoucherArr['code'] . "<br>"; echo $testVoucherArr['rental_end_date'] . "<br>"; echo $testVoucherArr['discount_value'] . "<br>"; testVoucherDate($testVoucherArr); break; } else { echo $testsubject . " is not equal to " . $testVoucherArr['code'] . "<br>"; } } EDIT: I've put the function above the loop, so no errors of undefined functions will occur
First set a flag to true, then loop setting the flag to false if there is an error. Then test the flag: $flag = true; // SET A FLAG foreach($a as $b){ if($b !== 'Hello')$flag = false; // IF contidtion not met, set flag to true } if($flag === false){ // TEST IF flag result echo 'Dear oh dear';die; } foreach(....){ // GO ON if flag === true .... }
How to check if an array is empty in PHP(Codeigniter)
Here it's my sample of code : public function show($imei,$start_time,$end_time,$dateto) { $from_time = str_replace('-','/',$start_time); $fromi=strtotime($from_time . ' ' . $end_time); $too1=strtotime($from_time . ' ' . $dateto); $data['coordinates'] = $this->road_model->get_coordinatesudhetime($imei, $fromi, $too1); $this->load->view('road/show', $data); if (!empty($data)) { echo 'Array it's empty*'; } } I want to check when $data it's empty .
if (empty($data)) { echo "array is empty"; } else { echo "not empty"; } or count($data) returns the size of array.
You can do this way also if(is_array($data) && count($data)>0) { echo "not empty"; }else{ echo "empty"; }
How to store each word in a string into specific variables?
Please help me to put these words of string into some specific variables. $remove4 = "First 1st, Second 2nd, Third 3rd, Fourth 4th"; i'm using this code, but i can get it right. can somebody tell me what is the problem in my code? $str = (explode(",",$remove4)); $check = array(); for($i=0;$i<=$count;$i++){ $check[] = $str[$i]; } foreach($check as $value){ echo $value . "<br>"; $var=(explode(" ", $value)); echo $var[0]; echo $var[1]; } Goal: Process1 = 'First'; Process2 = 'Second'; Process3 = 'Third'; Process4 = 'Fourth'; Temp1 = '1st'; Temp2 = '2nd'; Temp3 = '3rd'; Temp4 = '4th';
$remove4 = "First 1st, Second 2nd, Third 3rd, Fourth 4th"; $str = (explode(",",$remove4)); $check = array(); $i=0; foreach ($str as $value) { $i++; $explode = (array_values(array_filter(explode(" ",$value)))); ${'Process'.($i)} = $explode[0]; ${'Temp'.($i)} = $explode[1]; } echo $Process1 . "<br /> "; echo $Process2 . "<br /> "; echo $Process3 . "<br /> "; echo $Process4 . "<br /> "; echo $Temp1 . "<br /> "; echo $Temp2 . "<br /> "; echo $Temp3 . "<br /> "; echo $Temp4 . "<br /> "; Output : First Second Third Fourth 1st 2nd 3rd 4th
you can try this foreach($check as $key => $value){ //echo $value . "<br>"; $var=(explode(" ", $value)); ${'Process'.($key+1)} = $var[0]; ${'Temp'.($key+1)} = $var[1]; } echo $Process1; echo $Temp3;
If condition not checking the condition
function pokemon2() { include 'details.php'; $damage = $_POST['attack']; $oppo_health = $_SESSION['oppo_health']; if($oppo_health < 0) { echo "Died!"; } else { $oppo_path = $_SESSION['path']; echo "<br />"; echo $oppo_path; echo "<br />"; $oppo_health = $oppo_health - $damage; echo $oppo_health; $_SESSION['attack'] = $damage; $_SESSION['oppo_health'] = $oppo_health; } } The code should display 'Died' if the $oppo_health goes below 0! But its not happening as it should?? The logic is correct and no errors shown.
You need to start a session by using session_start() method.
Looping through every record from database
I've searched on the internet for this, and questions here on SO but mostly are using something else than PHP. So i will ask my own question. What i need to do is make a button that will print out (read literally print, as in downloading a word document with all details on it) every record from the database. The ID is named 'abstract_id'. What i'm going to show you next is the print button from all pages, what i mean by this is if you click on said button it will print everything from that specific page: $abstract_id = addslashes($_POST['abstract_id']); //Here i connect to the database// $query = "SELECT * FROM abstracts WHERE abstract_id = '$abstract_id'"; $result = mysql_query($query); $i = 0; $title = mysql_result($result,$i,"title"); $author[1] = mysql_result($result,$i,"author1"); $organization[1] = mysql_result($result,$i,"organization1"); $author[2] = mysql_result($result,$i,"author2"); $organization[2] = mysql_result($result,$i,"organization2"); $author[3] = mysql_result($result,$i,"author3"); $organization[3] = mysql_result($result,$i,"organization3"); $author[4] = mysql_result($result,$i,"author4"); $organization[4] = mysql_result($result,$i,"organization4"); $author[5] = mysql_result($result,$i,"author5"); $organization[5] = mysql_result($result,$i,"organization5"); $author[6] = mysql_result($result,$i,"author6"); $organization[6] = mysql_result($result,$i,"organization6"); $format = mysql_result($result,$i,"format"); $language = mysql_result($result,$i,"language"); $presenter = mysql_result($result,$i,"presenter"); $background = mysql_result($result,$i,"background"); $purpose = mysql_result($result,$i,"purpose"); $methods = mysql_result($result,$i,"methods"); $findings = mysql_result($result,$i,"findings"); $conclusion = mysql_result($result,$i,"conclusion"); $word_count = mysql_result($result,$i,"word_count"); $name = mysql_result($result,$i,"name"); $email1 = mysql_result($result,$i,"email1"); $email2 = mysql_result($result,$i,"email2"); $phone1 = mysql_result($result,$i,"phone1"); $phone2 = mysql_result($result,$i,"phone2"); $fax = mysql_result($result,$i,"fax"); $address = mysql_result($result,$i,"address"); $country = mysql_result($result,$i,"country"); $topic = mysql_result($result,$i,"topic"); $master_status = mysql_result($result, $i, "master_status"); $last_edit = mysql_result($result,$i,"last_edit"); header("Content-type: application/vnd.ms-word"); header("Content-Disposition: attachment;Filename=abstract_" . $abstract_id . ".doc"); echo "<html>"; echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">"; echo "<body>"; echo "<p><b>PCNE Abstract</b> $abstract_id</p>"; echo "<h1>$title</h1>"; echo "<b>"; for ($i = 1; $i<= 6; $i++) { echo ((!empty($author[$i-1]) && !empty($author[$i])) ? ", " : "") ; echo ((!empty($author[$i])) ? $author[$i] . "<sup>" . $i . "</sup>" : "") ; } echo ".</b>"; echo "<br>"; for ($i = 1; $i<= 6; $i++) { if (!empty($author[$i])) { echo (!empty($organization[$i]) && !empty($organization[$i-1])) ? ". " : ""; echo ((!empty($organization[$i])) ? "<sup>" . $i . "</sup>" . $organization[$i]: "") ; } } echo (!empty($email1)) ? " (" . $email1 . ")" : ""; echo "<br>"; echo "<br>"; echo "<b>Background</b> "; echo "$background<br>"; echo "<b>Purpose</b> "; echo "$purpose<br>"; echo "<b>Method</b> "; echo "$methods<br>"; echo "<b>Findings</b> "; echo "$findings<br>"; echo "<b>Conclusion</b> "; echo "$conclusion<br>"; echo "</body>"; echo "</html>"; Now, this works fine, but i need a same working button which does almost the same, but instead of printing out 1 record it should print all. So all i basically need is a foreach or while loop that goes through every abstract_id. It's been ages since i last programmed php, so i appreciate any help! If you need any clarification, feel free to ask.
First you don't need your 30 lines of mysql_result, just use mysql_fetch_assoc to get all values in associative array. Then you just have to do a while ( $line = mysql_fetch_assoc($query) ), see above : header("Content-type: application/vnd.ms-word"); header("Content-Disposition: attachment;Filename=abstract_all.doc"); echo "<html>"; echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">"; echo "<body>"; $query = mysql_query("SELECT * FROM abstracts WHERE 1") or die(mysql_error()) ; while ( $line = mysql_fetch_assoc($query) ) { echo "<p><b>PCNE Abstract</b>".$line['abstract_id']."</p>"; echo "<h1>".$line['title']."</h1>"; $authors = Array() ; for ($i = 1 ; $i <= 6 ; $i++ ) if ( isset($line['author'.$i]) && $line['author'.$i] != '' ) $authors[] = $line['author'.$i].' <sup>'.$i.'</sup>' ; echo '<b>'.implode(', ',$authors).'</b>' ; $organizations = Array() ; for ($i = 1; $i<= 6; $i++) { if ( ! isset($line['author'.$i]) || $line['author'.$i] == '' ) continue ; // Check if there is an author, if no go to next loop if ( isset($line['organization'.$i]) && $line['organization'.$i] != '' ) $organizations[] = ' <sup>'.$i.'</sup> '.$line['organization'.$i] ; } echo '<b>'.implode(', ',$organizations).'</b>' ; echo "<b>Background</b> "; echo $line['background']."<br>"; echo "<b>Purpose</b> "; echo $line['purpose']."<br>"; // ... } echo "</body>"; echo "</html>";