POST variable to another class - php

I have a search function using XPath, when results are shown a check box is also echoed.
<form name="save" method="POST" action="saveProcess.php">
<?php
foreach ($holidays as $holiday)
{
$resultTable .= "<p>{$holiday->title}" . "<br/>" .
"{$holiday->pubDate}" . "<br>" .
"{$holiday->description}" . "<input type='checkbox' name='chk' value='{$holiday->title}' />" . "<br /></p>";
}
?>
<input type="submit" value="submit"/>
</form>
I would like this check box to hold the value of {$holiday->title} which when the form is submitted will be shown in saveProcess.php, i use the isset method to check if the variable is set and it is not.
if (isset($_POST['chk'])) {
echo $_POST['chk'];
}
else
{
echo"variable is not set";
}
Where am i going wrong?

The problem is that you name each checkbox "chk", and when you submit the form, the values get overwritten. That's why it doesn't get anything in saveProcess.php. What you need to do, is either specify that the $_POST["chk"] can contain an array of value, like so:
<input type='checkbox' name='chk[]' value='{$holiday->title}' />
Notice the square brackets in the name. Now $_POST["chk"] will be an array.
Another way, would be to leave the html as it is, and just get the data, in saveProcess.php, using:
$HTTP_POST_VARS["chk"]
The first part basically explains why it doesn't work and how to fix it, while the second suggestion, is merely an alternate way of getting the data.
Have a great day!

Your code looks ok to me, just remember that the value of a checkbox is posted only if the checkbox is checked, if it's not checket $_POST['chk'] is not set
EDIT - since you are revriting your checkboxes as suggested in the comment use an array
<?php
foreach ($holidays as $holiday)
{
$resultTable .= "<p>{$holiday->title}" . "<br/>" .
"{$holiday->pubDate}" . "<br>" .
"{$holiday->description}" . "<input type='checkbox' name='chk[]' value='{$holiday->title}' />" . "<br /></p>";
}
?>
And then server side $_POST['chk'] will be ann array

Related

Checking if $_POST variable is set using mysql variable

I have a php file that is receiving some checkbox values from a form. Both the checkbox name and value are set up to match an Item_Name field in a mysql table. My current attempt is below:
while($row = $items->fetch_assoc()){
if( isset($_POST[$row['Item_Name']])) {
\\ Code to perform if true, mostly echoes
}
}
//Checkbox setup:
echo "<input type='checkbox' name=" . $row['Item_Name'] . "value=" . $row['Item_Name'] . ">"
$items is the data returned by my query of the mysql table. Currently none of the echoes inside the if are triggering so I think something is wrong with my if statement, but I'm to new to php to know what is wrong exactly.
Your problem is in your checkbox setup; you are missing quotes around the name and value attributes. Try this instead:
echo "<input type='checkbox' name=\"" . $row['Item_Name'] . "\" value=\"" . $row['Item_Name'] . "\">";

Accessing a variable from another file in PHP, SQL

<?php
$paseoLocationTo=$_POST['locationTo'];
$paseoLocationFrom=$_POST['locationFrom'];
$PTime=$_POST['time'];
echo"The value of Location to is $paseoLocationTo </br>";
echo"The value of Location from is $paseoLocationFrom </br>";
echo"The value of time is $PTime </br>";
mysql_connect('localhost', 'root', '')
or die(mysql_error());
mysql_select_db('shuttle_service_system')
or die(mysql_error());
$TripID =mysql_query("
SELECT DISTINCT Trip_ID as 'TripID'
FROM trip
WHERE Timeslot LIKE '$PTime' AND Location_From Like '$paseoLocationFrom' AND Location_To LIKE '$paseoLocationTo'
");
echo "<form action='LastPage.php' method='post'>";
while($check = mysql_fetch_array($TripID))
**echo "<name='TripID' id='TripID'>" . $check['TripID'] . " ";**
echo "<p class='sure'> Are you sure with your reservation? </p>";
echo"<input type='submit' value='Submit' class='Log'>";
echo"</form";
?>
From another php file, this the LastPage.php
<?php
**$TripID=$_POST['TripID'];
echo"The value of trip ID is $TripID </br>";**
?>
Hi guys I was wondering why I can't access the "TripID" variable in the other php file? I was accessing it before but now there seems to be a problem, am I doing it right? I'm sorry a php and SQL newbie.
You need to add
<input type="text" name="TripID" value="'.$check['TripID'].'" ... />
in your form in order to retrieve values with $_POST['TripID'].
There is no such thing as
**echo "<name='TripID' id='TripID'>" . $check['TripID'] . " ";**
which was found in your code.
**echo "<name='TripID' id='TripID'>" . $check['TripID'] . " ";**
Looks like that should be:
echo "<input type='text' name='TripID' id='TripID' value='" . $check['TripID'] . "' />";
If you don't want it to be editable, display it then add a hidden field:
echo $check['TripID'];
echo "<input type='hidden' name='TripID' id='TripID' value='" . $check['TripID'] . "' />";
Basically, you're not putting your trip id into an actual form tag, so it's not getting posted over to your LastPage.php.
Edit: fixed the first input to wrap the tripID in the value attribute.
Replace following lines
**echo "<name='TripID' id='TripID'>" . $check['TripID'] . " ";**
with
echo "<input type="hidden" name="TripID" value="'.$check['TripID'].'" />";
So it will not be visible to user on current page but when you will post the Form, it will be available in $_POST['TripID'] variable.
One more thing your tag is not properly closed.
Use MySQLi and prepared statements to prevent SQL injection.
PS: accept the answer if its work for you.
Your form tag is not closed properly. It is now as echo </form";
It should be echo"</form>";
Also you didnt added name in input tag.
It should be
echo"<input type='submit' value="$check['TripID']" name="TripID" class='Log'>";
There is no name tag <name> but you used how?

How to store the names of checkboxes of a form to a php arrray

First off, I want to store the names of these checkboxes which are submitted, and not their values.
This is my code:
<?php
$con=mysqli_connect("localhost","root","","notifier");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM student");
echo "Enter the attendance. Please untick for 'ABSENT' students and submit";
echo "<br>";
echo "<form action=\"d.php\" method=\"post\">";
while($row = mysqli_fetch_array($result))
{
echo "<br>" .$row['classrollno'] . "&nbsp &nbsp<input type=\"checkbox\" name=\"" . $row['studentid'] . "\" value=\"P\" checked>";
}
echo "<input type=\"submit\" name=\"submit\" value=\"submit\">";
echo "</form>";
?>
This code simply fetches a column of student rollnumberss from student table, prints them, and as well as prints a checkbox infront of them which is checked by default.
Names of checkboxes will be the student id (varchar, another column).
Now since All Checked checkboxes, that is the checboxes which will be submitted to next page will have same default value "P", I m not concerned about their values.
How do I store the names of these checkboxes in an array, and later on use it to perform updation in table for all these student id's?
Use the following code:
while($row = mysqli_fetch_array($result))
{
echo '<br>' .$row['classrollno'] . ' <input type="checkbox" name="studentId[]" value="' . $row['studentid'] . '" checked />';
}
Then, when you process the form, the $_POST['studentId'] variable will contain an array with all the id's.
Since the value that will probably be inserted in the db is 'P' for every student, you wouldn't need to include it in your form, but just hardcode it in your query.
Keep adding the names to an array. Its straight forward.
Declare $allStudentIds = array(); outside while loop. Then, to store in that array,
$allStudentIds[] = $row['studentid'];
Since you wanted to use these values later, you can directly store them inside a session variable:
$_SESSION['allStudentIds'][] = $row['studentid'];
In above case, $_SESSION['allStudentIds'] will be an array of all student ids selected.
Note: You need to start session using session_start() as the first line in the script after opening <?php tag.
Simply, in the fetching while loop, define an array and set each checkbox value to one of its elements then assign it as a session variable:
while($row = mysqli_fetch_array($result))
{
echo "<br>" .$row['classrollno'] . "&nbsp &nbsp<input type=\"checkbox\" name=\"" . $row['studentid'] . "\" value=\"P\" checked>";
$names[] = $row['studentid'];
}
Then,
$_SESSION['names'] = $names;
Your confusion seems to stem from the fact that you are mixing the View (the name of the checkbox in HTML) and the Model/Data (which the student_id you are getting from your DB query ie. the $row = mysqli_fetch_array($result) in the while loop).
All you need to do is create an empty array (eg. $studentid_arr) before the loop and after the echo statement which is just contributing to the view (the HTML) you do some work with your data. What you want to do currently is to store the student_ids (and not the name of the checkbox) in your $studentid_arr.
That can be done with a simple array_push ($studentid_arr,$row['studentid']);
So your while loop would look like
while($row = mysqli_fetch_array($result))
{
echo "<br>" .$row['classrollno'] . "&nbsp &nbsp<input type=\"checkbox\" name=\"" . $row['studentid'] . "\" value=\"P\" checked>";
array_push ($studentid_arr,$row['studentid']);
}
Now you can just POST this PHP array to your next script which is expecting these values. (which is what I assume you mean by submitting to the next page)

Creating a list of checkboxes with values from a php array as its label

I want to create a list of checkboxes with values from a php array as its label. I want it to look like
Here is the list of students whose schedules are saved:
[checkbox] Robb
[checkbox] Catelyn
[checkbox] Lady Stoneheart
but my code does not work.
Here's my code:
<?php
$students = $_SESSION['students'];
echo "Here is the list of students whose schedules are saved:<br/><br/>";
echo "<form action='checkbox-form.php' method='post'>
Load student?<br/>";
foreach ($students as $stud) {
echo "<br/><input type='checkbox' name=" . $stud . " value='load' />";
}
echo "<br/><br/><input type='submit' name='formSubmit' value='Submit' />
</form>";
?>
The array is not the problem because it contains the proper values when I print it through foreach.
It might be easier to do it this way:
On the form:
foreach ($students as $stud) {
echo "<br/><input type='checkbox' name=\"students[]\" value='$stud' />$stud<br>";
}
On the handler to see what it's passing:
print_r($_POST);
If all of the "value" fields are "load", which in this case they are, nothing can happen because your PHP won't see anything different value-wise.
You should set the name value of all of these checkboxes to the same thing, and set the value to the student's name (though that's bad design- you should be setting the value to the numeric DB id that represents the student- what if you have students with the same name?)
So:
for($i = 0; i < count($students); $i++) {
$s = $students[$i];
echo "<br/><input type='checkbox' name="students[]" value='$s' />";
}
In this case name="students[]" is the students ARRAY which you can access via $_POST['students'] as an array.
It looks like you've confused the "name" attribute for the label. A few notes:
"name" is used as the name of the parameter passed to the backend
"value" is the value that will be assigned to that parameter if the checkbox is checked
So the line in your foreach should look more like:
echo '<br /><input type="checkbox" name="students[]" value="'.$stud.'" />'.$stud;
If Robb and Catelyn are checked you will get the below in the $_POST['students'] variable server side:
Array
(
[0] => Robb
[1] => Catelyn
)
foreach($students as $student){
echo "<br/><input type='checkbox' name=" . $student . " value=" . $student . " />";
echo "<label for name=" . $student . ">" . $student . "</label>";
}

Save checked value Checkbox array POST

I have a list of checkboxes and save the checked values in an array. However, when someone clicks 'submit' and they get an error, all their checked boxes are forgotten. Usually I would let the script remember the checked boxes with a code like
IF checkbox value = OK { echo checked="checked"}
However, now I save it in an array and I have no idea how to do this?
<?php
$sql = "SELECT merknaam FROM merken";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo " <input type=\"checkbox\" name=\"merken[]\" value='" . $row['merknaam'] . "'> " . $row['merknaam'] . " <Br /> ";
}
?>
This is the code I use for the checkboxes. Next I display the array with this code:
$merkenstring = implode(",", $_POST['merken']);
echo $merkenstring;
Result: AC Ryan,Adidas,Agu,Cargo
I hope someone could give me a code example!
Assuming you are posting this to the same page, and $_POST['merken'] is still available after an error, use in_array() to test each checkbox's value against the current set in $_POST:
while ($row = mysql_fetch_array($result)) {
// If the current value is in the $_POST['merken'] array
// and the array has been initialized...
if (isset($_POST['merken']) && is_array($_POST['merken']) && in_array($row['merknaam'], $_POST['merken'])) {
// Set the $checked string
$checked = "checked='checked'";
}
// Otherwise $checked is an empty string
else $checked = "";
// And incorporate it into your <input> tag
echo " <input $checked type=\"checkbox\" name=\"merken[]\" value='" . $row['merknaam'] . "'> " . $row['merknaam'] . " <Br /> ";
//----------------------^^^^^^^^^^
}
If this was posted to a different script, you would (as with any post value returned to a previous script) need to store the array in $_SESSION instead and compare against $_SESSION['merken'] in your in_array() call.
Assuming $row['merknaam'] is the checkbox value, and $_POST['merken'] holds an array of checked checkbox values, then you simply need to check if the value is in the array:
if (in_array($row['merknaam'], $_POST['merken'])) {
// this checkbox should be checked
}

Categories