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>';
Related
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.)
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 have a page that retrieves from a mysql db (blob) a serialized base64 encoded array, which is then decoded, unserialized, and displayed.
My problem is, any html that is displayed is as plain text (not as code) and the some of the sensitive characters are escaped. " for example is \". I tried adding a str_replace() and although it did remove the \'s it didn't solve the issue.
Here's the code that displays the info:
$array = unserialize(base64_decode($sArray));
if ($array != ''){
foreach ($array as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
}
It properly adds the td tags to add to the table, but again, the $value is displayed as plain text.
Thanks in advance for any help!
The array is setup something like this:
FieldTitle1 => link
FieldTitle2 => Random Text
FieldTitle3 => 930809830
Sample sArray data:
YToxMjp7aToxO3M6OToidGVzdE5hbWUxIjtpOjI7czozMjoiPGEgaHJlZj1cXFwiI1xcXCI+dGVzdFZhbHVlMTwvYT4iO2k6MztzOjk6InRlc3ROYW1lMiI7aTo0O3M6MTc6IjxiPnRlc3RWYWx1ZTI8L2I+IjtpOjU7czo5OiJ0ZXN0TmFtZTMiO2k6NjtzOjQzOiI8aW1nIHNyYz1cXFwiaHR0cDovL3BsYWNlaG9sZC5pdC8xMHgxMFxcXCI+IjtpOjc7czo5OiJ0ZXN0TmFtZTQiO2k6ODtzOjEwMToiPGlmcmFtZSBzcmM9XFxcImh0dHA6Ly9jcm93bmZ1cm5pdHVyZW1hLmNvbVxcXCIgd2lkdGg9XFxcIjEwXFxcIiBoZWlnaHQ9XFxcIjEwXFxcIiBzZWFtbGVzcz48L2lmcmFtZT4iO2k6OTtzOjk6InRlc3ROYW1lNSI7aToxMDtzOjEyOiJSZWd1bGFyIFRleHQiO2k6MTE7czo5OiJ0ZXN0TmFtZTYiO2k6MTI7czo5OiIxMjk4MzkzNDciO30=
I changed form serialization to json_encode/decode and that solved the issue!
PHP Serialize Successful, Unserialize Failure
Thanks #Eyal Alsheich for pointing this link out!
I'm calling in values using PHP to cURL a site's API. I'm able to pull the data in and put into an array just fine, but when using JSON, one of the attributes ($title) comes back with too much data.
For example, if I just do
echo $new_array[27]['title'];
-> I get "Event Name" but if I do
echo json_encode($new_array[27]['title']);
-> I get {"#attributes":{"abc_id":"8"},"0":"Event Name"}
I want to use JSON as this works with something else I'm doing, but is there a way I can strip out the {"#attributes":{"abc_id":"8"},"0": part leaving just the "Event Name" as a string by itself?
Try:
$json = $new_array[27]['title'];
echo json_encode($json);
I'm not sure what you have in your array there, so these are a guess!
You could try:
unset($new_array[27]['title']['#attributes']);
Or:
$a = array();
foreach($new_array[27]['title'] as $arr) {
$a[] = $arr->__toString();
}
echo json_encode($a);
foreach ($_GET as $field => $label)
{
$datarray[]=$_GET[$field];
echo "$_GET[$field]";
echo "<br>";
}
print_r($datarray);
This is the output I am getting. I see the data is there in datarray but when
I echo $_GET[$field]
I only get "Array"
But print_r($datarray) prints all the data. Any idea how I pull those values?
OUTPUT
Array (
[0] => Array (
[0] => Grade1
[1] => ln
[2] => North America
[3] => yuiyyu
[4] => iuy
[5] => uiyui
[6] => yui
[7] => uiy
[8] => 0:0:5
)
)
EDIT: When I completed your test, here was the final URL:
http://hofstrateach.org/Roberto/process.php?keys=Grade1&keys=Nathan&keys=North%20America&keys=5&keys=3&keys=no&keys=foo&keys=blat&keys=0%3A0%3A24
This is probably a malformed URL. When you pass duplicate keys in a query, PHP makes them an array. The above URL should probably be something like:
http://hofstrateach.org/Roberto/process.php?grade=Grade1&schoolname=Nathan®ion=North%20America&answer[]=5&answer[]=3&answer[]=no&answer[]=foo&answer[]=blat&time=0%3A0%3A24
This will create individual entries for most of the fields, and make $_GET['answer'] be an array of the answers provided by the user.
Bottom line: fix your Flash file.
Use var_export($_GET) to more easily see what kind of array you are getting.
From the output of your script I can see that you have multiple nested arrays. It seems to be something like:
$_GET = array( array( array("Grade1", "ln", "North America", "yuiyyu", "iuy", "uiyui", "yui","uiy","0:0:5")))
so to get those variables out you need something like:
echo $_GET[0][0][0]; // => "Grade1"
calling echo on an array will always output "Array".
print_r (from the PHP manual) prints human-readable information about a variable.
Use <pre> tags before print_r, then you will have a tree printed (or just look at the source. From this point you will have a clear understanding of how your array is and will be able to pull the value you want.
I suggest further reading on $_GET variable and arrays, for a better understanding of its values
Try this:
foreach ($_GET as $field => $label)
{
$datarray[]=$_GET[$field];
echo $_GET[$field]; // you don't really need quotes
echo "With quotes: {$_GET[$field]}"; // but if you want to use them
echo $field; // this is really the same thing as echo $_GET[$field], so
if($label == $_GET[$field]) {
echo "Should always be true<br>";
}
echo "<br>";
}
print_r($datarray);
It's printing just "Array" because when you say
echo "$_GET[$field]";
PHP can't know that you mean $_GET element $field, it sees it as you wanting to print variable $_GET. So, it tries to print it, and of course it's an Array, so that's what you get. Generally, when you want to echo an array element, you'd do it like this:
echo "The foo element of get is: {$_GET['foo']}";
The curly brackets tell PHP that the whole thing is a variable that needs to be interpreted; otherwise it will assume the variable name is $_GET by itself.
In your case though you don't need that, what you need is:
foreach ($_GET as $field => $label)
{
$datarray[] = $label;
}
and if you want to print it, just do
echo $label; // or $_GET[$field], but that's kind of pointless.
The problem was not with your flash file, change it back to how it was; you know it was correct because your $dataarray variable contained all the data. Why do you want to extract data from $_GET into another array anyway?
Perhaps the GET variables are arrays themselves? i.e. http://site.com?var[]=1&var[]=2
It looks like your GET argument is itself an array. It would be helpful to have the input as well as the output.