I have a jQuery function to dynamically add rows containing input fields, this exists on a form, the function adds text boxes (distinct names) to each cell in the table
an example of the generated HTML would be:
<table width="400" border="0" cellspacing="0" cellpadding="2px" margin="0" >
<tbody>
<tr>
<td><input type="text" name="name_1"></td>
<td><input type="text" name="surname_1"></td>
<td><input type="text" name="age_1"></td>
</tr>
<tr>
<td><input type="text" name="name_2"></td>
<td><input type="text" name="surname_2"></td>
<td><input type="text" name="age_2"></td>
</tr>
<tr>
<td><input type="text" name="name_3"></td>
<td><input type="text" name="surname_3"></td>
<td><input type="text" name="age_3"></td>
</tr>
</tbody>
I am reading the "$_POST['varName'] data with the following code:
<?php
$cnt = 1 ;
$fName = ( $name ."_" .$cnt) ;
do {
echo("$_POST[$fName] <br>");
$cnt = $cnt +1 ;
$fName = ( $fldName ."_" .$cnt) ;
} while (isset($_POST[$fName]));
?>
however, i would like to simply loop through each row in the table and read the data sequentially in a loop (using PHP), my idea is to pass the table object to a php function, is this possible?
Basically i am looking for a solution to read the table data, where each row contains input boxes "name_X", "surname_x" and "age_x" and i will not know how many rows exist at design time... (i will never have more than 9 rows)
Hope this is clear!
... Any Suggestions?
i'm pretty sure you must use an array in the name="" values
<td><input type="text" name="name[]"></td>
You could use a hidden field and set there the number of rows as value using javascript.
In the php script you can then use a simple for loop.
Simething like this:
$rowCount = $_POST['hiddenName'];
for($i=1; i<=$rowCount; $i++)
{
$_POST['name_'.$i]
...
}
I Used both the name array and the simple for loop to find a suitable answer. Thanks All!
HTML: I have a js function that adds the following to a table dynamically (Button on form)
<tr>
<td><input type="text" name="name[]" ></td>
<td><input type="text" name="surname[]" ></td>
<td><input type="text" name="age[]"> </td>
</tr>
PHP: and this is the way that i process the table within the form
<?php
$rowCount = count($_POST['name']);
echo "<table>";
for($i=1; $i<=$rowCount; $i++)
{
echo "<tr>";
echo "<td>".$_POST['name'][$i -1]."</td>";
echo "<td>".$_POST['surname'][$i -1]."</td>";
echo "<td>".$_POST['age'][$i -1]."</td>";
echo "</tr>";
}
echo "</table>";?>
Related
This is the code for the admin panel of a certain site. Appointments asked by customers will be shown in this page. The admin will be able to change the appointments based on availability.
<?php
while($row = mysqli_fetch_assoc($result)){
?>
<form action="adminEdit.php" method="POST">
<tr>
<td><input type="text" id="name" value="<?php echo $row['Name'];?>"></input></td>
<td><input type="text" id="address" value="<?php echo $row['Address'];?>"></input></td>
<td><input type="text" id="phone" value="<?php echo $row['Phone'];?>"></input></td>
<td><input type="text" id="license" value="<?php echo $row['Car_License_No'];?>"></input></td>
<td><input type="text" id="engine" value="<?php echo $row['Car_Engine_No'];?>"></input></td>
<td><input type="text" id="date" value="<?php echo $row['Date'];?>"></input></td>
<td><input type="text" id="mechanic" value="<?php echo $row['Mechanic'];?>"></input></td>
<td><input type="submit" name="submit" value="Change"/></td>
</tr>
</form>
<?php
}
?>
Here, each row of data has a corresponding button which will be used for changing or modifying the records of that particular row. Once the admin changes a specific appointment it should get updated in database.
My problem is, all the rows are getting generated by a while loop. Now how can I access a specific row when the change button of that specific row has been clicked ? As the rows are getting generated by a loop, I wont be able to access them bynameoridbecause all of them will have the samenameandid`.
Searched for relevant questions but none of them matched with my scenario. It will be of great help getting an answer. Thanks in advance.
Personally I'd be inclined to take the output from being in the loop for better control over the data and resolving the issue. You're also creating a new form on each loop.
Just loop the DB and create a new variable, then use that variable to output the data in the form.
Example code to show the basic idea, not tested or stating it's complete etc:
while ($row = mysqli_fetch_assoc($result)) {
$someNewVar[$row['id']] = $row;
// The 'id' index would be from DB which identifies individual rows
}
?>
<form action="adminEdit.php" method="POST">
<?php
foreach ($someNewVar as $index => $value) {
?>
<tr>
<td>
<input
type="text"
id="<?php echo $index;?>"
value="<?php echo $value['Name'];?>">
</input>
</td>
<td>
<input
type="submit"
name="submit"
value="Change"/>
</td>
</tr>
<?php
}
?>
</form>
Then you'd need to have the row ID passed from clicking the submit button.
On a side note, this whole approach could be tidied up, and data should be obtained in one file separate to where you output it.
Then in the file which obtains the data you can set the array to something which is also identified in the output file to manage if no data was obtained.
ie
getData.php
while ($row = mysqli_fetch_assoc($result)) {
$dataFromDb[$row['id']] = $row;
}
$someNewVar = !empty($dataFromDb) ? $dataFromDb : false;
showData.php
if ($someNewVar) {
// do the loop and form
} else {
echo 'sorry no data found';
}
<tr contenteditable>
<td><center><?php echo $nama = $isi['nama']; ?></center> </td>
<td><center><?php echo $jk = $isi['jk']; ?></center> </td>
I have this code,
And I dunno how to save it on my database.
if you guys don't mind, you can check the picture here : http://imagizer.imageshack.us/a/img673/4384/Ww9PKg.jpg
What I suggest is instead of making the table content editable, and allow users to change it, put the data that will be updated on input fields, and post to your PHP script to save:
<form action="/post.php" method="post">
<tr>
<td><input type="text" name="nama-0" value="<?php echo $nama = $isi['nama']; ?>"></td>
<td><input type="text" name="jk-0" value="<?php echo $jk = $isi['jk']; ?>"></td>
</tr>
</form>
But if you still need to use the table without the input elements (I've no idea why that'd be required) then use javascript to extract the values from table, and then submit to your PHP script.
I'm trying to get the website to send the calculation results to another page. The code below is working but I have no idea how to get the rows with the results to be shown in a new page.
I know that i have to change the action below to /mynewpage
But I just want the results not the whole table.
I have no idea what to do to the code to make it show the results only in a new page. IF everything statys in the same page the calculator works well.
It's my first attempt with PHP, I clearly have no idea of what I'm doing. Many thanks in advance.
<?php
if (isset($_POST['valuea'])) $valuea = $_POST['valuea'];
if (isset($_POST['valueb'])) $valueb = $_POST['valueb'];
if (isset($_POST['valuec'])) $valuec = $_POST['valuec'];
if (isset($_POST['valued'])) $valued = $_POST['valued'];
if (isset($_POST['valuee'])) $valuee = $_POST['valuee'];
$balance = $valuec * $valuee;
$newphone = $valuea;
$total = $balance + $valuea;
$total2 = $balance + $valueb;
echo <<<_END
<form method='post' action='/'>
<table border='0' width='500px' cellpadding='3' cellspacing='1' class="table">
<tr class="calcheading"><td colspan="2"><strong>CALCULATOR</strong></td></tr>
<tr class="calcrow"><td>Phone Value:</td><td align="center"><input type='text' name='valuea' value="$valuea"/></td></tr>
<tr class="calcrow"><td>Phone upfront cost:</td><td align="center"><input type='text' name='valueb' value="$valueb"/></td></tr>
<tr class="calcrow"><td>Monthly contract cost:</td><td align="center"><input type='text' name='valuec' value="$valuec"/></td></tr>
<tr class="calcrow"><td>Contract duration:</td><td align="center"><input type='text' name='valued' value="$valued"/></td></tr>
<tr class="calcrow"><td>No. months left in the contract:</td><td align="center"><input type='text' name='valuee' value="$valuee"/></td></tr>
<tr class="submit"><td colspan="2"><input type='submit' value='Calculate'/></td></tr>
_END;
?>
<tr class="calcheading"><td colspan="2"><strong>OPTION 1 - PAY REMAINING OF THE CONTRACT AND BUY SAME PHONE UNLOCKED</strong></td></tr>
<tr class="calcrow">
<td><i>Payment left to network:</td>
<td align="center"><input type="text" value="<?php echo round($balance)?>"></td></i>
</tr>
<tr class="calcrow">
<td><i>New unlocked phone:</td>
<td align="center"><input type="text" value="<?php echo round($newphone)?>"></td></i>
</tr>
<tr class="calcrow">
<td><i>TOTAL:</td>
<td align="center"><input type="text" value="<?php echo round($total)?>"></td></i>
</tr>
<br>
<tr class="calcheading"><td colspan="2"><strong>OPTION 2 - PAY BALANCE LEFT AND GET SAME PHONE ON A NEW CONTRACT*</strong></td></tr>
<tr class="calcrow">
<td><i>Payment left to network:</td>
<td align="center"><input type="text" value="<?php echo round($balance)?>"></td></i>
</tr>
<tr class="calcrow">
<td><i>New contract phone initial cost:</td>
<td align="center"><input type="text" value="<?php echo round($valueb)?>"></td></i>
</tr>
<tr class="calcrow">
<td><i>TOTAL:</td>
<td align="center"><input type="text" value="<?php echo round($total2)?>"></td></i>
</tr></table>
</form>
You can either send the values in a form and receive them on the other page using
$value1 = $_GET['value1'];
$value2 = $_GET['value2']; // etc
The other method would be saving them in a session variable, at the top of any pages where you wish to use session variables, call session_start(), then save them
$_SESSION['value1'] = $value1;
Then in another page, you can call them by simply
echo $_SESSION['value1'];
I'm not sure what you mean by new page? If you have a script like process.php that has that code then you can add session_start(); as your first line after the php start tag. By using $_Session['result']=$calc_result; on the 'process.php' you will store the value in your session. In the 'new page' script you call session_start(); again and you can get the stored value by saying $_Session['result'].
There are many ways to print your answers on a new page but lets keep it simple: A good way to do it would be for you to separate out the HTML form that posts the values and the php calculation logic on two different pages. So for example, your HTML form is in one file values.php (does not have any php code, you can name it with a .html prefix as well) and the php code is in another file calc.php. Now, to your form, specify an action such as
<form method='post' action='calc.php'>
This will post all the values to calc.php where your calculation code is and you can display the results however you please (not limited to a form again) but in a table or so on. Once you learn ajax, you'll never want to come back to doing this.
Here is a working barebones example: http://runnable.com/VEKvtTTrkXFwjAwL/calculator555-for-php
Dunno if the title makes sense, but I have a variable which would to put it in basic terms would be called like this:
$_POST['something'+$variable2]
I have a form which is for editing selected records, this form contains entries for all previously selected records:
<form name="input" action="editcar.php" method="POST">
<input type="submit" value="Yes">
while($row = mysqli_fetch_assoc($result))
{
echo'
</div>
<table style="color:white">
<tr>
<td style="text-align:right">Manufacture:</td><td><input type="text" name="manufacture'.$row['carIndex'].'" value="'.$row['make'].'"></td>
<td style="text-align:right">Model: </td><td><input type="text" name="model'.$row['carIndex'].'" value="'.$row['model'].'"></td>
</tr>
<tr>
<td style="text-align:right">Colour: </td><td><input type="text" name="colour'.$row['carIndex'].'" value="'.$row['colour'].'"></td>
<td style="text-align:right">Reg: </td><td><input type="text" name="reg'.$row['carIndex'].'" value="'.$row['Reg'].'"></td>
</tr>
<tr>
<td style="text-align:right">Price: </td><td><input type="text" name="price'.$row['carIndex'].'" value="'.$row['price'].'"></td>
<td style="text-align:right">Mileage: </td><td><input type="text" name="mileage'.$row['carIndex'].'" value="'.$row['miles'].'"></td>
</tr>
<tr>
<td style="text-align:right">Max MPH: </td><td><input type="text" name="mph'.$row['carIndex'].'" value="'.$row['mph'].'"></td>
<td style="text-align:right">MPG: </td><td><input type="text" name="mpg'.$row['carIndex'].'" value="'.$row['mpg'].'"></td>
</tr>
</table>
</form>
</div> ';
}
?>
</form>
The form is looped for each record previously chosen, to enable mass editing. The isue arouses when I realised I'd have multiple inputs with the same name, so I did:
<input type="text" name="model'.$row['carIndex'].'" value="'.$row['model'].'">
Placing the primary key of the record it was currently tired to on the end of it's name. Which seemed like a logical way to go about things.
However now I need to call these variables to place in the mysql query and I dunno how to do that, or even if I can.
I have the selected records saved in an array so I have:
foreach ($postid as $carID)
{
$query = "stuff";
mysqli_query($db, $query);
}
Each loop has $carID containing the variables that was put on the end of the form input names.
So something like:
$_POST['something'+$variable2]
is all I can think of but doesn't work.
Any method that works for my overall code is welcome not just a solution to the issue I've made.
Actually your way should work. Just replace the + with . in $_POST['something'+$variable2].
My tip is: use an array as name in your html instead:
<input type="text" name="model[]" value="'.$row['model'].'">
On php-Side you can loop through all $_POST['model'] since its an array now.
You can add the index for every entry in your html, too:
<input type="text" name="model['.$row['carIndex'].']" value="'.$row['model'].'">
PHP uses a dot for concatenation, not + like Java and Javascript:
$_POST['something' . $variable2]
Try something like this:
<form ...>
<?php
while($row = mysqli_fetch_assoc(...):
$index = $row['carIndex'];
?>
<input type="text" name="carmodel[<?php echo $index?>][model]" value="<?php echo $row['model'] ?>">
<?php endforeach; ?>
</form>
This way you will have the data stored in $_POST['carmodel'] as an array indexed by carIndex value as the structure of data in $_POST is defined by names of inputs, here you will have names likee carmodel[1][model] for example so then in post it will be in $_POST['carmodel'][1][model]
you can read here as well
How would I create this array structure in an HTML form?
I have a working form with a javascript 'Add Row' button, data collection and processing by PHP. While it works, the code seems fairly high-maintenance and clumsy to me (for one thing, every time I change the form I need to work the same changes into the js that adds the new row). I'm looking for suggestions to make it more sleek and simple. Currently I'm assigning each input a unique name, with hidden input that keeps track of the number of rows for me, and then I use that number to determine the amount of for loops the PHP script needs to work through to post to the database.
One thing I've considered is changing from input names to using name[], but I'm not sure if that's the right method for my needs, and how I post each row as a separate record to the database. In any case, here's the code.
HTML
<table id="table1">
<tr style="display: none"><td colspan="2">
<input type="hidden" id="samp_count" name="samp_counter" value="" />
<input type="hidden" value="sample" name="type1" /></td>
</tr>
<tr>
<td >pic caption </td>
<td>
<input type="text" name="desc1"/></td></tr>
<tr>
<td >extended description</td>
<td><textarea style="width:100%" rows="7" name="notes1"></textarea></td>
</tr>
<tr>
<td>pic file</td>
<td><input id="pic_file1" type="file" name="pic1" /></td>
</tr>
</table>
<button type="button" class="add_row" width="40px" id="samp_add_button">add row
JavaScript for the button
$(document).ready(function(){
$("#samp_count").val("1");
$("#samp_add_button").click(function(){
var iter_str=$("#samp_count").val();
var pic_id = "#pic_file" + iter_str;
if (!$(pic_id).val()){
$("#samp_error").css("visibility","visible");
}
else{
iter_str ++; // update counter
$("#samp_count").val(iter_str); //reset counter in table header to current count
var a = '<tr><td colspan="2" ><span>pic caption<input type="text" name="desc'+iter_str+'"/></span><br /></td>";
var b = '<td rowspan="3">extended description<br /><textarea style="width:100%" rows="7" name="notes'+iter_str+'"></textarea></td>';
var c = '<tr><td colspan="2" >pic file</td><td><input id="pic_file'+iter_str+'" type="file" name="pic'+iter_str+'" /></td></tr>';
$("#table1").append(a+b+c);
$("#samp_error").css("visibility","hidden");
}
});
});
PHP
<?php
if(isset($_POST['send_button'])&&$isValid==TRUE){
$user = $_POST['user'];
$count_str1 = $_POST['samp_counter'];
$count1 = intval($count_str1);
for ($i=1; $i <= $count1; $i++) {
$desc= "desc".$i;
$pic= "pic".$i;
$notes= "notes".$i;
$desc_con = $_POST[$desc];
$notes_con = $_POST[$notes];
if($_FILES[$pic]["name"]){
if( formFileUpload($pic, $user)){ //custom function to validate and upload pics-- not relevant to question at hand
$uid_path = "portfolios/".$user."/";
$file_path=$uid_path.$_FILES[$pic]["name"];
$dbh = new PDO('mysql:host=localhost;dbname=db', 'admin','pass');
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
$statement=$dbh->prepare("INSERT INTO portfolios (UserID, Description, FilePath, FileType, Notes) VALUES (?,?,?,?,?)");
$statement->bindParam(1,$user);
$statement->bindParam(2,$desc_con);
$statement->bindParam(3,$file_path);
$statement->bindParam(4,$_POST[type1]);
$statement->bindParam(5,$notes_con);
$statement->execute();
}
else{
$fileErrorDis="inline";
$isValid=FALSE;
} }}
?>
Link to working website -- self-explanatory but text in Hebrew (in some of the forms, the js has not been updated and the new row does not resemble the original one)