Problem with 'fputcsv' repeating the same variable - php

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);

Related

PHP - Updating form data. (on same page)

I need to be able to update my form data once the submit button is pressed on the same page.
I have a csv file. And at the moment, I have worked out how to edit data inside it, and save it in the csv file (through a form).
-(I have attached the main code below, but even any suggestions would be helpful)
The form and php execution is on the same page, but once the user edits the values and presses submit, the data goes back to the original data. So it updates in the csv file, but not in the form.
This is the form:
for ($i=0; $i<200; $i++) {
if(empty($SearchResults[$i][0]) == false){ //If its full
?>
<form method="post" action="">
Full Name: <input name = "Name2" type="text" value="<?php echo $SearchResults[$i][0] ?>"/>
Weight (kg): <input name="Weight2" type="number" value="<?php echo $SearchResults[$i][1] ?>"/>
Weight of belongings (kg): <input name="WeightOfBelongings2" type="number"value="<?php echo $SearchResults[$i][2] ?>"/>
<input name="submit" type="submit" />
</form>
<?php
$i++;
}else if (empty($SearchResults[$i][0]) == true){ //If it is empty
$i =201;
}
}
This is what happens when the submit button is pressed:
if (isset($_POST['submit'])) {
$FullName = $_POST['Name2'];
$Weight = $_POST['Weight2'];
$WeightOfBelongings = $_POST['WeightOfBelongings2'];
//Creates a new felon from the class in felen.php and assigns it to this variable $Felon
$Felen = new felen;
//This refers to a function in the class Felen. From this information it calculates the costs, ammounts etc. And saves it to a variable that can be called.
$Felen -> CreateFelen($FullName, $Weight, $WeightOfBelongings);
//This is a for loop that checks when there is an avaliable line to put the data into.
if ($FullName != "") {
$i = 0;
for ($i=0; $i<200; $i++) {
if(empty($csv[$i][0]) == false){ //If its full
if($csv[$i][0] == $_POST['Name2']){
//its only printing it if it is in the first row?
$csv[$i][0] = $FullName;
$csv[$i][1] = $Weight;
$csv[$i][2] = $WeightOfBelongings;
$csv[$i][3] = $Felen->FelenTotalWeight;
$csv[$i][4] = $Felen->UnassembliumRequired;
$csv[$i][5] = $Felen->ReassembliumRequired;
$csv[$i][6] = $Felen->CostOfUnassemblium;
$csv[$i][7] = $Felen->CostOfReassemblium;
$csv[$i][8] = $Felen->TotalCostOfJourney;
$i = 201;
}
}
}
//Saves the previous data and new changes to the csv file
//This opens to file as a write file
$fp = fopen('data.csv', 'w');
//This takes the array that has had data ddded to it and adds it to the file
foreach ($csv as $fields) {
fputcsv($fp, $fields);
}
//This closes the file
fclose($fp);
}
}
Thank you very much!

SOAP REQUEST on PHP Multidimensional Arrays

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!

PhP Radio button in Array

I have a form where you can select a radio button and it should transfer what was selected to the next page. My problem is that no matter which radio button you choose it always transfers the value associated last radio button over instead of the one you chose.
So if I choose Around the World it carries 5 with it instead of 10
I am required to use the GET method.
Here is my code:
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
foreach($title as $sub=>$s_value) {
echo "$sub $$s_value";
echo '<input type="radio" name="sub" value="', $sub,'">';
echo "<br>";
}
if (empty($_GET["sub"])) {
} else {
$sub = sub_input($_GET["sub"]);
}
if (empty($_GET["s_value"])) {
} else {
$s_value = sub_input($_GET["s_value"]);
}
if (isset($title['sub'])){
$valid=false;
}
This is the code for the next page:
echo "<b>$sub</b><br />";
echo "Base Total: $ $s_value/mon x $month months <br />";
Yes I have omitted a lot of things, because everything else in my code is fine.
I tried doing this as well, adding in an unset() statement but it didnt work. It completely deleted the value variable....
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
foreach($title as $sub=>$s_value) {
echo "$sub $$s_value";
echo '<input type="radio" name="sub" value="', $sub,'">';
echo "<br>";
unset($s_value);
}
//I also tried putting the unset here//
if (empty($_GET["sub"])) {
} else {
$sub = sub_input($_GET["sub"]);
}
if (empty($_GET["s_value"])) {
} else {
$s_value = sub_input($_GET["s_value"]);
}
if (isset($title['sub'])){
$valid=false;
}
You need to change the names of your variables $s & $s_value within the foreach loop. The foreach loop is setting these variables and they are then being accessed outside of the foreach loop if either of the GET values is empty such that there is no GET value to replace the contents of the variable. Therefore, it always uses 5 as the value because that is the last $s_value that you set.
In summary, changing $s & $s_value within the foreach loop to something like $key & $value respectively will fix your problem with the array value. Alternatively, you could unset them after the foreach loop but before the if statements.
In your current code, you just happened to switched the values on the loop. 10, 7, 5 are inside the elements, while the names Around The world... etc are inside the keys. You just need to switch them. Consider this example:
<?php
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
if(isset($_GET['submit'], $_GET['sub'])) {
$sub = $_GET['sub'];
$name = array_search($sub, $title);
echo '<script>alert("You selected '.$name. ' => '.$sub.'");</script>';
}
?>
<form method="GET" action="index.php">
<?php foreach($title as $key => $value): ?>
<input type="radio" name="sub" value="<?php echo $value; ?>" /> <?php echo $key; ?> <br/>
<?php endforeach; ?>
<br/>
<input type="submit" name="submit" value="Submit" />
</form>

Declare php variables by for loop in array

How to declare variables in the array using for loop. I have 3 input fields on my page, so when the submit buttons is pressed, it should process the following line of code. On my html page, there are fields named: question1, question2, and question3.
Here's the code of process.php file. It doesn't work for some reason, I suppose there are several mistakes here but I cannot find em.
<?php
$question = array();
for($j=1; $j<4; $j++) {
$question[j] = $_POST['question[j]'];
$result;
$n=1;
if($question[j] != "") {
$result = $n.'): '.$question[j].'<br/><br/>';
$n++;
}
}
echo $result;
?>
<?php
$question = array();
$result = "";
for($j=1; $j<4; j++) {
$question[$j] = $_POST["question$j"];
if($question[$j] != "") {
$result .= $j.'): '.htmlentities($question[$j]).'<br/><br/>';
}
}
echo $result;
?>
Though you don't need an array.
<?php
$result = "";
for($j=1; $j<4; j++) {
$result .= $_POST["question$j"]!="" ? htmlentities($_POST["question$j"]).'<br/><br/>':'';
}
echo $result;
?>
For starters, arrays are zero-indexed, so I think you want this:
for($j=0; $j<3; j++)
Aside form that, this doesn't evaluate the value of j:
$_POST['question[j]']
I think you might want something like this:
$_POST["question$j"]
However, if you made the indexing change above, since your elements are named starting with 1 instead of 0 then you'd need to account for that:
$_POST['question' . $j+1]
You can use following HTML code
<input type="text" name="question[a]" />
<input type="text" name="question[b]" />
<input type="text" name="question[c]" />
with following PHP code:
foreach($_POST["question"] as $key => $value)
{
// $key == "a", "b" or "c"
// $value == field values
}
Remember to sanitize Your input!

HTML multiple checkboxes with identical name= into PHP $_POST

So I have a 3rd party survey tool that generates html surveys, and for multi-select checkboxes in a given question, it will name them all the same:
<input type="checkbox" value="1" id="V25_1" name="V25">
<input type="checkbox" value="2" id="V25_2" name="V25">
Is there a way that all the selected values can be retrieved in PHP?
$_POST by default seems to simply store only the last selected value.
Your code should be approximately the following:
<select multiple="multiple">
<input type="checkbox" value="1" id="V25_1" name="V25[]">
<input type="checkbox" value="2" id="V25_2" name="V25[]">
</select>
V25[] means that you can get the value from an array. e.g. $_GET['V25'][0]
You could also specify an index if needed:
V25[1] or V25[a]
You could run something like this before the form submit:
$(":checkbox").each(function(){
$(this).attr("name",$(this).attr("id"));
});
or
$(":checkbox").each(function(){
$(this).attr("name",$(this).attr("name")+"[]");
});
It is possible to retrieve all variables when you have multiple elements with identical 'name' parameters.
After much scouring the internet for a solution, I wrote the following php script which grabs the raw post data, and parses it:
<?php
function RawPostToArray() {
$rawPostData = file_get_contents("php://input");
if($rawPostData) {
$rawPostData = explode('&', $rawPostData);
if($rawPostData && is_array($rawPostData) && count($rawPostData)) {
$result = array();
foreach($rawPostData as $entry) {
$thisArray = array();
$split = explode('=', urldecode($entry), 2);
$value = (count($split) == 2) ? $split[1] : '';
if(array_key_exists($split[0], $result)) {
if(is_array($result[$split[0]])) {
$result[$split[0]][] = $value;
}
else {
$thisArray[] = $result[$split[0]];
$thisArray[] = $value;
$result[$split[0]] = $thisArray;
}
}
else {
$result[$split[0]] = $split[1];
}
}
return $result;
}
else return array();
}
else return array();
}
?>
Any duplicate 'names' are bumped down into an array within the result, much the way $_POST does, when the HTML is coded correctly.
There is probably plenty of room for improvement here, and I'm sure not all situations are accounted for, but it works well for my application.
Suggestions are appreciated where improvements can be made.

Categories