First of all, I am a newbie when it comes to coding, so please be kind and patient :)
What I am trying to do is to select two rows ('ID', 'name') from a MySQL table (categories), populate a drop down list with one row ('name'), and on submission of a form, pass the other ('ID') to another table.
Now, I can populate the drop down list, no problem. I have populated this with both 'ID' and 'name' to test that both of the variables I am using to hold this information, contain the correct data. But I cannot seem to $_POST the information.
I guess I am either looking at the wrong part of the array, or I am simply using the wrong code.
This is the code to create a new product, under a category from the database.
<?php
include 'db_config.php';
?>
<form enctype="multipart/form-data" action="insert.php" method="post">
<h3>Add New Product</h3>
Category:
<!-- START OF categories (table) names (row) SQL QUERY -->
<? $sql = "SELECT ID, name FROM categories";
$result = $mysqli->query($sql);
echo "<select name='category_name'>";
while ($row = $result->fetch_assoc()) {
$cat_ID=$row['ID'];
$cat_name=$row['name'];
extract($row);
echo "<option value='" . $cat_ID . $cat_name . "'>" . $cat_ID . " " . $cat_name ."</option>";
}
echo "</select>";
?>
<!--END OF SQL QUERY -->
<br>
Code: <input type="text" name="code"><br>
Name: <input type="text" name="prod_name"><br>
Description: <input type="textarea" name="description"><br>
Image: <input type="file" name="image"><br>
<input type="Submit">
</form>
For now, I am just echoing this out in the insert.php script, to test the code above. This is a snippet of the insert.php script.
echo "ID: " . $_POST['$row["ID"]'] . "<br>";
echo "Category: " . $_POST['$row["name"]'] . "<br>";
echo "Code: ". $_POST['code'] . "<br>";
echo "Name: " . $_POST['prod_name'] . "<br>";
echo "Description: ". $_POST['description'] . "<br>";
echo "Image: " . $_POST['image'] . "<br>";
Don't worry about the last line above. I know this needs to be $_FILES, and I have all this covered. I have stopped writing the data to the table until I get my issue fixed. In the full script, image are being upload to "/images" and the location stored in the table. This all works fine.
The problem is with the first two lines, as they are blank when returned. I thought I was storing the information correctly, as I am calling the same variables to populate the drop down list, but I cannot seem to $_POST it.
Does that makes sense?
Thanks to all who help me. Once day I will be as good as you....I hope.
TIA
Smurf.
this bellow:
echo "ID: " . $_POST['$row["ID"]'] . "<br>";
echo "Category: " . $_POST['$row["name"]'] . "<br>";
is wrong, select element has its name category_name, so, instead of this, you should
do:
echo "Category: " . $_POST['category_name'] . "<br>";
echo "ID: " . $_POST['$row["ID"]'] . "<br>";
echo "Category: " . $_POST['$row["name"]'] . "<br>";
There aren't any form elements with those names in your form ($row["ID"] and $row["name"]). Those would be really strange names for a form element anyway. The form element you're creating is:
<select name='category_name'>
So the selected value would be posted as:
$_POST['category_name']
The option elements for that select appear to have values which are a combination of ID and Name:
"<option value='" . $cat_ID . $cat_name . "'>"
Thus, if the user selects an option with a value of 1SomeName then $_POST['category_name'] will evaluate to '1SomeName'.
It's certainly unconventional to use the combination of ID and Name for the option values, but it should work. The problem is presents is that you now have a composite string which needs to be parsed in order to be useful. Generally what one would do is just use the ID as the value and the Name as the display. All you should need to use it throughout the code is the ID.
The $_POST variable you want, is inside category_name
Cuz your select is...
<select name='category_name'>
So you need to get it by...
$_POST['category_name'];
Which will return whatever you've assigned to the select options...ie
2 Name
2 being the ID, and Name being the name
But if you then want to use that ID to retrieve from DB or anything, you're gonna have to explode that apart...like so....to get each piece.
$array = explode(" ", $_POST['category_name']);
That will leave you with...
$array[0] = ID
$array[1] = Name
But I would avoid all that part, by just assigning the ID to the value only...like so..
echo "<option value = '".$cat_ID."'> ".$cat_name." </option>";
That way you just pass the ID and have access to it on the other side.
Related
I am very new to php and am teaching it to myself, so please keep that in mind.
I am working on a project that presents users with a list of items, from a database, with checkboxes, and allows the user to check them. I want to save the values of the checked fields. This is the line of code that prints all of the options. It prints a course code and course title, with a checkbox.
echo "<input type='checkbox' name ='boxes'>" . $row['course'] . ' ' . $row['title'] . "<br>";
However, when I try to print the values selected, it doesn't work. I get an error that says invalid argument supplied foreach()
if(isset($_POST['submit_courses'])){
if(!empty($_POST['boxes'])){
foreach($_POST['boxes'] as $selected ){
echo $selected."</br>";
}
}
}
Please help!
Try:
echo "<input type='checkbox' name ='boxes[]'>" . $row['course'] . ' ' . $row['title'] . "<br>";
EDIT:
To better answer the question:
You need to add the value="" attribute to your input fields. So if you have an ID in your $row array then it would be like this...
echo "<input type='checkbox' name ='boxes[]' value=' . $row['id'] . '>" . $row['course'] . ' ' . $row['title'] . "<br>";
Now you should be able to get the selected id's from the populated values inside of the $_POST['boxes'] array. Just loop through them and do something with them like echo them out.
foreach ($_POST['boxes'] as $box_value) {
echo $box_value . "<br>";
}
Only the boxes that are selected will be in the array and you will have the identifier for whatever courses were selected.
I am trying to create a form using data from MySQL and my current output is not looking as expected so I just need some simple changes to my current form
My current output in the browser: http://gyazo.com/f4668ca59586ec0d4d1500ea6f7b6257
What I am looking to do is
fix the problem with the first column called 'Long Jump A' so its
next to a drop down menu, and you can see the bottom one is next to
nothing.
Secondly, How can I swap the order of the drop down and the
event? So the event is on the left then the drop down is on the
right?
Moving the form down from the top so there is a space
The code:
<?php
require_once 'db/connect.php';
//Query to display all events
if ($event_result = $con->query("SELECT Event.Name FROM event")) {
echo "<form method =\"POST\">";
while ($row = $event_result->fetch_assoc()) {
echo $row['Name'] . ' <br> ';
if ($student_result = $con->query("SELECT Student.Form, Teacher.Form, Student.Forename, Student.Surname, Student_ID " .
"FROM Student, Teacher " .
"WHERE Student.Form = Teacher.Form AND Teacher.Form = 'C'")) {
if ($student_result->num_rows) {
echo "<select name ='Student_ID'>";
while ($row1 = $student_result->fetch_assoc()) {
echo "<option value ='" . $row1['Student_ID'] . "'>" . $row1['Forename'] . ' ' . $row1['Surname'] . "</option>";
}
echo "</select>";
}
}
}
echo "</form>";
}
?>
You have an opening <br /> as you echo out the name of the row. This means echo the title, then break before you display the <select> group. You should move that <br /> down right before the closing while loop.
Or just remove the top <Br /> and add it back after the ending so it looks like this:
echo "</select> <br />";
edit: this will fix the last two of your questions, as now each select group will properly line up with the title of the row. If you want more space at the top of the form you have a bunch of options: add more breaks, add a margin or padding, or position the element as relative and use css top property or CSS transforms to move it.
I want to send some information from one php file to another.
I've read about the use of $_SESSION and $_POST, but they're giving me some problems.
My code looks something like this:
<form action="booking.php" method="post">
<select name="bookingflight">
<?php
$query = "SELECT Flight, Name
FROM Airport";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo "<option value=\"". $row['Flight'] . ',' . $row['name'] . "\">" . $row['Flight'] . ' ' . $row['name'] . "</option>";
}
?>
</select></p>
<input type="submit" value="book flight"/>
</form>
This gives me a dropbox list of all the flights, along with the name of the flights.
If I select an element it's stored in $_POST["bookingflight"] which I can access in booking.php, which is fine.
However, it's given as a string, while I should be able to handle flight and name separately.
Ideally, I'd have two variables, one for flight and one for name, which I can access in booking.php.
How should I do this? With $_SESSION I don't even know how to assign a selected item from the list to a variable.
Alternate Solution: If Flight is unique data
while($row = mysql_fetch_array($result)) {
$flight=$row['Flight'];
$name=$row['Name'];
echo "<option value='$flight'>$flight $name</option>";
}
PHP : booking.php
<?php
$flight=$_POST['bookingflight'];
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT Flight,Name FROM Airport WHERE Flight='$flight'");
$row = mysqli_fetch_array($result);
$name= $row['Name'] ; // Here you get Name of selected Flight
mysqli_close($con);
?>
Or
If your Airport table contains any unique data/id , you can pass that data as option value too
You started this the wrong way...
Give your Airport table a unique primary key (named id, INT, auto-increment) and pass that as a value in generated options:
echo "<option value=\"". $row['id'] ."\">" . $row['Flight'] . ' ' . $row['name'] . "</option>";
Now when you POST your form you get that ID value in booking.php.
Because every flight has a unique ID you can just issue another query and you get your result as an array there:
$query = "SELECT Flight, Name FROM Airport WHERE id = $id";
Put this in your booking.php...
if($_POST)
{
$values = $_POST['bookingflight'];
$val= explode(',',$values);
$_SESSION['flightnumber'] = $val[0];
$_SESSION['flightname'] = $val[1];
}
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'] . "   <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'] . "   <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'] . "   <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)
I have a PHP form, which in the end is going to write all the filled in data to a MySQL database. That's all fairly doable, but here is something tricky that I don't know how to handle:
I have a DIV which requests all the rows of one table. Every row represents a category and the user can choose several categories to add to their post. This is the code I use to retrieve the rows + checkbox in front of them:
<?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 /> ";
}
?>
The user can choose multiple categories, and I would like to save them all and write them to my database. All the categories should be written to 'one' column called 'categories', but the seperate categories should still be distinguishable.
Might be a tricky one? Hope someone can help!
Change the code for the checkboxes to:
echo " <input type=\"checkbox\" name=\"merken[]\" value='" . $row['merknaam'] . "'> " . $row['merknaam'] . " <br /> ";
Adding the [] after the name will allow PHP to treat the checkboxes as an array, which you can serialize and store in your database.