I echoed this and fetched in ajax .
$result= $this->mpesa->STKPushQuery($checkoutRequestID, 174379, "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919");
The results am getting in json is:
{"requestId":"","errorCode":"400.002.02","errorMessage":"Bad Request - Invalid CheckoutRequestID"}
Now in my php code I need to get the Keys of errorCode that sometimes is a successCode so when I try this:
if ($result->errorCode=="400.002.02"){
$Data = '{"status":"Submit payment before Checking for it"}';
echo $Data;
Its fine because the errorCode is found in Json. When there is a success message i.e:
if ($result->successCode=="0"){
$Data = '{"status":"Payment Successful"}';
echo $Data;
}
I get an error with the first statement. Because errorCode is not found in Json
So what I actually need is to get the key of json(which will be either errorCode or successCode)
i.e
$mystatusCode== Get the either the errorCode or SuccessCode (key in Json array[1])
if ($results->mystatusCode=="400.002.02"){
$Data = '{"status":"Submit payment before Checking for it"}';
echo $Data;
}else if ($results->mystatusCode=="0"){
$Data = '{"status":"Payment has been processed successfully"}';
echo $Data;
}
Using isset will accomplish your goal:
$mystatusCode = ( isset($result->errorCode) ? $result->errorCode :
( isset($result->successCode) ? $result->successCode :
NULL
)
);
Or you can just use it in the if statements directly without making a new single var:
if (isset($result->errorCode) && $result->errorCode == "400.002.02") {
...
}
elseif (isset($result->successCode) && $result->successCode == "0") {
...
}
Related
I am receiving post values. I want a suggestion for logic to handle empty or not set post values.
Is there such a way if one of them receives empty post, the $Data array should not receive anymore values and make it empty. In other words, i am trying to immitate the try and catch feature. If on any POST is empty, ignore reading the rest of POST and make that array as empty
Is my second draft considred valid?
First draft
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTYPE"]))){
$DATA["SHOWSCHEDULE_SHOWTYPE"] = $_POST["SHOWSCHEDULE_SHOWTYPE"];
}
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTITLE"]))){
$DATA["SHOWSCHEDULE_SHOWTITLE"] = $_POST["SHOWSCHEDULE_SHOWTITLE"];
}
if(empty($DATA)){
//do something
}else{
//do something else
}
Second draft
try{
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTITLE"]))){
$DATA["SHOWTITLE"] = $_POST["SHOWSCHEDULE_SHOWTITLE"];
}else{
throw new Exception('POST SHOWSCHEDULE_SHOWTITLE');
}
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTYPE"]))){
$DATA["SHOWTYPE"] = $_POST["SHOWSCHEDULE_SHOWTYPE"];
}else{
throw new Exception('POST SHOWSCHEDULE_SHOWTYPE');
}
} catch (Exception $e) {
echo 'ERROR: ', $e->getMessage(), "\n";
unset($DATA);
}
You can use one if statement with all required POST parameters.
if(!empty($_POST['var1']) && !empty($_POST['var2']) && !empty($_POST['var3']) && !empty($_POST['var4'])):
/*and then assign all the POST values to a $DATA array as you want.*/
$DATA['var1'] = $_POST['var1'];
$DATA['var2'] = $_POST['var2'];/* and so on..*/
endif;
I personally prefer to white list values that I loop through and assign.
<?php
$valid_keys = ['SHOWSCHEDULE_SHOWTYPE', 'SHOWSCHEDULE_SHOWTITLE'];
$at_least_one_empty = false;
foreach($valid_keys as $data_key)
{
$data[$data_key] = isset($_POST[$data_key])
? trim($_POST[$data_key]) // Remove accidental user whitespace.
: ''; // If unsubmitted - set to empty string.
if($data[$data_key] === '')
$at_least_one_empty = true;
}
if($at_least_one_empty) {
unset($data);
} else {
process($data);
}
Note with the sample code above an unsubmitted value will be assigned the empty string. This might not be the behaviour you want.
However if you just want to assign and check you received all inputs this might do (no filtering or validation):
<?php
$valid_keys = ['SHOWSCHEDULE_SHOWTYPE', 'SHOWSCHEDULE_SHOWTITLE'];
foreach($valid_keys as $data_key)
$data[$data_key] = $_POST[$data_key] ?? null;
$not_all_received = in_array(null, $data, true);
Im writing a page in HTML/PHP that connects to a Marina Database(boats,owners etc...) that takes a boat name chosen from a drop down list and then displays all the service that boat has had done on it.
here is my relevant code...
if(isset($_POST['form1'])){//if there was input data submitted
$form1 = $_POST['form1'];
$sql1 = 'select Status from ServiceRequest,MarinaSlip where MarinaSlip.SlipID = ServiceRequest.SlipID and BoatName = "'.$form1.'"';
$form1 = null;
$result1 = $conn->query($sql1);
$test = 0;
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$values1[] = array(
'Status' => $row['Status']
);
$test = 1;
}
echo '<p>Service Done:</p><ol>';
if($test = 1){
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
echo '</ol>';
}else{
echo 'No service Done';
}
the issue im having is that some of the descriptions of sevice are simply Open which i do not want displayed as service done, or there is no service completed at all, which throws undefined variable: values1
how would I stop my script from adding Open to the values1 array and display a message that no work has been completed if values1 is empty?
Try this
$arr = array();
if (empty($arr))
{
echo'empty array';
}
We often use empty($array_name) to check whether it is empty or not
<?php
if(!empty($array_name))
{
//not empty
}
else
{
//empty
}
there is also another way we can double sure about is using count() function
if(count($array_name) > 0)
{
//not empty
}
else
{
//empty
}
?>
To make sure an array is empty you can use count() and empty() both. but count() is slightly slower than empty().count() returns the number of element present in an array.
$arr=array();
if(count($arr)==0){
//your code here
}
try this
if(isset($array_name) && !empty($array_name))
{
//not empty
}
You can try this-
if (empty($somelist)) {
// list is empty.
}
I often use empty($arr) to do it.
Try this instead:
if (!$values1) {
echo "No work has been completed";
} else {
//Do staffs here
}
I think what you need is to check if $values1 exists so try using isset() to do that and there is no need to use the $test var:
if(isset($values1))
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
Or try to define $values1 before the while:
$values1 = array();
then check if it's not empty:
if($values1 != '')
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
All you have to do is get the boolean value of
empty($array). It will return false if the array is empty.
You could use empty($varName) for multiple uses.
For more reference : http://php.net/manual/en/function.empty.php
I'm writing a script to make an api call and add credit card to a billing system
<?php
include 'class.hbwrapper.php';
HBWrapper::setAPI('http://my-site.com/admin/api.php','API ID','API Key');
$params = array(
'id'=>ID,
'cardnum'=>CARDNUM,
'cardtype'=>CARDTYPE,
'expiryyear'=>EXPIRYYEAR,
'expirymonth'=>EXPIRYMONTH
);
$return = HBWrapper::singleton()->editClientCreditCard($params);
print_r($return);
?>
Here is the response
{
"success": true,
"call": "editClientCreditCard",
"server_time": 1317726229,
"info": [
"Credit Card details updated"
]
}
How can I write an if statement to check the value of returned success value if it is either true or false in php?
in another question, should I be looking at php to do this? or use jquery?
Thank you
Depending on your PHP version:
For an object:
if(json_decode($return)->success === true)
For an array:
if(json_decode($return, true)['success'] === true)
For older PHP or if you need the entire object/array decoded:
$result = json_decode($return);
if($result->success === true)
Like this;
$data = json_decode($return);
if($data['success'] === true) {
//true
} else {
//false
}
You can use json_decode to transform the JSON response to a php variable. Then you can check the response.
For further information look at the PHP manual http://php.net/manual/de/function.json-decode.php
$data=json_decode($your_json_string);
if($data->success){
...
}
you can do it like this .
$return = json_decode($return);
if($return->success){
// true
echo "TRUE";
} else {
// false
echo "FALSE";
}
I want to check two arrays. If the value of one array anybody equal then $response:1 and otherwise for $response:0
example arrays:
{"data_comment":[{"name":"a"},{"address":"b"},{"age":"16"}]}
{"data_comment2":[{"name":"b"},{"address":"e"},{"age":"18"}]}
file php :
if($data_comment==$data_comment2){
$response2["success"] = "1";
// echoing JSON response
echo json_encode($response2);
} else {
$response2["success"] = "0";
$response2["message"] = "Error";
// echoing JSON response
echo json_encode($response2)
}
so , if any value of data_comment is same with data_comment2 value, then result will be false [$response2["success"] = "0"; ]..
but with my code, result always show [$response2["success"] = "1"; ] , there's is not same value at all between data_comment and data_comment2 .
thanks for any advice
$_GET['numberofwelds']; & $_GET['numberofconwelds']; are sent to this script using GET JSON. I want to add these together, and then use json_encode to send a total back to the callback (in another php script) . If both $_GET 's are empty, then I want nothing to happen. How should I change this?
$numberofwelds = $_GET['numberofwelds'];
$numberofconwelds = $_GET['numberofconwelds'];
if (isset($_GET['numberofwelds']) && $_GET['numberofwelds'] != '' {
$numberofwelds + $numberofconwelds = $sum_total;
echo json_encode($sumtotal);
} else {
exit()
}
Firstly, you are trying to access your $_GET variables without checking they exist first.
Secondly, you should be throwing Exceptions instead of just calling exit() or die(). You can then log them with $e->getMessage() or write them to the local filesystem.
Finally, you need to validate your data. Make sure it is what you expect it to be.
if (isset($_GET['numberofwelds']) && isset($_GET['numberofconwelds']))
{
// Now we know both values definitely exist, VALIDATE them
$numwelds = $_GET['numberofwelds'];
$numconwelds = $_GET['numberofconwelds'];
if (is_int($numwelds) && is_int($numconwelds))
{
// Calculate your total
$total = $numwelds + $numconwelds;
echo json_encode($total);
}
else
{
// We get here because your GET variables do exist but they aren't
// numbers as you expect (you or someone else has sent rubbish data)
// You want to do nothing, although I would return an error in your json
// to be displayed to the user or logged by the consumer of the service
}
}
else
{
// We get here because your GET variables simply don't exist. They haven't been
// passed in as you are expecting them to be
// You want to do nothing, although I would return an error in your json
// to be displayed to the user or logged by the consumer of the service
}
Always code defensively.
I'm going to show you what I would do in this situation.
if (isset($_GET['numberofwelds']) && isset($_GET['numberofconwelds']))
{
$numwelds = $_GET['numberofwelds'];
$numconwelds = $_GET['numberofconwelds'];
if (is_int($numwelds) && is_int($numconwelds))
{
$total = $numwelds + $numconwelds;
$response = array("status" => "success", "message" => $total);
echo $response;
}
else
{
$response = array("status" => "failure", "message" => "GET params were not numbers");
echo $response;
}
}
else
{
$response = array("status" => "failure", "message" => "GET params do not exist");
echo $response;
}
Then, in your consuming service (most likely a JavaScript / jQuery AJAX call), you can do the following:
.done(function(data) {
var json = $.parseJSON(data);
if (data.status === "success") {
// Yay, we got a success back
console.log("The total is: " + data.message);
} else if (data.status === "failure") {
// Uh oh, something's gone wrong server-side
console.log(data.message);
}
});
change this
if ($_GET['numberofwelds'] != '' && $_GET['numberofconwelds'] != '') {
$numberofwelds + $numberofconwelds = $sum_total;
echo json_encode($sumtotal);
} else {
exit()
}
to this
if ($numberofwelds && $numberofconwelds ) {
$sum_total = array(
'sumTotal' => $numberofwelds + $numberofconwelds,
);
echo json_encode($sum_total);
}else {
exit();
}
Please always check existence of the array keys with isset() construction or array_key_exists() function.
if (isset($_GET['numberofwelds']) && $_GET['numberofwelds'] != '' && isset($_GET['numberofconwelds']) && $_GET['numberofconwelds'] != '') {
echo json_encode(array("total" => $_GET['numberofwelds'] + $_GET['numberofconwelds']));
} else {
exit();
}
UPDATE
With is_numeric() function this code should be more robust:
if (isset($_GET['numberofwelds']) && is_numeric($_GET['numberofwelds']) && isset($_GET['numberofconwelds']) && is_numeric($_GET['numberofconwelds'])) {
echo json_encode(array("total" => $_GET['numberofwelds'] + $_GET['numberofconwelds']));
} else {
exit();
}
PHP reference: array_key_exists()
PHP reference: isset()
$numberofwelds = json_decode($_GET['numberofwelds'], true);
$numberofconwelds = json_decode($_GET['numberofconwelds'], true);
$mergedJson = array_merge(numberofwelds, numberofconwelds);
echo json_encode($mergedJson);
This should do it. It grabs the json, decodes and turns it in to an array (second parameter of json_decode set to true) and then combines them.