Retrieve a variable whos name is has another variable in it - 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?

Related

Enter data from attendance sheet into phpmyadmin

Inserting multiple record in phpmyadmin att table keeping all the information same except attendance and student id after clicking the submit button.Its taking only one last row without attendance status.I'm fetching attendance sheet from database.I have been stuck here in my first php project.
faculty panel
<form action="<?php $PHP_SELF ?>" method="post">
<li><b>Select Courses :</b> <select name="courses" id="courses" class="form-
control action" >
<option value="">Courses</option>
<?php echo $courses; ?></select></li><br/>
<li><b>Select Semesters :</b> <br><select name="semesters" id="semesters"
class="form-control action" >
<option value="">Semesters</option></select></li><br/>
<li><b>Select Subjects :</b><br> <select name="subjects" id="subjects"
class="form-control " >
<option value="">Subjects</option></select>
<br/>
<li><b>Session No:<b><br/><input type="text" name="session_no"
id="session_no" placeholder ="Session No" class="form-control">
<br>
<label class="control-label" for="date">Date</label>
<br/>
<input class="form-control" id="date" name="date" placeholder="DD/MM/YYYY"
type="date"/>
<br/>
<li><b>Enter time:</b></li><br/>
From :<input type="time" name="time_from" id="time_from" class="form-
control"/> </li><li>
<br/>
To :<input type="time" name="time_to" id="time_to" class="form-control"/>
</li></div>
<br>
<li><label class="btn btn-info">Display attendance sheet</label> </li>
<br/>
//attendance table
<table id = "table" class = "table table-bordered">
<thead class = "alert-info">
<tr>
<th>Student ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Present</th>
<th>Absent</th>
</tr>
</thead>
<tbody>
<?php
$q_student = $conn->query("SELECT * FROM `student`")
or die(mysqli_error());
while($f_student = $q_student->fetch_array()){
?>
<tr>
<td><input name="student_no" value="<?php echo
$f_student['student_no']?>" class="form-control"
readonly/></td>
<td><?php echo $f_student['firstname']?></td>
<td><?php echo $f_student['lastname']?></td>
<td><input type="radio" name="attendance[<?php echo
$f_student['student_no']; ?>]" value="1"
class="form-control"></td>
<td><input type="radio" name="attendance[<?php echo
$f_student['student_no']; ?>]" value="0"
class="form-control"></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
//Insert Record into attendancetable
if(isset($_POST['submit']))
{
foreach ($_POST['attendance'] as $attendance){
$faculty_id =
mysqli_real_escape_string($conn,$_SESSION['faculty_id']);
$student_no =
mysqli_real_escape_string($conn,$_POST['student_no']);
$courses = mysqli_real_escape_string($conn,$_POST['courses']);
$semesters = mysqli_real_escape_string($conn,$_POST['semesters']);
$subjects = mysqli_real_escape_string($conn,$_POST['subjects']);
$session_no = mysqli_real_escape_string($conn,$_POST['session_no']);
$date = mysqli_real_escape_string($conn,$_POST['date']);
$time_from = mysqli_real_escape_string($conn,$_POST['time_from']);
$time_to = mysqli_real_escape_string($conn,$_POST['time_to']);
$attendance=var_dump($_POST['attendance']);
$conn=mysqli_connect("localhost","root","","db_sars");
$ins="INSERT INTO att( faculty_id,student_no,courses,semesters,subjects,session_no,date,time_from,time_to,attendance_status)
VALUES ('$faculty_id','$student_no','$courses','$semesters','$subjects','$session_no','$date','$time_from','$time_to','$attendance')";
}
if(#mysqli_query($conn,$ins))
{
echo "inserted";
}
else
{
die(#mysqli_error());
}
}
?><input type="submit" name="submit" value="Submit Form" class="btn btn-info"></form>
In the code you posted, you are not assigning the attendance data ($_POST['attendance']) to the $attendance variable due to use of var_dump.
You wrote:
$attendance=var_dump($_POST['attendance']);
From the php manual for var_dump:
Return Values
No value is returned.
Instead, try formatting this line like you did all the rest:
$attendance = mysqli_real_escape_string($conn,$_POST['attendance']);
Adding multiple students at a time- update
It appears that you are printing each student id in the front end table. I think that would be a better field to loop with. However, with your current front end code, it is creating a new post variable for each student id. Instead you probably want this instead:
<td><input name="student_no" value="StudentID[<?php echo $f_student['student_no']?>]" class="form-control" readonly/></td>
Note how this turns the student id into an array of student ids rather than a ton of different variables of each student ID.
Then for your foreach:
foreach ($_POST['StudentID'] as $StudentID) {
$StudentID is now updated for each iteration and allows you to look up the appropriate index in the other arrays. And you would change the pertinent rows as:
$student_no = mysqli_real_escape_string($conn,$StudentID); // The student ID is set by as in foreach
$StudentAttendance = $_POST['attendance'][$StudentID]; // Get the attendance status by looking up the student by student id in the attendance array
$attendance=mysqli_real_escape_string($conn,$StudentAttendance); // Escape input to avoid table disasters (reference Little Bobby Tables)
I haven't tested your code and understand that there is a lot more going on than this. However, it's probably best to tackle one thing at a time. What you have to do is create a loop to go over each student, and each field that you want to collect should be posted as an array with an index for each student by their student id.
Using var_dump is useful for understanding what a variable contains (for instance, it would help us to see what your variables contain if you would post the var_dump output with your question). If you have error messages, please post them as it helps guide us in the right direction as we attempt to help you out.

Submitting a specific row of a form which is generated by a loop

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';
}

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; ?>

HTML form to update Mysql with PHP (and HTML)

I've been trying to develop a real estate page where people can add listings. I am new to the world of php mysql. I have been over this problem for over a day and can't figure out where the problem is.
I have a form where people can add data. That's good and working. Now I am starting to have a place where people can add / delete / update their info. I am trying to build this step by step.
This is where a user could pull the information. My problem is with the piece of the code:
edit_form.php?idBAR=$row[id].
Full code below.
<table>
<tr>
<td align="center">EDIT DATA</td>
</tr>
<tr>
<td>
<table border="1">
<?php
include"configS_OH.php";//database connection
$order = "SELECT * FROM braaasil_brokerstour.property";
$result = mysql_query($order);
while ($row=mysql_fetch_array($result)){
echo ("<tr><td>$row[id]</td>");
echo ("<td>$row[address]</td>");
echo ("<td>$row[day]</td>");
echo ("<td>$row[hours]</td>");
echo ("<td>Edit</td></tr>");
}
?>
</table>
</td>
</tr>
</table>
Then this tutorial try to pass id through the address bar (I don't know much about php to actually say much)
It tries to upload the data into a new form where a person could edit info.
But I can't load the data into the new form. If I use where id=7, I get the info into the form. But this method of passing the info in the address bar like ?idBAR=8... and then try to catch it in the other code (where id=$idBAR), is not working.
Here is the code:
<table border=1>
<tr>
<td align=center>Form Edit Employees Data</td>
</tr>
<tr>
<td>
<table>
<?php
include "configS_OH.php";//database connection
print $database;
$order = "SELECT * FROM braaasil_brokerstour.property
WHERE id='$idBAR'";
print $idBAR;
$result = mysql_query($order) or die( mysql_error() );
$row = mysql_fetch_array($result);
?>
<form method="post" action="edit_data.php">
<input type="hidden" name="idBAR" value="<?php echo "$row[id]"?>">
<tr>
<td>Address</td>
<td>
<input type="text" name="address"
size="20" value="<?php echo "$row[address]"?>">
</td>
</tr>
<tr>
<td>Date</td>
<td>
<input type="text" name="day" size="40"
value="<?php echo "$row[day]"?>">
</td>
</tr>
<tr>
<td>Time</td>
<td>
<input type="text" name="time" size="40"
value="<?php echo "$row[hours]"?>">
</td>
</tr>
<tr>
<td align="right">
<input type="submit"
name="submit value" value="Edit">
</td>
</tr>
</form>
</table>
</td>
</tr>
</table>
I tried an tried and tried..
Thank you for your time in advance.
WHERE id='$idBAR'
You haven't assigned $idBAR any value. You need to read it from the $_GET array first:
$idBAR = $_GET['idBAR'];
You should, of course, check that this value exists first, and is acceptable.
I don't see anywhere you have actually used the GET data, just the reference name which is used in GET.
If you first query is working and is getting the $row['id'] value ok - you can verify this when you go to edit_form.php, in your browser URL bar at the top, does it say this:
edit_form.php?idBAR=7
(or whatever number should be there)
If so, then you just need to use the PHP GET. Your data is stored in $_GET[], and in this case, the reference name is idBAR. So your id from your previous page query is sent through the link into your URL, and on your edit_form.php page, you'd use that data as:
$_GET['idBAR']
You can use that, but personally I assign the data to a variable, such as:
$strGetId = $_GET['idBAR'];
Then you can use $strGetId throughout your code.
Also, check things like isset(), empty() etc, just so you know you are working with A) something is actually there, and B) it's not empty etc
if you are putting a variable directly in a string without concatenating, it can't be an array variable; you must concatenate those you also need to surr. so this
echo ("<td>Edit</td></tr>");
should be this
echo ("<td>Edit</td></tr>");
also, it looks like your form is sending data with POST. When you pass form data in the url string after the question mark, that is passing with get.
so...in your form where you want to use that variable, you set it up like this
$idBAR=$_GET['idBAR']; //to get the variable if it was part of the URL
$idBAR=$_POST['idBAR']; //if it was sent with post, as is the case with your form
also, request contains both get and post, so
$idBAR=$_REQUEST['idBAR'];
will work in either case.
The problem is the $row[id] is seen as text just like everything else. You want the value of $row[id]. Instead of
echo ("<td>Edit</td></tr>");
try
echo ("<td>Edit</td></tr>");

PHP Loop through HTML table elements from submit form

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>";?>

Categories