I'm trying to delete specific key and value pair from external JSON file in PHP when user clicked delete button on the page.
I'm not familiar with PHP so I couldn't able to figure out what I'm doing wrong. I looked at more than 20 questions on stackoverflow but none of them helped to solve my problem.
What I'm trying to achieve in general to write a simple script which user can write something in textbox and submit, show it on the page and when user wants delete it. (I have done the submit and showing part but stuck on deleting part)
Firstly my JSON file:
{
"departman1":
[
{"departman1stage":"John"},
{"departman1stage":"Test"},
{"departman1stage":"Test2"}
]
}
Part of my index.php file:
...
include ('yazdir.php');
include ('sil.php');
<div class='icerik'>
<?php
foreach ($json['departman1'] AS $d){
echo '<p class="' . $d['departman1stage'] .'">';
echo "--> ";
echo $d['departman1stage'];
echo '<form action="sil.php" method="POST"><button type="submit" class="dugme" name="' . $d['departman1stage'] .'"><i class="fa fa-trash"></i></button></form>';
echo "<br>";
echo "</p>";
}
?>
</div>
<br>
<form action="yazdir.php" method="POST">
<div class="icerik"><p><input type="text" name="departman1stage"></p></div>
<br>
<input type="submit" value="Gonder">
</form>
...
It is not related with problem but I still put my yazdir.php code:
$json_sifreli = file_get_contents ("data.json");
$json = json_decode($json_sifreli, true);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$data = array(
'departman1stage' => $_POST["departman1stage"]
);
array_push ( $json['departman1'], $data );
$json_sifreleme = json_encode($json, true);
file_put_contents('data.json', $json_sifreleme);
}
sil.php is currently blank, as I said I tried different methods. Some of them deleted whole JSON file and put 'null' into it. Some of them deleted unrelated key and value pair. As a last resort, I decided to write here.
Thanks in advance, sorry for taking your time.
You can delete keys using the PHP built-in unset function. It works on individual array keys:
<?php
$foo = [
'a' => 23,
'b' => 42,
];
unset($foo['a']);
var_dump($foo);
Results in:
array(1) {
["b"]=>
int(42)
}
PHP arrays are hash maps, no matter if keys are strings are numeric. In your example JSON, departman1 is an array with numeric keys. You can delete numeric keys with unset as well:
$bar = [
23,
42,
];
unset($bar[0]);
var_dump($bar);
Results in:
array(1) {
[1]=>
int(42)
}
Note that the dump shows 1 as key. Unsetting numeric keys does not cause the array to be renumbered. You end up with holes and this will show up in json_encode output:
echo json_encode($bar);
// Results in: {"1":42}
So you could go through the swamp of using a JSON file as data store, but be cautioned it's a Pandoras Box full of hardships. It also doesn't scale beyond one concurrent user because json_encode and json_decode do not provide ACID properties, which database management systems provide you. My suggestion: ditch the JSON file and pick up a proper database such as PostgreSQL or MySQL (they have good support in PHP via PDO).
view the example code in playground
(BTW: You are using the $_POST variable directly, which is unsafe user input. Sanitizing input can be done with PHP built-in filter_var function.)
Related
I'm having some problems getting the data through my PHP loop.
<?php
$url = 'https://www.fibalivestats.com/data/1653309/data.json';
$content = file_get_contents($url);
$json = json_decode($content, true);
?>
<?php
foreach($json['totallds']['sPoints'] as $item); {
echo $item;
}
?>
The error I'm getting is an array to string conversion error. What I'm trying to get is the data from the sPoints array that will give me a Top 5 points scorers for a basketball game.
I'll build a table for this in HTML later but for now, it's not displaying the data at all and I'm getting errors. I feel like I may have confused arrays and strings too. Any thoughts about what I'm doing wrong? JSON file can be found in the $url variable.
Also if it helps, here's the link to where I have gotten the data from and what context the Top 5 is from https://www.fibalivestats.com/u/NSS/1653309/lds.html
Thanks!
Your $item is an array, so you can't just echo it like that. You can, however, echo its columns, for example:
foreach($json['totallds']['sPoints'] as $item) {
echo $item['firstName'] . ' ' . $item['familyName'];
}
Notice the removed semicolon between the foreach () and {.
Well, array to string conversion error means you're trying to echo an array.
If you see the return of the url you are looking at, you can verify that the "sPoints" key returns an array with several objects.
Try to change echo to print_r or var_dump to view entire data or complete your business logic.
Try changing:
echo $item;
to:
var_dump($item);
I'm trying to use an HTML submit which is populated from an associative array from an SQL database, but I would like to pass multiple values as opposed to the usual 1. I've tried using JSON in the value, with the variables and then decode the JSON later to retrieve the individual variables.
<select name="name">
<?php
foreach($array as $vals){
echo '<option value={"a":".'$vals['1']'.","b":".'$vals['2']'.","c":".'$vals['3']'.","d":".'$vals['4']'."}>Option Name</option>';
}?>
</select>
It works as intended until one of the options has a spacing in the string and then in the HTML page. I end up with a problem where somehow an extra " is inserted in the space, so my browser is showing the value:
{"a":"x" y","b":"xy","c":"xyz","d":"xyzz"}
The problem is the "x" y" which I was hoping to be "x y".
Does anyone have ideas on how I can fix this? Or equally any other methods of achieving the same result?
You need to put quotes around the value attribute so that spaces don't terminate it. Also use htmlentities() to encode other special characters.
Also, don't construct JSON by hand, use json_encode().
foreach ($array as $vals) {
$obj = ["a" => $vals[1], "b" => $vals[2], "c" => $vals[3], "d" => $vals[4]];
$json = htmlentities(json_encode($obj));
echo "<option value='$json'>Option Name</option>";
}
I would build the JSON as a PHP array and then you can base64_encode(json_encode()) the array. This would be easier to read and you don't have to worry about other edge cases with this solution.
Check the position of . and '
echo '<option value={"a":".'$vals['1']'.","b":".'$vals['2']'.","c":".'$vals['3']'.","d":".'$vals['4']'."}>Option Name</option>';
Corrected
echo '<option value={"a":"'.$vals['1'].'","b":"'.$vals['2'].'","c":"'.$vals['3'].'","d":"'.$vals['4'].'"}>Option Name</option>';
I have a number of items of data. Sometimes the var is not created/set, sometimes it is. This is because the var data comes from a form with optional fields.
I have created the variables only if the information is present as such:
if(!empty($_POST["user-jobtitle"])){
$idealJobTitle = $_POST["user-jobtitle"]; }
So if the field user-jobtitle is not filled in, then $idealJobTitle is not created.
I now wish to create an array with a key for each value. But I only want to add to the array if that variable exists. Otherwise, I just want to omit it.
I have written code below which I know is wrong but follows the sort of logic I am after. What is the correct way to do this? Do I really have to run through nested if statements checking if the var exists and only then pushing to the array?
$other_info = array (
"other_info" => array(
if(isset($message)){
"message" => $message
},
if(isset($salaryRange)){
"salary_range" => $salaryRange
},
if(isset($idealJobTitle)){
"ideal_job_title" => $idealJobTitle
}
if(isset($applyFor)){
"ideal_applying_for" => $applyFor
}
)
);
An expected result, if the user has not provided an ideal job title on the form, would be as such:
array(1) {
["other_info"]=>
array(3) {
["message"]=>
string(18) "my message here"
["salary_range"]=>
string(19) "£25k - £30k"
["ideal_applying_for"]=>
string(18) "Cat cuddler"
}
}
As you can see in the above, the ideal_job_title key and value are simply not present.
You should not conditionally declare variables. That's just asking for problems later on.
Unpacking values from one array into a variable and then conditionally packing them back into an array is needlessly complex. Keep your data in an array and move it around in one "package".
You can't have nested if statements within an array declaration.
The most useful way to handle this would be to use names in your form that you're also going to use later on in your $other_info array. Translating between various variable and key names throughout your code is just terribly confusing, pointless and needlessly requires a ton of additional code. In other words, why does the same piece of information need to be called user-jobtitle and $idealJobTitle and ideal_job_title in different contexts? If you'd keep it consistent, you could simply filter empty values and be done with it:
$other_info = array('other_info' => array_filter($_POST));
Yup, array_filter gets rid of empty elements without individual if statements. You can further use array_intersect_key and similar functions to further filter out keys.
If you name variables as key in the array, you can use compact function. Undefined variable will not be in array
$ar = compact("message", "salaryRange", "idealJobTitle", "applyFor");
You can use the below code :
$other_info = array();
if(isset($message)){
$other_info['other_info']["message"] = $message;
}
if(isset($salaryRange)){
$other_info['other_info']["salary_range"] = $salaryRange;
}
if(isset($idealJobTitle)){
$other_info['other_info']["ideal_job_title"] = $idealJobTitle;
}
if(isset($applyFor)){
$other_info['other_info']["ideal_applying_for"] = $applyFor;
}
You already have a code that works and puts the values in variables. Create an empty array and put the data directly in the array under various keys instead of individual variables:
$info = array();
// Analyze the input, put the values in $info at the correct keys
if (! empty($_POST["message"])) {
$info["message"] = $_POST["message"];
};
if (! empty($_POST["salaryRange"])) {
$info["salary_range"] = $_POST["salaryRange"];
};
if (! empty($_POST["idealJobTitle"])) {
$info["ideal_job_title"] = $_POST["idealJobTitle"];
}
if (! empty($_POST["applyFor"])) {
$info["ideal_applying_for"] = $_POST["applyFor"];
}
// Voila! Your data is now in $info instead of several variables
// If you want to get the structure you described in the non-working code you can do:
$other_info = array(
"other_info" => $info,
);
I know there are some similar questions but none of them solves my issue.
I have a simple form:
<form method="post">
Import data: <textarea type="text" name="import"></textarea>
<input type="submit">
</form>
Then I get data from the "import" field:
$current = my_data();
$import = $_POST['import'];
$merge = array_merge($current,$import);
The problem is, even if I paste:
array('foo' => 'bar')
I get:
Warning: array_merge(): Argument #2 is not an array in
(address)
on line (line)
I can't change the HTML markup and I have to paste arrays there. Any ideas how to fix it? I've been reading about serialize() but not sure if there's anything to serialize is array() is not array() for PHP. Why is that? Any solutions? Thanks a lot!
UPDATE
$current hold an array of options for my theme.
$merge is supposed to hold the same keys with different values (around 30-50 of them, not multidimensional but might be in the future), but of course users might add new ones so in order to ignore them I'm actually using:
$imported_options = array_merge($current_options , array_intersect_key($_POST["import"], $current_options ));
(simplified this one as it's just an example)
So after all I want to load an array from the form and update the other array with it.
PHP will not create arrays in $_GET/$_POST unless you tell it to:
Import data: <textarea type="text" name="import[]"></textarea>
^^---- need these
Without the [], PHP will treat any duplicate field names as strings to be overwritten. With [] in the name, PHP will treat them as new elements in an array.
You can do
$current['import'] = $import;
Or you can change your html this way:
<textarea type="text" name="myarray['import']"></textarea>
And in php:
$import = $_POST['myarray'];
The second argument is not an array.
$_POST['import'] = value received from the form.
With that said, try:
$current [] = $_POST['import'];
What are you trying to get from $_POST['import'] ?
you are using a textarea to get an array?
if it's just a single variable then use array_push
http://php.net/manual/es/function.array-push.php
for array_merge you need to have 2 arrays.
I have an array ($form) which retreives some information from $_POST:
$form = $_POST['game'];
Now I want to work with the values in this array, but I somehow fail.
For debugging I used these commands (in the exact same order, with no extra lines inbetween):
print_r($form);
echo '#' . $form['System_ID'] . "#";
and as returned output I get:
Array
(
['Title'] => Empire: Total War - Special Forces
['Genre_ID'] => 1
['Type'] => Spiel
['System_ID'] => 1
)
##
Any ideas where my System_ID went? It's there in print_r, but not in the next line for echo?!?
Alright, I found the solution myself (a.k.a. d'oh!)
I added another
var_dump($form);
for further analysis and this is what I got:
array(4) {
["'Title'"]=>
string(34) "Empire: Total War - Special Forces"
["'Genre_ID'"]=>
string(1) "1"
["'Type'"]=>
string(5) "Spiel"
["'System_ID'"]=>
string(1) "1"
}
Notice the single quote inside the double quote?
Looks as if you're not allowed to use the single quote in html forms or they will be included in the array key:
Wrong: <input type="text" name="game['Title']" />
Correct: <input type="text" name="game[Title]" />
print_r() doesn't put quotes around keys - for debugging i'd recommend ditching print_r altogether. var_export or var_dump are better.
even better: use firephp. it sends the debug info via headers, so it doesn't mess up your output and thus is even usable with ajax. output is displayed nicely with firebug including syntax coloring for data structures.
and it's even easier to use: just fb($myvar);
It works for me:
<?
$form['System_ID'] = 1;
print_r($form);
echo '#' . $form['System_ID'] . '#';
?>
Output:
% php foo.php
Array
(
[System_ID] => 1
)
#1#
PHP 5.2.6, on Fedora Core 10
EDIT - note that there's a hint to the real cause here. In my code the print_r output (correctly) shows the array keys without single quotes around them. The original poster's keys did have quotes around them in the print_r output, showing that somehow the actual key contained the quote marks.