first loop through everything, than if 1 is true do something - php

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
....
}

Related

Count the instances where a variable equals TRUE

Working on a quiz website where when users submits their answers $perQuestionScore equals true when the answer is correct but false when it is wrong. I'm trying to find the instances where $perQuestionScore equals true in other to total the score but it doesn't seem to work.
My code looks like below
<?php
$perQuestionScore = 0;
if (isset($_POST['grader'])) {
if(isset($_POST[$chosen]))
{
$choice= $_POST[$chosen];
if (strpos($choice, $correctOne) !== false) {
$perQuestionScore++;
echo $_POST[$chosen] . "" . " is the correct answer";
} elseif (strpos($choice, $correctOne) == false) { echo $_POST[$chosen] . "" . " is the Wrong answer";
} else {
echo "You did not choose an answer"; {
}
}
}
}
}
echo "<input id=grader' type='submit' name='grader' value='Grade Quiz'>" . "</form>";
echo $perQuestionScore * 10;
}
$conn->close();
?>
I suggest simplifying it to this:
<?php
$perQuestionScore = 0; //initialize var
if ($choice == $correct) {
$perQuestionScore++; //add 1 if correct
}
echo $perQuestionScore * 10; //i guess you want it times 10

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";
}

isset method not working returns nothing

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

foreach loop does not work with include

Would someone of you know why I'm not able to use a (long)piece of code within a foreach loop?
The code in the foreach loop is only executed once.
This code at topictweets.php works fine on its own but I want to repeat it for each forum.
The foreach loop works fine without the include. I also tried to have the code from topic tweets.php plainly in the foreach loop, this didn't work either of course.
The code it includes is used to get topics of a forum from the database and find related tweets, and save those in the database.
Is there some other way to do this?
foreach ($forumlist as $x => $fID) {
echo 'id:'.$fID.'<br>';
include 'topictweets.php';
/////////
////////
}
online version: http://oudhollandsedrop.nl/webendata/FeedForum/fetchtweets.php
bunch of code in topic tweets.php
<?php
//?/ VVVV ---- SELECT TOPICS FOR CURRENT FORUM ----- VVVV ////
echo $fID;
$sql = "SELECT Topics_TopicID
FROM Topics_crosstable
WHERE Forums_ForumID = '$fID'";
$result = mysql_query($sql);
if (!$result) {
//echo 'The topiclist could not be displayed, please try again later.';
} else {
if (mysql_num_rows($result) == 0) {
// echo 'This topic doesn′t exist.';
} else {
while ($row = mysql_fetch_assoc($result)) {
//display post data
// echo $row['Topics_TopicID'];
// echo': ';
$topic = "SELECT Name
FROM Topics
WHERE TopicID = " . mysql_real_escape_string($row['Topics_TopicID']);
$topicname = mysql_query($topic);
if (!$topicname) {
// echo 'The topic could not be displayed, please try again later.';
} else {
if (mysql_num_rows($topicname) == 0) {
// echo 'This topic doesn′t exist.';
} else {
while ($row = mysql_fetch_assoc($topicname)) {
//display post data
// echo $row['Name'];
// echo'<br>';
$topiclist[] = $row['Name'];
}
}
}
}
}
}
foreach ($topiclist as $key => $value) {
$terms .= "" . $value . ",";
}
//echo'<p>';
//echo rtrim($terms, ",");
//echo'<p>';
//echo'<p>';
//echo $terms;
//$terms="vintage";
//Twitter account information
$username = "Username";
$password = "Password";
while (true) {
//$terms="vintage";
//echo "search terms: " . substr_replace($terms, "", -1) . "\n";
$url = "https://stream.twitter.com/1/statuses/filter.json";
$cred = sprintf('Authorization: Basic %s', base64_encode("$username:$password"));
$param = "track=" . urlencode(substr_replace($terms, "", -1));
$opts = array(
'http' => array(
'method' => 'POST',
'header' => $cred,
'content' => $param,
'Content-type' => 'application/x-www-form-urlencoded'),
'ssl' => array('verify_peer' => false)
);
$ctx = stream_context_create($opts);
$handle = fopen($url, 'r', false, $ctx);
//var_dump($handle);
$content = "";
$flag = true;
while ($flag) {
$buffer = fread($handle, 100);
//$buffer = stream_get_line($handle, 1024, "\n");
$a = explode("\n", $buffer, 2);
$content = $content . $a[0];
#var_dump($a);
if (count($a) > 1) {
#echo $content;
#echo "\n";
$r = json_decode($content, true);
#var_dump($r);
// echo '<p>';
// echo "text: " . $r["text"];
// echo '<br>';
// echo "\nrceated_at: " . $r["created_at"];
// echo '<br>';
// echo "\nuser screen name: " . $r["user"]["screen_name"];
// echo '<br>';
// echo "\nuser id: " . $r["user"]["id"];
// echo '<br>';
// echo "\nid : " . $r["id"];
// echo '<br>';
// echo "\nin_reply_to_status_id: " . $r["in_reply_to_status_id"];
// echo '<p>';
// echo "\n\n";
$created_at = $r["created_at"];
$created_at = strtotime($created_at);
$mysqldate = date('Y-m-d H:i:s', $created_at);
//
// echo'<p>';
foreach ($topiclist as $key => $value) {
// echo'getshere!';
//$whichterm = $r["text"];
$whichterm = '"' . $r["text"] . '"';
//echo $whichterm;
if (stripos($whichterm, $value) !== false) {
// echo 'true:' . $value . '';
//find topicid
$whattopic = "SELECT TopicID
FROM Topics
WHERE Name = '$value'";
//var_dump($whattopic);
$tID = mysql_query($whattopic);
//var_dump($tID);
if (!$tID) {
// echo 'topic id not found.';
} else {
if (mysql_num_rows($tID) == 0) {
// echo 'This topic doesn′t exist.';
} else {
while ($rec = mysql_fetch_assoc($tID)) {
$inserttweets = "INSERT INTO
Tweets(Topics_TopicID, AddDate, Tweetcontent)
VALUES('" . mysql_real_escape_string($rec['TopicID']) . "',
'" . mysql_real_escape_string($mysqldate) . "',
'" . mysql_real_escape_string($r["text"]) . "')";
//WHERE TopicID = " . mysql_real_escape_string($row['Topics_TopicID'])
}
}
$addtweet = mysql_query($inserttweets);
if (!$addtweet) {
//something went wrong, display the error
//echo 'Something went wrong while adding tweet.';
//echo mysql_error(); //debugging purposes, uncomment when needed
} else {
echo 'Succesfully added tweet';
}
}
}
}
die();
$content = $a[1];
}
}
fclose($handle);
}
?>
"Pasting" a bunch of code inside a loop isn't a great practice. In fact, what you're looking for is a function or the use of a defined class. So, if you can, define a function in your topictweets.php that will contain your code and use it in your loop:
include 'topictweets.php';
foreach ($forumlist as $x => $fID) {
echo 'id:'.$fID.'<br>';
processYourForums($fID);
/////////
////////
}
try include_once()
however, why not have a loop within topictweets.php?
you can do the query, etc.. in this page, but then loop through it in the include
This should work fine:
include 'topictweets.php';
foreach ($forumlist as $x => $fID) {
echo 'id:'.$fID.'<br>';
}
You only need to include once.

php: echo an error message

code :
$searchText = '3423, 2453, 3245 , 2425, 6765';
$numbers = str_replace(", ", ",", $searchText);
$code = explode(",", $numbers);
if ( (preg_match("/[^0-9]/i"), $code) || (strlen($code) != 4) ) {
$searchingError= 'Can not cantain string and more than 4 digists number!';
echo '<script type="text/javascript">';
echo "alert('" . $searchingError . "')";
echo "</script>";
}
function validate ($a) {
if (ctype_digit($a) && (strlen($a) == 4)) {
return "'$a'" ;
} else {
//$searchingError= 'Can not cantain string and more than 4 digists number!';
//echo '<script type="text/javascript">';
//echo "alert('" . $searchingError . "')";
//echo "</script>";
}
}
$parsed = array_map( "validate",$code);
print_r($parsed);
$code = '(' . preg_replace('/\,+/', ',',implode(',', $parsed)) . ')';
echo '<br />' . $code;
In this code, is there a way to identify $searchText have only 4 digits numbers or it contain string etc. If it's so, I want to echo an error message.
Thanks for any comments.
Check if $code is a text using is_int and the length of each number using strlen();
in an if statement:
if (is_int($code)) {
if (strlen($num1) = 4 && strlen($num2) ...) {
//code here
}
else
echo "Error.";
}
else
echo "The search is text";
This will work to verify that they are digits only and 4 characters only...
//is not digits or //is not 4 characters in length
if ( (preg_match("/[^0-9]/i"), $code) || (strlen($code) != 4) ) {alert error...}
GOT IT!
<?php
$a = "4444 , 111X , 565656, 4444";
$a = str_replace(" ", "", $a);
$b = explode(",",$a);
function validate($v){
if ((strlen($v)!=4)||(preg_match("/[^0-9]/i", $v))) { echo 'error<br/>'; }else{ echo 'success<br/>'; };
}
array_filter($b,"validate");
echo 'complete';
?>

Categories