Can't transfer an object array with html form - php

i have a little problem with my program and not so experienced in php. I want to transfer an array of objects with a html form to my php file. First i will let you take a look on my code:
location.php (with executable forms)
<form action="action/add_items.php" method="POST">
<table border="1" width="20%">
<thead>
<th>
<?= $lang["location_task"][$location->getProperty("location_id")][$location_task->getProperty("location_task_id")]; ?>
</th>
</thead>
<tbody>
<?php
$location_task_items = $location_task->getProperty("location_task_items");
foreach ($location_task_items as $location_task_item) {
?>
<tr>
<td>
<?= $lang["item"][$location_task_item->getProperty("location_task_item_id")]; ?>
</td>
<td>
<?= $location_task_item->getProperty("location_task_item_value"); ?>
</td>
</tr>
<?php
}
?>
<tr>
<td></td>
<td>
<input type="hidden" value="<?php print_r($location_task_items); ?>" name="location_task_items"/>
<input type="submit" value="start"/>
</td>
</tr>
</tbody>
</table>
</form>
You can see that i only print the array in the input hidden value. Is that right?
add_items.php
$location_task_items = $_REQUEST["location_task_items"];
foreach($location_task_items as $location_task_item) {
if($Player_Has_ItemsClass->getObjectByIds($player_id, $location_task_item->getProperty("location_task_item_id")) == null) {
$player_has_items_attributes = array();
$player_has_items_attributes["player_has_items_player_id"] = $player_id;
$player_has_items_attributes["player_has_items_item_id"] = $location_task_item->getProperty("location_task_item_id");
$player_has_items_attributes["player_has_items_item_value"] = $location_task_item->getProperty("location_task_item_value");
$player_has_items = new Player_Has_Items($player_has_items_attributes);
$Player_Has_ItemsClass->insertObject($player_has_items);
} else {
}
}
I only get the array as string and this exception on the foreach in add_items.php:
Invalid argument supplied for foreach()
I also tried it with json_encode and json_decode:
print_r(json_encode($location_task_items))
json_decode($_REQUEST["location_task_items"]);
but only get (object attributes were public):
Call to undefined method stdClass::getProperty()
Thanks for you help :)

In your hidden field use json_encode and then in your destination use json_decode:
<input `type="hidden" value='<?php echo json_encode($location_task_items); ?>' name="location_task_items"/>`

You could do this
<input type="hidden" value="<?php echo serialize($location_task_items); ?>" name="location_task_items"/>
and then
$location_task_items = unserialize($_REQUEST["location_task_items"]);

Related

Making a table with foreach, trying to submit data using each table row

So its been over 10 years since writing any code what so ever so i might be way off here. I have a table showing all students in a classroom populated by a foreach loop with an added box to input their grade. I need 1 submit button to insert one new row per student in the grades table in my database with their grade and the assignment name that is selected above.
I know i need to identify each grade value im just unsure how and it's only posting the person in the last row.
global $wpdb;
$asnames = $wpdb->get_results( "SELECT * FROM assignments" );
$results = $wpdb->get_results( "SELECT * FROM enrolled" );
?>
<div class="container"><center>
<form action ="<?php echo $_SERVER['REQUEST_URI']; ?>" method ="post">
<table class="form-table" id='topper'>
<tbody>
<tr>
<th>Assignment Name</th>
</tr>
<tr>
<td>
<select name="Assignment">
<?php foreach($asnames as $asname) { ?>
<option value="<?php echo $asname->id ?>"><?php echo $asname->assign_name ?></option>
<?php
} ?>
</select>
</td>
</tr>
</tbody>
</table></center>
</div>
<br><br>
<div class="container"><center>
<form action ="<?php echo $_SERVER['REQUEST_URI']; ?>" method ="post">
<table class="form-table" id='student'>
<tbody>
<tr>
<th>Students Name</th>
<th>Points</th>
</tr>
<?php foreach($results as $row){ ?>
<tr>
<td><?php echo "$row->student_name" ?></td>
<td><input type="text" class="regular-text" name="Grade"></td>
</tr>
<?php } ?>
<!-- </tbody> -->
</table>
<p><input type="submit" name="submitinsert" id="submitinsert" class="button button-primary" value="Submit"/></p> </form>
</center></div>
<?php
if ($_POST['submitinsert']){
$result = $wpdb->insert(
'grades',
array(
"student_name" => $row->student_name,
"assignment_id" => $asname->id ,
"grade" => $_POST['Grade']
)
);
}
I cant seem to get it to grab each row as it is in the table to insert, only the last row gets put in.
EDIT: I got the grade input worked out now just trying to get each loop put into the database with the single submit button.

How to pass php variable outside of while loop within same page

I have faced small problem regarding passing php variable outside of PHP loop. I have created table and form in same page. First table is displayed and the through edit link in form pop up dialog box appears. I want to pass dynamic ID to dialog box after click edit link. My page includes a php table and form.
PHP/HTML Table
<table>
<th>ID</th>
<th>Title</th>
<th>Edit</th>
<?php
$query="select * from video order by id desc";
$result=$con->query("SELECT * FROM video ORDER by id DESC") or die($con->error);
while($row=$result->fetch_assoc()){
$id=$row['id'];
$heading=$row['heading'];
?>
<tr>
<td>
<?php echo $id ?>
</td>
<td>
<?php echo $heading ?>
</td>
<td>
Edit
</td>
</tr>
<?php } ?>
</table>
After this table, I want to display data in this form
PHP Form in dialog box
<div class="remodal" data-remodal-id="modal2" role="dialog" aria-labelledby="modal2Title" aria-describedby="modal2Desc">
<form action="" method="POST" enctype="multipart/form-data">
<table>
<tr>
<th>Video ID</th>
<td>
<input type="number" value="<?php echo $id?>" name="id" readonly></input>
</td>
</tr>
<tr>
<th>Video Title</th>
<td>
<input type="text" value="<?php echo $heading?>" name="title"></input>
</td>
</tr>
</table>
</form>
</div>
I know that while loop can't connect to popup dialog box form, so my code prints only data of first row. If I include whole code within while loop, my table structure become mess. Is there any idea to pass ID outside of while loop ? I tried using global variable method, but it doesn't work. Perhaps I can't properly use global variable. Thanks
In your while loop store values in to array like this:
<?php
$query="select * from video order by id desc";
$result=$con->query("SELECT * FROM video ORDER by id DESC") or die($con->error);
$array = [];
while($row=$result->fetch_assoc()){
$id=$row['id'];
$heading=$row['heading'];
$array[$id] = $heading;
?>
And in your html table like this :
<table>
<tr>
<th>Video ID</th>
<th>Video Title</th>
<?php foreach ($array as $key => $val){ ?>
<td>
<input type="number" value="<?php echo $key?>" name="id" readonly></input>
</td>
<td>
<input type="text" value="<?php echo $val?>" name="title"></input>
</td>
<?php } ?>
</tr>
</table>

Codeigniter, Passing Inputs of Array and then display the result

Excuse me if this question is already asked everywhere, but i cant find answer that worked.
So I have a dynamically generated table, which is generated by selecting rows from a table in a database.
This is the view file that create the table.
all rows except the heading are created based on how many data found in the table in a database, so, all the inputs are have name like
<form class="form-horizontal" role="form" id="formDtKryw" method="POST" action="updKryw">
<div class="table-responsive form-group row">
<table class="table table-hover table-condensed table-bordered">
<thead class="text-center">
<tr>
<th>No</th>
<th>Nama</th>
<th>Telepon</th>
</tr>
</thead>
<tbody>
<?php $no = 0;
foreach ($dftr_crKryw as $data_crKryw):
$no_ktp[$no] = $data_crKryw->no_ktp;
?>
<input type="hidden" name="no_ktp[<?php echo $no; ?>]" id="no_ktp[<?php echo $no; ?>]" value="<?php echo $data_crKryw->no_ktp; ?>">
<tr>
<td><?php echo $no+1; ?></td>
<td><?php $this->db->select('nama,')->from('dt_prbd')->where('no_ktp', $data_crKryw->no_ktp);
$qry = $this->db->get();
if ($qry->num_rows() > 0) {
foreach($qry->result() as $data):
echo $data->nama;
endforeach;
}
?></td>
<td><?php
if ($data_crKryw->memo == NULL) {
?>
<select class="form-control input-sm" name="memo[<?php echo $no; ?>]" id="memo[<?php echo $no; ?>]">
<option value="">---Pilih---</option>
<option value="Memo 1">Memo 1</option>
<option value="Memo 2">Memo 2</option>
<option value="Memo 3">Memo 3</option>
</select>
<?php
}
else {
echo $data_crKryw->memo;
}
?></td>
</tr>
<?php
$no++;
endforeach;
}
?>
<input type="hidden" name="totData" id="totData" value="<?php echo $no; ?>">
<tr>
<td colspan="11" align="right"><button type="submit" id="submit" class="btn btn-primary">Simpan Data</button> <button type="reset" class="btn btn-danger">Hapus Form</button></td>
</tr>
</tbody>
</table>
</div>
</form>
This is the Controller that should catch the inputs
function updKryw(){
$totData = $this->input->post('totData');
$no_ktp = $this->input->post('no_ktp');
$memo = $this->input->post('memo');
$frmUpdKryw = array(
'totData' => $totData,
'no_ktp' => $no_ktp,
'memo' => $memo
);
$this->load->view('display_data', $frmUpdKryw);
}
And this is the view file that suppose to view all the captured information from the form
<html>
<head></head>
<body>
<?php
for($x = 0; $x < $totData; $x++){
echo $totData . "<br>";
echo $no_ktp[$x] . "<br>";
echo $memo[$x] . "<br>";
}
?>
</body>
</html>
All that displayed is only the $totData, and the $no_ktp[$x] and $memo[$x] is not display anything.
Anyone can help please if there is any error in my code or my logic.
Thanks in advance.
=========================================================================
edit: i started to think that my php engine is broken. why?
even this simple form doesn't display anything.
form.php
<form name="myForm" method="post" action="go.php">
<input type="text" name="name" value="firstname">
<input type="text" name="addr" value="firstaddr">
<button type="submit" name="submit" id="submit">save</button>
</form>
go.php
$name = $_POST[name];
$addr = $_POST[addr];
echo $name;
echo $addr;
First I recommend debug before saving data to $frmUpdKryw array
$this->input->post(NULL, TRUE); // returns all POST items with XSS filter
$this->input->post(); // returns all POST items without XSS filter
Then if data is not empty, before
$this->load->view('display_data', $frmUpdKryw);
add
var_dump($frmUpdKryw);
if all is good here, then to debug in beginning of the view
var_dump($totData);
var_dump($no_ktp);
var_dump($memo);
If all is good here then problem is in your loop, so you will need just fix it. Either you will know where you have problems:
failed with sending data with POST
failed with saving to new variable
failed with sending data to view
and last failed with loop
Hope it will help
when I solve another problem within the same app, this problem is fixed too, the problem is not in the code or logic. all codes are works as expected.
here are the link for the solution. not the solution that I expect, but its working.
The Solution
thanks to Abdulla and Oleg Sapishchuk

Store PHP/SQL foreach form items in variables

Sorry I'm a bit of a noob when it comes to PHP but I just wondered if someone had an idea on how I could solve this PHP/SQL problem.
I have a PDO statement that gets all users from a database.
With the array of users from the database I create a foreach loop to display all of the users in a table which I want to use to select a specific user, enter a number in the row of the user I select, then click submit and store the users name and also the number. I will use this information to populate another database later.
My question is, I cant seem to reference the user or the number in the table to extract the user and number I enter. When I try and request the numbered entered in the index.php, it will only ever display a number if I enter a number for a the final user in the table. When I try and view the FullName it never works and I get 'Undefined index: FullName' error.
I also specified to 'POST in the form but it doesnt seem to be doing that.
Does anyone have any ideas?
Thanks
//function.php
function getName($tableName, $conn)
{
try {
$result = $conn->query("SELECT * FROM $tableName");
return ( $result->rowCount() > 0)
? $result
: false;
} catch(Exception $e) {
return false;
}
}
//form.php
<form action "index.php" method "POST" name='form1'>
<table border="1" style="width:600px">
<tr>
<th>Name</th>
<th>Number Entered</th>
<tr/>
<tr>
<?php foreach($users as $user) : ?>
<td width="30%" name="FullName">
<?php echo $user['FullName']; ?>
</td>
<td width="30%">
<input type="int" name="NumberedEntered">
</td>
</tr>
<?php endforeach; ?>
</table>
<input type="submit" value="submit"></td>
</form>
//index.php
$users = getName('users', $conn);
if ( $_REQUEST['NumberedEntered']) {
echo $_REQUEST['NumberedEntered'];
echo $_REQUEST['FullName'];
}
The variable FullName isn't transmitted by your form to index.php. Only values of form elemnts are sent. You can add a hidden form field, that contains FullName like this:
<input type="hidden" name="FullName" value="<?php echo $user['FullName']">
But your second problem is, that your foreach loop will create several input fields with the exact same name. You won't be able to recieve any of the entered numbers, except the last one. have a look at this question for possible solutions.
Update
Putting each row in individual form tags should solve your problem:
<?php foreach($users as $user) : ?>
<form action="index.php" method="POST">
<tr>
<td align="center" width="40%" >
<?php echo $user['FullName']; ?>
<input type="hidden" name="FullName" value="<?php echo $user['FullName']; ?>" />
</td>
<td width="30%">
<input name="NumberedEntered"/>
</td>
<td>
<input type="submit" value="submit"/>
</td>
</tr>
</form>
<?php endforeach; ?>

process hidden field with jquery and calculate

I have an html table I've updated to use checkboxes to be able to delete multiple files:
<table>
<thead>
<tr>
<th>Camera Name</th>
<th>Date Created</th>
<th>Video Size</th>
<th>Video Length</th>
<th>
<button type="submit" class="deletebutton" name="delete_video" value="Delete" title="Delete the selected videos" onClick="return confirm('Are you sure you want to delete?')">Delete</button><br>
<input type="checkbox" name="radioselectall" title="Select All" />
</th>
</tr>
</thead>
<tbody>
<?php
for($i=0;$i<$num_videos;$i++)
{
//do stuff
//Note: I'm looping here to build the table from the server
?>
<tr >
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo $result_videos[$i]["camera_name"]; ?>
</td>
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo setlocalTime($result_videos[$i]["video_datetime"]); ?>
</td>
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo ByteSize($result_videos[$i]["video_size"]); ?>
</td>
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo strTime($result_videos[$i]["video_length"]); ?>
</td>
<td>
<form name="myform" action="<?php echo htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST">
<input type="checkbox" name="radioselect" title="Mark this video for deletion"/>
<input type="hidden" name="video_name" value="<?php echo $result_videos[$i]["video_name"]; ?>" />
</form>
</td>
</tr>
I started with first creating some jquery code to create a select all/deselect all button in the table heading and just a test to show I can find which boxes are checked. That all works:
//selectall checkboxes - select all or deselect all if top checkbox is marked in table header
$("input[name='radioselectall']").change(function()
{
if( $(this).is(':checked') )
{
$("input[type='checkbox']","td").attr('checked',true);
}
else
{
$("input[type='checkbox']","td").attr('checked',false);
}
});
//process checkboxes - which ones are on
$(".deletebutton").click(function() {
$("input[name='radioselect']:checked").each(function(i){
alert(this.value);
});
});
So the part where I'm stuck is I don't know where to go from here. I need to pass all the video_names of all the videos selected (with the checkboxes). video_name is part of a hidden field in my form. So I need to pass that to my php function when the delete button is selected. Not really sure how to tackle this. Hope this makes sense.
Simple solution maybe:
Change your checkboxes to have a value of 1 and a name of $result_videos[$i]["video_name"]; in the table rows, make the form encapsulate the whole table.
Then on submit you can do something like:
foreach ($_POST as $key => $value) {
//Delete $key (the name) where $value == 1
}
Your approach is fine if you want to access the hidden fields through jQuery at a given point but once you submit the form and lose the DOM, the PHP processing page will have no way to relate the selected checkboxes with the hidden fields as there is no consistent naming scheme.
One approach would be to use the loop counter to suffix the two in order to pair them up:
<input type="checkbox" id="radioselect_<?= $i ?>" title="Mark this video for deletion" value="1" />
<input type="hidden" id="video_name_<?= $i ?>" value="<?php echo $result_videos[$i]["video_name"]; ?>" />
This would be good if you want to relate more than the two fields. Otherwise, you could just use the video_name as the value of the checkbox, as Ing suggested.

Categories