I have a bunch of urls I am echoing from a json file with a foreach loop. I then select some of those with a form checkbox, which I then want to write to another json file. But when I write to the second json file, it just grabs the last checked url, not all the checked ones.
form:
<?php
if(!empty($user_array)){
foreach($user_array as $image){
echo
<input type="checkbox" name="photo_url" value="'. $image['url'] . '">;
}
}
grab_urls.php
$new_json = fopen("new-order.json", "w") or die("Unable to open file!");
$txt[] = array(
'photo_url'=> $_POST['photo_url'],
);
fwrite($new_json, json_encode($txt, JSON_FORCE_OBJECT));
fclose($new_json);
How can I get all the checked URLs?
You need to create multiple checkbox array.something like below:
<?php
if(!empty($user_array)){
foreach($user_array as $image){
echo
<input type="checkbox" name="photo_url[]" value="'. $image['url'] . '">;
}
}
?>
Related
Dear Fellow PhP Experts,
I am writing below code to export HTML table data in PHP.
Its working nicely in localhost. However, when I deployed to the domain, there is warning-
'Warning: Cannot modify header information - headers already sent by
(output started at ../result_month.php:64 //dbconnect.php line//) in
../result_month.php on line 77 //header("Location: $FileName") line//'.
Seeking suggestion from you, what I am exactly doing wrong.
<?php require_once('dbconnect.php'); ?>
<?php
//To generate report, home page added below data to query desired information.
$month=$_POST["themonth"];
$year=$_POST["theyear"];
?>
<?php //I am not intended to redirect to new page when pressing export button
if(isset($_POST["export"]))
{
//as i am in the same page, need to generate query string again, that is why kept this month and year in hidden inputs
$month_visit=$_POST["selected_month"];
$year_visit=$_POST["selected_year"];
$FileName = "data_" . $month_visit . "_" . $year_visit . ".csv";
header("Location: $FileName"); //its showing error in this line
$output = fopen($FileName, 'w');
// output the column headings
fputcsv($output, array('ID', 'Name'));
// fetch the data
$query_string = "SELECT ID, Name from Participant";
$rows = mysql_query($query_string);
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);
fclose($output);
}
?>
<form method="post"> // added this form at the top of HTML table to add export button
<input type="hidden" name="selected_year" value="<?php echo $year; ?>">
<input type="hidden" name="selected_month" value="<?php echo $month; ?>">
<input type="submit" name="export" value="Export to CSV" />
</form>
<?php
$result = mysql_query("SELECT ID, Name from Participant");
echo "displaying query data in html table";
?>
Any content without PHP open tag are treated as HTML, sent as HTTP_BODY.
HTTP_BODY will be sent after HTTP_HEADER was closed.
Try these codes:
<?php
require_once('dbconnect.php');
//To generate report, home page added below data to query desired information.
$month=$_POST["themonth"];
$year=$_POST["theyear"];
//I am not intended to redirect to new page when pressing export button
if(isset($_POST["export"]))
{
//as i am in the same page, need to generate query string again, that is why kept this month and year in hidden inputs
$month_visit=$_POST["selected_month"];
$year_visit=$_POST["selected_year"];
$FileName = "data_" . $month_visit . "_" . $year_visit . ".csv";
// WARNING : Uncomment this will cause header() call failed.
//echo "THIS IS HTTP_BODY";
header("Location: $FileName"); //its showing error in this line
$output = fopen($FileName, 'w');
// output the column headings
fputcsv($output, array('ID', 'Name'));
// fetch the data
$query_string = "SELECT ID, Name from Participant";
$rows = mysql_query($query_string);
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);
fclose($output);
}
?>
<form method="post"> // added this form at the top of HTML table to add export button
<input type="hidden" name="selected_year" value="<?php echo $year; ?>">
<input type="hidden" name="selected_month" value="<?php echo $month; ?>">
<input type="submit" name="export" value="Export to CSV" />
</form>
<?php
$result = mysql_query("SELECT ID, Name from Participant");
echo "displaying query data in html table";
?>
EDITED
Problem - A null value is written to the JSON file after the function runs.
Expectation - Capture data entered into HTML form, append it to an existing JSON file.
Some of the Stack resources I've used:
How do I extract data from JSON with PHP?
How to loop through JSON array using PHP
how to write a json file as a datasource in php?
How to Append JSON File in PHP?
How to add to json array in .json file with php
How can I write data in local JSON file using jQuery?
My JSON file looks like this:
{
"records": [
{"Date":"05/04/2016","Miles":168081,"Gallons":11.003,"Cost":28.60,"MPG":24.1,"Street":"5500 Mirage St","City":"Yorba Linda","State":"CA","Zip":92807,"Time":"07:04"},
{"Date":"04/18/2016","Miles":167815,"Gallons":10.897,"Cost":27.23,"MPG":25.7,"Street":"5500 Mirage St","City":"Yorba Linda","State":"CA","Zip":92807,"Time":"15:46"}
],
"error" : false,
"status" : 200
}
EDITED - My PHP script looks like this (update implements Chay's code):
<?php
function runMyFunction() {
// #####
if ($_SERVER['REQUEST_METHOD'] !== 'POST' && !isset($_POST)) { //You may add $_POST[post_name] for validation
die('I need post method!');
}
// check if file exists
$filename = 'mpg-data-file2.json';
if ( ! file_exists($filename) ) {
echo 'ERROR:' . $filename . ' not found' . '<BR>';
} else {
echo 'OK: ' . $filename . ' exists.' . '<BR>';
$data = array(
"Date"=> $_POST['mpg_date'],
"Miles"=> $_POST['mpg_miles'],
"Gallons"=> $_POST['mpg_gallons'],
"Cost"=> $_POST['mpg_cost'],
"MPG"=> $_POST['mpg_mpg'],
"Street"=> $_POST['mpg_street'],
"City"=> $_POST["mpg_city"],
"State"=> $_POST['mpg_state'],
"Zip"=> $_POST['mpg_zip'],
"Time"=> $_POST['mpg_time']
);
//Load data from json file
$dataFile = file_get_contents("mpg-data-file2.json");
$dataFile = json_decode($str_data,true);
//Merge data from post with data from file
$formattedData = array_merge($dataFile['records'],$data);
$formattedData = json_encode($formattedData);
//If data from file is empty, just use data from post
if (empty($dataFile)) {
$formattedData = json_encode($data);
}
//Set a parent key
$records['records'] = $formattedData;
//Overwites everything
/* $handle = fopen($filename,'a+');
fwrite($handle,$records);
fclose($handle); */
file_put_contents($filename,$records, FILE_APPEND | LOCK_EX);
print_r($formattedData);
echo 'OK: ' . '<BR>' . $records . '<BR>';
}
// #####
}//end runMyFunction
/*
if (isset($_GET['hello'])) {
runMyFunction();
} */
if(isset($_POST['mpg_date'],$_POST['mpg_date'],$_POST['mpg_miles'],$_POST['mpg_gallons'],$_POST['mpg_cost'],$_POST['mpg_mpg'],$_POST['mpg_street'],$_POST["mpg_city"],$_POST['mpg_state'],$_POST['mpg_zip'],$_POST['mpg_time'])) {
runMyFunction($_POST);
}
?>
An excerpt of the HTML form looks like this:
<form action="_process.php" method="POST" role="form">
<div class="form-group">
<label for="mpg_date">Fuel Date:</label>
<input type="text" class="form-control" id="mpg_date" name="mpg_date" placeholder="04/18/2016">
</div>
<div class="form-group">
<label for="mpg_miles">Odometer (Miles):</label>
<input type="number" min=”0″ step="any" class="form-control" id="mpg_miles" name="mpg_miles" placeholder="167815">
</div>
<!-- And so on... -->
<div>
<a href='_process.php?hello=true'>Run PHP Function</a>
</div>
</form>
I'm sure that your submission doesn't POST something since you're using anchor (without any javascript) to submit. In the other word, notice I change it to <button>.
<form action="_process.php" method="POST" role="form">
<div class="form-group">
<label for="mpg_date">Fuel Date:</label>
<input type="text" class="form-control" id="mpg_date" name="mpg_date" placeholder="04/18/2016">
</div>
<div class="form-group">
<label for="mpg_miles">Odometer (Miles):</label>
<input type="number" min=”0″ step="any" class="form-control" id="mpg_miles" name="mpg_num" placeholder="167815">
</div>
<!-- And so on... -->
<div>
<button type="submit" role="button">Run PHP Function</button>
</div>
</form>
If you also noticed I also changed the second input name above to mpg_num. And this should be your backend looks.
...
...
if(isset($_POST['mpg_date'], $_POST['mpg_num'])) {
runMyFunction($_POST);
}
Updated
if ($_SERVER['REQUEST_METHOD'] !== 'POST' && !isset($_POST)) { //You may add $_POST[post_name] for validation
die('I need post method!');
}
// check if file exists
$filename = 'mpg-data-file.json';
if ( ! file_exists($filename) ) {
echo 'ERROR:' . $filename . ' not found' . '<BR>';
} else {
echo 'OK: ' . $filename . ' exists.' . '<BR>';
$data = array(
"Date"=> $_POST['mpg_date'],
"Miles"=> $_POST['mpg_miles'],
"Gallons"=> $_POST['mpg_gallons'],
"Cost"=> $_POST['mpg_cost'],
"MPG"=> $_POST['mpg_mpg'],
"Street"=> $_POST['mpg_street'],
"City"=> $_POST["mpg_city"],
"State"=> $_POST['mpg_state'],
"Zip"=> $_POST['mpg_zip'],
"Time"=> $_POST['mpg_time']
);
//Load data from json file
$dataFile = file_get_contents("mpg-data-file.json");
$dataFile = json_decode($str_data,true);
//Merge data from post with data from file
$formattedData = array_merge($dataFile['records'],$data);
//If data from file is empty, just use data from post
if (empty($dataFile)) {
$formattedData = $data;
}
//Set a parent key
$records['records'] = $formattedData;
$records['error'] = false;
$records['status'] = 200;
$records = json_encode($records);
//Overwites everything
$handle = fopen($filename,'w+');
fwrite($handle,$records);
fclose($handle);
print_r($records);
}
I hope this won't consume your environment RAM alot :)
This:
<a href='_process.php?hello=true'>Run PHP Function</a>
will actually submit your form. When you just link to the script that way rather than submitting the form, none of the $_POST values will be set.
It looks like your form just needs a submit button. You can put '_process.php?hello=true' into the form action if you want the if (isset($_GET['hello'])) { check to work.
In other words:
<form action="_process.php?hello=true" method="POST" role="form">
<!-- All your inputs, etc. ...-->
<input type="submit" value="Run PHP Function">
</form>
In order to append the new data to your existing JSON, you'll need to change the order that things happen in your function. The else part should be like this:
// First get the existing JSON from the file and decode it
$str_data = file_get_contents("mpg-data-file.json"); // Get the JSON string
$data = json_decode($str_data,true);// json_decode expects the JSON data, not a file name
// Then create a new data array from the $_POST data and add it to the 'records' key
$new_data = array(
"Date"=> $_POST['mpg_date'],
"Miles"=> $_POST['mpg_miles'],
"Gallons"=> $_POST['mpg_gallons'],
"Cost"=> $_POST['mpg_cost'],
"MPG"=> $_POST['mpg_mpg'],
"Street"=> $_POST['mpg_street'],
"City"=> $_POST["mpg_city"],
"State"=> $_POST['mpg_state'],
"Zip"=> $_POST['mpg_zip'],
"Time"=> $_POST['mpg_time']
);
$data['records'][] = $new_data;
// Then re-encode the JSON and write it to the file
$formattedData = json_encode($data);//format the data
$handle = fopen($filename,'w+');//open or create the file
fwrite($handle,$formattedData);//write the data into the file
fclose($handle);//close the file
print_r($data);
I am having trouble making a image deleter in php i do not know what is wrong
PHP:
<?php if (isset($_POST['dcheck'])) {
$img_dir = "Uploads/";
$image = $_POST['dcheck'];
mysql_query("DELETE FROM Photos WHERE PhotoNumber = '".$image."'") or die(mysql_error());
echo 'The image(s) have been successfully deleted.';
} else{
echo 'ERROR: unable to delete image file(s)!';
}
?>
HTML:
<form action="Admin3.php" method="post">
<?php
while($check = mysql_fetch_array($query2)){
echo '<img class="images2" src= "/PhotographyMML/Uploads/resized' . $check['PhotoName'] . $check['PhotoType'] . '" height="100" width ="100" ><input type="checkbox" name="dcheck[]" value="'. $check['PhotoNumber'] .'" />';
}
?>
<input type="submit" value="Delete Image(s)" />
</form>
Your dcheck variable is an array. You will want to create an outer loop around the existing query code you have and foreach through the array, deleting each time.
<?php if (isset($_POST['dcheck'])) {
$img_dir = "Uploads/";
foreach ($_POST['dcheck'] as $image) {
mysql_query("DELETE FROM Photos WHERE PhotoNumber = '".$image."'") or die(mysql_error());
echo 'The image(s) have been successfully deleted.';
} else{
echo 'ERROR: unable to delete image file(s)!';
}
}
?>
A small optimization would be to alter the query so it uses WHERE A small optimization would be to alter your delete query so that it uses WHERE PhotoNUmber IN (1, 2 ...).
This would cause your deletion to happen in one query rather than N queries.
What seems to be missing is any code to actually remove the original file you're alluding to. That would require some sort of file deletion function typically utilizing http://php.net/manual/en/function.unlink.php
I have this code that displays contents of a particular file. I would like to add a submit button that when clicked saves the changes in to a file. Can anyone help me or give some examples that i can use to create this button. i have tried couple of example that i found on the web but could get it to work. is the solution hidden somewhere with $_POST. her is the code.
<?php
$relPath = 'test_file_1.php';
$fileHandle = fopen($relPath, 'r') or die("Failed to open file $relPath go and make me a sandwich! "); ;
while(!feof($fileHandle)){
$line = fgets($fileHandle);
$lineArr = explode('=', $line);
if (count($lineArr) !=2){
continue;
}
$part1 = trim($lineArr[0]);
$part2 = trim($lineArr[1]);
$simbols = array("$", "[", "]", "'", ";");
//echo "<pre>$part1 $part2</pre>";
echo '<form>
<pre><input type="text" name="content_prt1" size="50" value="' .str_replace($simbols, "",$part1).'"> <input type="text" name="content_prt2" size="50" value="' .str_replace($simbols, "",$part2).'"></pre>
<form />';
}
echo '<input type="submit" value="Submit">';
fclose($fileHandle) or die ("Error closing file!");
?>
EDIT
code for the updatefile.php
<?php
if(isset($_REQUEST['submit1'])){
$handle = fopen("test_file_1.php", "a") or die ("Error opening file!");;
$file_contents = $_REQUEST["content_prt1" . "content_prt1"];
fwrite($handle, $file_contents);
fclose($handle);
}
?>
the code stops at error opening file
If you look at the at purely submitting point of view then put the submit button inside the <form> tags
Also, the closing form tags must be form and not from. The updatefile.php I refer to is the file that you post the input box type text to that will update the file of the database field. Remember to close the file before writing to it again. Hope this helps.
<?php
$relPath = 'test_file_1.php';
$fileHandle = fopen($relPath, 'r') or die("Failed to open file $relPath go and make me a sandwich! ");
echo '<form action="updatefile.php" method="POST">';
while(!feof($fileHandle))
{
$line = fgets($fileHandle);
$lineArr = explode('=', $line);
if (count($lineArr) !=2){
continue;
}
$part1 = trim($lineArr[0]);
$part2 = trim($lineArr[1]);
$vowels = array("$", "[", "]", "'", ";");
echo '<pre><input type="text" name="content_prt1" size="50" value="' .str_replace($vowels, "",$part1).'">
<input type="text" name="content_prt2" size="50" value="' .str_replace($vowels, "",$part2).'">
</pre>';
}
echo '<input type="submit" value="Submit">';
echo '<form>';
fclose($fileHandle) or die ("Error closing file!");
?>
You can't submit more than one form with a single submit button. You'll have to echo the <form> tags outside of the loop so that only one form gets created.
The other problem is you have multiple inputs that are named the same, so $_POST will contain only the value of the last input of each name. You probably mean to append [] to the names of the inputs, e.g. name="content_prt1[]". This way, PHP will create an array of those inputs' values in $_POST['content_prt1'].
Finally, note that what you have so far may pose an HTML injection risk (when displaying the page) unless you're certain that the text coming out of the file doesn't contain characters like < and >. To mitigate this, you can use htmlentities when echoing the text into the inputs.
I am trying to pass array using form post method :
submit.php
<form method="post" action="makepub.php">
<?php
.... Loop
....
echo '</td><td align="center">';
echo '<input type="checkbox" name="file_list[]" value="'.$pr.'">' ;
echo '</td><tr/>';
....
.... Loop end
?>
makepub.php :
if (isset($_POST['submit1'])) {
$file_list = $_POST["file_list"];
$how_many = count($file_list);
echo '<b>Total No of Public files chosen : </b>'.$how_many.'<br><br>';
if ($how_many>0) {
echo '<b>You changed following files to public : </b><br>';
}
for ($i=0; $i<$how_many; $i++) {
echo ($i+1) . '- ' . $file_list[$i] . '<br>';
// Some code here
}
echo "<br><br>";
}
Ok these two files works perfectly on my localhost with XAMPP.
php version 5.3
but on my server array is not getting passed.
I checked by replacing the array with single variable. Even so nothing is passed to file makepub.php
Is there anything i am missing with post here ???
Any suggestion is appreciated.
Thanks.
Your code should work as it appears, however you should make sure your submit button has a name of submit1 and then you close the form with a closing tag.