SOAP REQUEST on PHP Multidimensional Arrays - php

I'm trying to figure out how to get the right response from Multidimensional array in a SOAP request.
In fact, I would like to be able to Submit a "VAT" number and get the MULTISCORE value
functions.php
<?php
function score ($name)
{
$details=array(
array(
VAT=>"BE0422370068",
COMPANY=>"DEXIA",
MULTISCORE=>25,
CITY=>"HASSELT"
)
/*
array(
VAT=>"BE0402607507",
COMPANY=>"SCANIA",
MULTISCORE=>50,
CITY=>"BRUSSEL"
),
array(
VAT=>"BE0446140711",
COMPANY=>"DELHAIZE",
MULTISCORE=>50,
CITY=>"GENT"
)
*/
);
foreach($details as $va=>$var) //BTW
{
foreach($va as $co=>$cor) //COMPANY
{
foreach($co as $mu=$mur) //MULTISCORE
{
foreach($mu as $ci=<$cir) //CITY
{
if($name==$va) //If VAT exist
$score=$mur; //Show MULTISCORE value
}
}
}
}
return $score;
}
?>
These functions are called from following PHP request
Client.php
<?php
require 'lib/nusoap.php';
$client = new nusoap_client("http://localhost:8080/service.php?wsdl");
if (isset($_POST["cia"]))
{
$cia_name = $_POST["cia"];
}
if (!isset($_POST['submit'])) {
?>
<html>
<head>
<title>Scania Finance GRAYDON</title>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Company: <input type="text" size="12" maxlength="12" name="cia"><br /><br />
<input type="submit" value="submit" name="submit">
</form>
<?php
} else {
$response = $client->call('score',array("name"=>"$cia_name"));
if (empty($response))
echo "Please go <b>'Back'</b> and enter Company name";
else
echo "GRAYDON - MultiScore of Company $cia_name is equal to <b>".$response."</b></br></br>";
if ($response < '30'){
echo "SORRY, Graydon MultiScore is less than 30!";
} elseif ($response < '60'){
echo "CAN BE DISCUSSED, Graydon MultiScore is between 30 and 60, the visit of a Financial Salesman is needed!";
} else {
echo "GREAT, Graydon MultiScore is greater than 60, we can do Business together!";
}
}
?>
</body>
I can't find the way to call the right Array values.

You need to do two things.
1) in your function.php file write this line:-
$score = $details[$key];
return $score;
2) In your client.php file
$response is now Array so you need to print it via
print_r($response);
Now you can get MULTISCORE by $response['MULTISCORE'] and COMPANY NAME by $response['COMPANY'];
Note:- You wrote echo $response so you got only "Array" print.
Suggestion:- You should ON Error Reporting in developement mode otherwise you cannot debug code properly.
Write this line as:-
echo "GRAYDON - MultiScore of VAT ".$vat_num." is equal to <b>".$response['MULTISCORE']."</b></br></br>";
check new condion like this:-
if($response['MULTISCORE'] < '30'){
// your code
}
if you want company name then,
print company name:-
echo $response['COMPANY'];

You don't need to run foreach loop in this case. If you simply want MULTISCORE by submitting VAT value then it is very easy by below way:
refer array_search and array_column
function score ($name)
{
$details=array(
array(
'VAT'=>"BE0422370068",
'COMPANY'=>"DEXIA",
'MULTISCORE'=>25,
'CITY'=>"HASSELT"
)
/*
array(
'VAT'=>"BE0402607507",
COMPANY=>"SCANIA",
MULTISCORE=>50,
CITY=>"BRUSSEL"
),
array(
VAT=>"BE0446140711",
COMPANY=>"DELHAIZE",
MULTISCORE=>50,
CITY=>"GENT"
)
*/
);
$key = array_search($name, array_column($details, 'VAT'));
// $key = array_search('BE0402607507', array_column($details, 'VAT'));
$score = $details[$key]['MULTISCORE'];
return $score;
}
if you want all array values by submitting VAT then you need to write following line:-
$score = $details[$key];
return $score;
Now you will get company name by echo $score['COMPANY']; and multiscore by echo $score['MULTISCORE'];
Hope this will help you :)

Ok, anyway, I can't get it. As already said, tried several options as you asked but can't get the value only returns "Array".
For people are looking for how to retrieve one value of a multidimensional array using a SOAP request, to test it use XAMPP, here my work files on a PHPSOAP.zip
workfiles:
https://drive.google.com/file/d/0B-pCOHYZNf6COFNLdFV5RkpITGM/view?usp=sharing
Ravi Hirani thank you for your help!

Related

PHP Multiple Input Text and Input File Array

I have the following code Multiple text and type File Using an array to upload file and Text.
in this code, if I remove type file this code is working. but after use file is not work
Here is the Form
<form method="post" enctype="multipart/form-data">
<?php
$data_array = array('text','text2','file','file2');
foreach($data_array as $data_name){ ?>
<input type="hidden" name="data_name[]" value="<?php echo $data_name; ?>">
<?php if(strpos($data_name,'text') !== false){ ?>
<input name="data_value[]" type="text" />
<?php }
if(strpos($data_name,'file') !== false){ ?>
<input name="data_value[]" type="file" /> <?php }
} ?>
<input type="submit" name="submit" value="Add" />
</form>
Here is The Php Code, I Think More Improvement on $_FILE Part
if(isset($_POST['submit'])){
if(isset($_FILES['data_name'])){
foreach(array_combine($_FILES['data_name'],$_POST['data_value']) as $dataname => $datavalue){
$file_name = $_FILES['data_name']['name'];
echo file_name;
}
}
if(isset($_POST['data_name'])){
foreach(array_combine($_POST['data_name'],$_POST['data_value']) as $dataname => $datavalue){
echo $dataname.' - '.$datavalue;
}
}
}
Here is The Error of File..
Warning: array_combine(): Both parameters should have an equal number
of elements in pagename.php on line 25
Warning: Invalid argument supplied for foreach() in pagename.php on line 25
I Need Output Like This -
text = value
text2 = value2
file = file.jpg
file2 = file2.jpg
As stated explicitly in the error message, $_FILES['data_name'] and $_POST['data_value' are not the same size. (And I'm pretty sure the foreach is failing because the array_combine failed).
That is explained by you here: "if I remove type file this code is working. but after use file is not work".
If you want to use array_combine(), the arrays must be of the same size.
If you add a filter (eg if(strpos($data_name,'file') !== false)) the potential exists that the arrays will not match (as this problem indicates).
One approach would be to filter out the "data_name[]" inputs with the same condition as the "data_value[]" inputs.
Or the other way round: add an else on the above mentioned if that produces <input name="data_value[]" type="hidden" /> (notice the type). This will ensure the arrays are the same size. You will have to figure out what to do with these "dummy" inputs in the php code. Perhaps give them a value (like value="dummy") that you can test on.
replace your php-code with this:
function get_names_for_entity($name, $arr)
{
if (!empty($arr)) {
$ret = array_values(
array_filter(
$arr,
function ($itm) use ($name) {
return strpos($itm, $name) !== false;
}
)
);
} else {
$ret = [];
}
return $ret;
}
$names_a = [
'file' => get_names_for_entity('file', $_POST['data_name']),
'text' => get_names_for_entity('text', $_POST['data_name'])
];
if (isset($_POST['submit'])) {
if (isset($_POST['data_value'])) {
foreach ($_POST['data_value'] as $dataname_idx => $datavalue) {
echo $names_a['text'][$dataname_idx].' - '.$datavalue;
}
}
if (isset($_FILES['data_value'])) {
foreach ($_FILES['data_value']['name'] as $dataname_idx => $datavalue) {
$file_name = $_FILES['data_value']['name'][$dataname_idx];
echo $names_a['file'][$dataname_idx].' - '.$file_name;
}
}
}

Problem with 'fputcsv' repeating the same variable

Iv been trying to have data from my array variables sent into a .txt file. the variables are working as intended since iv already managed to code in 3 products that a user can choose from, then use a form to submit the quantity and they all individually appear with the movie name and quantity separately. But when i cant seem to figure out a way to fputcsv send the movie names and quantity for each movie separately, i just repeats the last movie and quantity for every line, then when i submit the next movie and quantity it over-rides the last one.
My code for cart page (not showing all the code since most is css, the if/else statements were just me trying desperately to at least get the 2nd movie name out)
<?php
session_start();
?>
<?php
var_dump ($_POST);
if(!isset($_SESSION['cart'])) {
$_SESSION['cart']=[];
}
$cart = &$_SESSION['cart'];
$movieName = $_POST['movie_name'];
$quantity = $_POST['qty'];
if(isset($movieName)) {
$currentQuantity = $cart[$movieName];
$cart[$movieName] = $currentQuantity + $quantity;
} else {
$cart[$movieName] = $quantity;
}
var_dump($_SESSION);
?>
<?php
$list = array
(
"$movieName,$quantity",
"$movieName,$quantity",
"$movieName,$quantity",
);
$file = fopen("orders.txt","w");
foreach ($list as $line)
if ($movieName = 'Game of Thrones: Season 1') {
}
else if ($movieName = 'Friends Season 1') {
}
else if ($movieName = 'Inception') {
}
{
fputcsv($file,explode(',',$line));
}
fclose($file); ?>
one of the forms submitting data:
<form action="cart.php" method="post">
<input type="hidden" name="movie_name" value= "Game of Thrones: Season 1" />
<input type = "hidden" name = "id" value = "M01" />
<br>
<div class="widthc">
<button class="prod" id="minus">−</button>
<input type="number" name="qty" value="0" id="qty" min="0" max="15"/>
<button class="prod" id="plus">+</button>
<br><br>
<button class="prod" type="submit"> Submit</button>
</form>
If there is any other code u want/need to see just let me know and ill edit my post to include it. Thanks for taking the time to read.
So many little things in this code seem wrong or show just a lack of understanding. Some may be due to "sample" code.
Either way, let me go over it in chunks.
<?php
session_start();
?>
<?php
var_dump ($_POST);
Closing and opening a new PHP block is just pointless. This could be due to sample code for the question (or not). Either way it should be just :
<?php
session_start();
// debug
var_dump ($_POST);
Nothing really wrong on the next chunk. Personally I do not like it (ie; create a new var for something that already exists, even with a reference) but each to their own.
if(! isset($_SESSION['cart'])) {
$_SESSION['cart']=[];
}
$cart = &$_SESSION['cart'];
$movieName = $_POST['movie_name'];
$quantity = $_POST['qty'];
This next bit I'm not 100% confident on. You have created $movieName above from the value of $_POST['movie_name']. I believe even if that value is a blank string, your isset() will return true. Either way the result may still work as expect.
if(isset($movieName)) {
$currentQuantity = $cart[$movieName];
$cart[$movieName] = $currentQuantity + $quantity;
} else {
$cart[$movieName] = $quantity;
}
If the lodgic is sound, the following line change would remove a pointless creation of a var.
//$currentQuantity = $cart[$movieName];
$cart[$movieName] += $quantity;
Another close and open PHP block that could be removed
var_dump($_SESSION);
?>
<?php
Now to the real issue. You are creating an array with repeated elements:
$list = array (
"$movieName,$quantity",
"$movieName,$quantity",
"$movieName,$quantity",
);
The above code block would make 3 elements in the array, all with the same values - they would be all identical values of the current $movieName and $quantity.
I think what you really wanted to do was something more like:
foreach($_SESSION['cart'] as $k => $v) {
if ($v > 0) {
$list[] = array($k,$v);
}
}
This next part is interesting due to the errors. The first question is why do you hard-code a variable name?
And then the next question is did you really mean to use = instead of == in the if statement?
$file = fopen("orders.txt","w");
foreach ($list as $line) {
if ($movieName = 'Game of Thrones: Season 1') {
// do nothing? Really?
} else if ($movieName = 'Friends Season 1') {
// do nothing? Really?
} else if ($movieName = 'Inception') {
// do nothing? Really?
}
}
fputcsv($file,explode(',',$line));
fclose($file);
I think what you wanted here was more like:
// To overwrite, use 'w'
$fp = fopen('orders.csv', 'w');
// Or (as noted by Rob) to append to the file, use 'a'
//$fp = fopen('orders.csv', 'a');
// For other options see: http://php.net/manual/en/function.fopen.php
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);

Creating code logic that uses a for loop to cycle through several arrays

I'm trying to create a code logic by using a for loop instead of multiple if statements.
This is the previous if statement code I used before:
if (isset($_POST['answer1']))
{
if ($_POST['answer1'] === '1d')
{
print $correct[0];
}
elseif ($_POST['answer1'] === '1b')
{
print $incorrect[0];
}
elseif ($_POST['answer1'] ==='1c')
{
print $incorrect[0];
}
elseif ($_POST['answer1'] === '1a')
{
print $incorrect[0];
}
};
This code allows me to check for the answer and print either the $correct or $incorrect variable. My issue in this code is that it is very inefficient because I end up having to create ten or so if statements.
I came up with a mock-up of the for loop code to illustrate:
$_SESSION["totalCorrect"] = 0;
if (!isset($_SESSION["totalCorrect"]))
{
$_SESSION["totalCorrect"] = 0;
}
else
{
$totalCorrect = $_SESSION["totalCorrect"];
}
$postAns = array($_POST['answer1'] as $ans1, $_POST['answer2'] as $ans2, $_POST['answer3'] as $ans3, $_POST['answer4'] as $ans4, $_POST['answer5'] as $ans5, $_POST['answer6'] as $ans6,
$_POST['answer7'] as $ans7, $_POST['answer8'] as $ans8, $_POST['answer9'] as $ans9, $_POST['answer10'] as $ans10);
for ($i = 0; $i < count($postAns); i++)
{
if ($i == $postAns[])
{
if ($postAns[] === 'answer')
{
print $correct[];
$_SESSION["totalCorrect"]++;
}
else ()
{
print $incorrect[];
}
}
};
For this code, I have three arrays involved that I am trying to cycle through, $postAns, $correct, and $incorrect. The $correct and $incorrect arrays, when called, print out text depending on whether they got the answer right.
So for the for loop, I want to be able to cycle through each value of the $postAns array to check and and see which answer number it is and whether it is the correct answer or not. If it's correct, then the code cycles through $correct to get the right text for that answer number and increments the value of totalCorrect, the variable that stores how many the user got right. If incorrect, the code cycles through $incorrect to get the right text for that answer number.
I'm not really proficient with loops in general so any insight/help would be greatly appreciated.
EDIT: Included the form submission code
<form action="staff_info.php" method="get" id="q1">
<fieldset>
<legend>Question 1</legend>
<input type="radio" name="answer1" value="1a" id="1a"><label for="1a"> A. </label>
<input type="radio" name="answer1" value="1b" id="1b"><label for="1b"> B. </label>
<input type="radio" name="answer1" value="1c" id="1c"><label for="1c"> C. </label>
<input type="radio" name="answer1" value="1d" id="1d"><label for="1d"> D. </label>
<input type="button" id="answer" class="button " title="abutton" value="ANSWER">
NEXT
</fieldset>
The one thing you're missing in your pseudo code is the actual answers. If you create an array of correct answers as #fefe indicated then the loop will be something like this:
$correctAnswers = array(
'answer1'=>'1d',
'answer2' => '2b',
'answer3' => '3c',
'answer4' => '4b',
'answer5' => '5a'
);
$numberCorrect = 0;
$responseIndex = 0;
foreach ($correctAnswers as $key=>$answer) {
if ($_POST[$key] === $answer) {
$numberCorrect++;
print $correct[$responseIndex];
}
else {
print $incorrect[$responseIndex];
}
$responseIndex++;
}
I don't really know what you trying to achieve but the loop should look something like this and you can make some validation with if or switch case.
$postAns = array(
'answer1'=>'ans1',
'answer2' => 'ans2',
'answer3' => 'ans3',
'answer4' => 'ans4',
'answer5' => 'ans5',
'answer6' => 'ans6',
'answer7' => 'ans7',
'answer8' => 'ans8',
'answer9' => 'ans9',
'answer10' => 'ans9'
);
foreach ($postAns as $key=>$ans) {
var_dump($ans);
}

Instead of submit get data on entering page php

I use this snippet to get vehicle data from a external database:
<form method="post" action="<?php echo $_SERVER['REQUEST_URI'] ?>" class="vwe-kenteken-widget">
<p><input type="text" name="open_data_rdw_kenteken" value="<?php echo $_POST['open_data_rdw_kenteken'] ?>" maxlength="8"></p>
<p><input name="submit" type="submit" id="submit" value="<?php _e('Kenteken opzoeken', 'open_data_rdw') ?>"></p>
</form>
<?php if($data): ?>
<h3><?php _e('Voertuiggegevens', 'open_data_rdw') ?></h3>
<table>
<?php
$categories = array();
foreach ($data as $d) {
if( !is_array($fields) || in_array($d['name'], $fields) ) {
if( !in_array($d['category'], $categories) ) {
$categories[] = $d['category'];
echo '<tr class="open-rdw-header">';
echo '<td colspan="2" style="font-weight: bold;">';
echo ''.$d['category'].'';
echo '</td>';
echo '</tr>';
}
echo '<tr style="display:none">';
echo '<td>'.$d['label'].'</td>';
echo '<td>'.$d['value'].'</td>';
echo '</tr>';
}
}
?>
</table>
<?php endif; ?>
What i want to accomplish is that the data is loaded without the user have to enter a value and hit the submit button. The input value will get loaded based on the product page the user is viewing.
EDIT:
The data is loaded based on:
public function get_json() {
if ( isset( $_POST['kenteken'] ) ) {
$data = $this->rdw->get_formatted($_POST['kenteken']);
foreach ($data as $row) {
$json['result'][$row['name']] = $row['value'];
}
if ($_POST['kenteken']) {
if ($data[0]['value'] == '') {
$json['errors'] = __( 'No license plates found', 'open_data_rdw' );
}
else {
$json['errors'] = false;
}
}
else {
$json['errors'] = __( 'No license plate entered', 'open_data_rdw' );
}
header('Content-type: application/json');
echo json_encode($json);
die();
}
}
So instead of a $_POST action just get the data based on a pre-declared value that is different on each page.
Hard to answer - but I'll try to use my crystal ball.
$data comes from a database query, right?
I assume further, that the query takes the value from the open_data_rdw_kenteken form field to gather $data.
To have the table rendered, you have to fill $data with the right data. That implies that you must have a kind of default value for open_data_rdw_kenteken to get the data out of the DB. The default can be "all" which should reflect on your SQL Query or as your wrote "defined by product page".
Pseudo Code
$data = getData('BT-VP-41');
function getData($open_data_rdw_kenteken="")
{
$where = "";
if(!empty($open_data_rdw_kenteken)) {
$where = 'WHERE rdw_kenteken = "'.mysqli_real_escape_string($open_data_rdw_kenteken)';
}
$data = myslqi->query("SELECT * FROM dbTbl ".$where)
return $data;
}
As I wrote - this is pseudo code and will not run out of the box. You'll have to adapt that to your environment.
TL;DR: The line
<?php if($data): ?>
keeps you from rendering the table. To render you need $data filled with the right data.
Hope that will get you in the right direction.

PHP If / Else statement going directly to the Else without waiting for form input

Ok so I have a form with 1 input and a submit button. Now I am using an if/else statement to make three acceptable answers for that input. Yes, No, or anything else. This if/else is working the thing is the code is kicking out the else function as soon as the page is loaded. I would like there to be nothing there until the user inputs then it would show one of three answers.
Welcome to your Adventure! You awake to the sound of rats scurrying around your dank, dark cell. It takes a minute for your eyes to adjust to your surroundings. In the corner of the room you see what looks like a rusty key.
<br/>
Do you want to pick up the key?<br/>
<?php
//These are the project's variables.
$text2 = 'You take the key and the crumby loaf of bread.<br/>';
$text3 = 'You decide to waste away in misery!<br/>';
$text4 = 'I didnt understand your answer. Please try again.<br/>';
$a = 'yes';
$b = 'no';
// If / Else operators.
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
}
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
?>
<form action="phpgametest.php" method="post">
<input type="text" name="name" /><br>
<input type="submit" name="senddata" /><br>
</form>
You just need to call the code only when the POST value is set. This way it will only execute the code when the form was submitted (aka $_POST['senddata'] is set):
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
}
Just put the validation in the first if statement like this:
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a) {
echo ($text2);
} elseif ($usertypes == $b) {
echo ($text3);
} else {
echo ($text4);
}
}
When you load your page the browser is making a GET request, when you submit your form the browser is making a POST request. You can check what request is made using:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your form was submitted
}
Put this around your form processing code in order to keep it from being executed on GET request.

Categories