session_start();
echo "<form method='post'>";
echo "<input type='text' name='random' placeholder='Product' >";
echo "<input type='submit' value='submit' name='submit'>";
echo "</form>";
if(!$_SESSION['list']) {
$_SESSION['list'] = array(); // create session
}
if(isset($_POST['submit']) && empty($_POST['random'])) { // Check if input is empty
echo "* Input is empty!";
} elseif(isset($_POST['submit']) && isset($_POST['random'])) {
$_SESSION['list'][] += 1; // add +1 to array
}
foreach ($_SESSION['list'] as $value) {
echo $value . "<br>"; // shows the list/array
}
So I tried to make array that add +1 number on a submit, but my array keeps being 1, so it doesn't go like: 1,2,3,4,5... but it goes like: 1,1,1,1,1,1 . They don't add up. How do I fix this?
Given an array $arr, or $_SESSION['list'] in your case, it is possible to append an element to the end of the array as follows.
$arr[] = 'new element';
You try to combine this with the += operator. This will first append 0 to the array and then increment it, resulting in 1 being appended all the time.
It looks like what you actually want to do is this:
$arr[] = end($arr) + 1;
That is, take the last value of the array, add 1 to it and append that to the array.
Related
I have a json file with some data that I'm displaying on my website using php foreach.
I need 2 functions for that:
Add new element (which I coded without any troubles)
Remove specific data (which I'm struggling with)
The question is - I dont know how to pass an selected element ID, because $_POST takes the input's name key, and I cant pass it to function dynamically.
Here is my code that displays data in html:
$index = 0;
foreach (json_decode($data) as $element) {
$isDone = $element->isDone ? '+' : '-';
echo $isDone ." ". $element->name . "<br>";
echo "<form action='/operateJson.php'>";
echo "<input type='submit' value='-' style='background-color: red;' name='remove$index'>";
echo "</form>";
$index++;
}
And it looks like that
Here is my code from action
function addRow($row, $rowname): void
{
$jsonData = file_get_contents($row);
$data = json_decode($jsonData, true);
$data[strval(count($data))] = array(
'name' => strval($rowname),
'isDone' => 0
);
$jsonData = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents('../db.json', $jsonData);
}
if (isset($_POST["1"])) {
addRow("../db.json", $_POST["rownamefirst"]);
}
That is working, but I need to add a function that executes after clicking the red button and then removing the chosen element from json
Hello I am submitting a form with POST method and I want its contents to be echo'ed one by one apart from the last one. So far I am using
<?php foreach($_POST as $data){
echo $data;
}
?>
which displays the whole array of $_POST, how can I make it using common "for" loop to not echo the last item of the array? It doesnt seem to work
<?php
$length=count($_POST)-1;
for($i=0; $i<$length; $i++) {
echo $_POST[$i];
?>
<br>
<?php } ?>
I am getting 5 errors, undefined offset 0 through 4 where the echo line is present
Do the following:
<?php
$counter = 0;
$lastItemOrder = count($_POST);
foreach($_POST as $value) {
$counter++;
if( $counter !== $lastItemOrder) {
echo $value;
}?>
<br><?php
} ?>
Your loop for just get numerical index like $_POSR[0], $_POST[1]... This just would work if in the HTML the attribute name of the input elements be numerical also, like name="0" and so on.
foreach perform loop on array independently of index, numerical or string.
Try this:
<?php
$counter = 0;
$lastItemOrder = count($_POST);
foreach($_POST as $index => $value) {
$counter++;
if( $counter !== $lastItemOrder) {
echo $index . ": " . $value;
}?>
<br><?php
} ?>
ok now I get it, I didnt know the difference between associative and numeric arrays. I fixed it with an if statement
I have a particular JSON file that looks like this:
[
{
"objID":"kc6BvvNlVW",
"string":"bill",
"createdOn":"2018-09-18T01:51:02",
"updatedOn":"2018-09-18T01:51:02",
"number":1,
"boolean":true,
"array":["item1","item2"],
"pointer":{"type":"__pointer","objID":"hYtr54Ds","className":"Users"}
},
{
"objID":"sS1IwFPPWh",
"string":"tom",
"createdOn":"2018-09-18T01:59:40",
"updatedOn":"2018-09-18T01:59:40",
"number":12.3,
"boolean":false,
"array":["item1","item2"],
"pointer":{"type":"__pointer","objID":"tRe4Fda5","className":"Users"}
}
]
1. I need to first check if the "pointer" object has "__pointer" inside the type key and show only the objID value in an HTML table, like this:
"tRe4Fda5"
Right now, this is how my table looks like:
And here's my foreach PHP code (into a table row):
foreach($jsonObjs as $i=>$obj) {
$row_id = $i;
echo '<tr>';
foreach($obj as $key => $value){
// $value is an Array:
if (is_array($value)) {
echo '<td>';
foreach($value as $k=>$v){
// $v is a Pointer
if ($v === '__pointer') {
echo json_encode($v); // <-- WHAT SHOULD I DO HERE ?
// $v is an Array:
} else {
echo json_encode($v);
}
}
echo '</td>';
// $value is a Number:
} else if (is_numeric($value)){
echo '<td>'.(float)$value.'</td>';
// $value is a String:
} else { echo '<td>'.$value.'</td>'; }
}
As you can see in the pointer column, the string I get is:
"__pointer""hYtr54Ds""Users"
with no commas as separators, so this is the line of code I need to edit:
echo json_encode($v); // <-- WHAT SHOULD I DO HERE ?
I've tried with echo json_encode($v[$k]['__ponter']);, but no positive results.
So my final first question is: how can I get each VALUE of the "pointer" array?
2. Also, the second row of the boolean column shows noting since its value is false, shouldn't it show 0, since the first row shows 1 (true)?
You can look into the object during the second loop to see if it has a property called type and if that property is set to __pointer.
foreach($jsonObjs as $i=>$obj) {
$row_id = $i;
foreach($obj as $key => $value){
// see if $value has a type property that is set to pointer
if (isset($value['type']) && $value['type'] == "__pointer") {
// $value is the pointer object. Do with it what you will
echo "<td>" . $value['objID'] . "</td>";
}
// more code
}
}
instead of
foreach($value as $k=>$v){
// $v is a Pointer
use
foreach($value as $k)
{
//then check for pointer
if($k->type === '__pointer')
{
echo json_decode($k); //here you will get proper key and value
}
}
I am building a table in which i should put some values inside the <td></td>.
What I have is a $checked value which I convert it in some string like: id1,id2,id3
What I need to do is a loop which permits me to print this values like this. Something like this:
(for i=0, i<length of words, i++) {
echo "<td> .id[i].</td>"
}
My real variable is this:
if(isset($_POST['Submit'])) {
echo "<pre>";
$checked = implode(',', $_POST['checkbox']);
echo $checked;
Thanks!
If $_POST['checkbox'] is already an array then you don't have to implode() it before processing :
foreach ($_POST['checkbox'] as $id) {
echo '<td>' . $id . '</td>';
}
$searchquery = mysql_query("SELECT * FROM regform_admin WHERE status = 'Approved' AND month LIKE '%".$checkmonth."%' AND day LIKE '%".$checkday."%' AND year LIKE '%".$checkyear."%' OR month2 LIKE '%".$checkmonth."%' AND day2 LIKE '%".$checkday."%' AND year2 LIKE '%".$checkyear."%' OR betday LIKE '%".$checkday."%'");
while($fetchres = mysql_fetch_array($searchquery)) {
$vehicles = $fetchres['vehicles'];
echo "<b>$vehicles</b><br>";
}
include "vehicledbconnect.php";
$searchquery2 = mysql_query("SELECT * FROM vehicletbl WHERE vehicle NOT LIKE '%".$vehicles."%'");
while($fetch = mysql_fetch_array($searchquery2)) {
$v = $fetch['vehicle'];
$vehed = $fetch['vehed']; $vehcap = $fetch['vehcap']; $vehyr = $fetch['vehyr'];
$type = $fetch['type'];
echo "<tr>";
echo "<td class=light><input type = 'checkbox' name='chk[]'></td>";
echo "<td class=light>$v</td>";
echo "<td class=light>$type</td>";
echo "<td class=light>$vehyr</td>";
echo "<td class=light>$vehed</td>";
echo "<td class=light>$vehcap</td>";
echo "<td class=light>$vehcolor</td>";
echo "</tr>";
echo "$array";
}
Is it possible to echo all values inside the while statement from $searchquery inside $searchquery2?
For example the values of $searchquery is:
vehicle1
vehicle2
vehicle3
Now I'm going to echo all of it inside $searchquery2, is it possible? I try to echo $vehicles (from $searchquery) inside $searchquery2 but it only echoes the last value (example. vehicle3) because I know it is not inside the while statement of $searchquery.
Is it possible? Thanks.
Build a loop in loop.
Try this:
mysql_query("SELECT * FROM regform_admin WHERE...")
while(...)
{
$vehicles = $fetchres['vehicles'];
echo "<b>$vehicles</b><br>";
mysql_query("SELECT * FROM vehicletbl WHERE vehicle NOT LIKE '%".$vehicles."%'");
while(...)
{
echo ...
}
}
Instead of echoing inside the while loop, try buffering the output to a variable instead:
$ob = '';
while($fetchres = mysql_fetch_array($searchquery))
$ob .= '<b>' . $fetchres['vehicles'] . '</b><br>';
echo($ob);
During your second while loop, $ob is still alive and you can echo it out just as easily. Here I'm storing it as a string, but you can store the values as an array also if you need more granular access to the elements.
Update
If you want to store them into an array, try it this way:
$ob = array();
while($fetchres = mysql_fetch_array($searchquery))
$ob[] = $fetchres['vehicle']; // This pushes the current vehicle onto the end of the array
After this loop, you just have the string for each vehicle in the array, and none of the formatting. You can add that in when you output the elements. Iterate over your array with foreach:
foreach($ob as $k => $v) {
// Inside this loop, $k is the key, or index, and $v is the value.
// You can change the names of these variables by modifying the line above, e.g.
// foreach($ob as $foo => $bar) <-- $foo = key/index, $bar = value
}