Save several checked values to MySQL database - php

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.

Related

Changing the output of my HTML form

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.

Can't update a selected row by user

I've written this code for a user to edit one row and update it in MySQL, but it always posts the last row no matter which row you have selected (there are 3 rows).
What's the problem?
<?php include("includes/db_connection.php"); ?>
<?php
global $connection;
$sid="s5";
/**select all salesman from store 5**/
$sql ="SELECT * FROM employees WHERE e_type='Salesperson' AND store_assigned='".$sid."';";
/**get the result and put into table, which can be edited by user**/
$result = mysql_query($sql);
echo "<form method='post' action='update_salesman.php'>";
echo "<table border='1'><tr><th>Employee ID</th><th>Name</th><th>Address</th><th>Email</th><th>Job Title</th><th>Store</th><th>Salary</th></tr>";
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td><input type='text' name='eid' value='".$row['eid']."' readonly /></td>";
echo "<td><input type='text' name='e_name' value='".$row['e_name']."' /></td>";
echo "<td><input type='text' name='e_addr' value='".$row['e_addr']."' /></td>";
echo "<td><input type='text' name='e_email' value='".$row['e_email']."' /></td>";
echo "<td><input type='text' name='e_type' value='".$row['e_type']."' /></td>";
echo "<td><input type='text' name='store_assigned' value='".$row['store_assigned']."'/></td>";
echo "<td><input type='text' name='e_salary' value='".$row['e_salary']."' /></td>";
echo "<td><input type ='submit' value='update' /></td></tr>";
}
echo "</table>";
echo "</form>";
print($sql);
?>
Get the posted data, and update it in MySQL database:
<?php include("includes/db_connection.php"); ?>
<?php
$eid = $_POST['eid'];
$ename = $_POST['e_name'];
$eaddr = $_POST['e_addr'];
$eemail = $_POST['e_email'];
$etype = $_POST['e_type'];
$estore = $_POST['store_assigned'];
$esalary = $_POST['e_salary'];
$sql = "UPDATE employees SET e_name='" . $ename . "', e_addr='" . $eaddr . "', e_email='" . $eemail . "', e_type='" . $etype . "', store_assigned='" . $estore . "', e_salary='" . $esalary . "' WHERE eid='" . $eid . "' ;";
$result = mysql_query($sql);
print("</br>" . $sql);
?>
The result is always this:
UPDATE employees SET e_name='Norah ', e_addr='111 Melwood,PA', e_email='anorahm#gmiil.com', e_type='Salesperson', store_assigned='s5', e_salary='4000.00' WHERE eid='e334' ;
Your problem is twofold. First, when generating the HTML code, you use a while loop to echo the fields. Note that the names of these fields are the same every time the loop runs. (You can see this in the generated HTML (source code). Note that on submitting, one one of the multiple same-named fields will be posted.
Second, in the PHP form handler code, you read the post data and then do one update query, while you may want to update more than one field.
The easiest way to solve this is to make sure that the field names in the HTML form are different for each of the rows, and to use a loop structure when updating the sql table such that there's an update for each row.
even though it may appear fine on the html side, it's clear what's happening on the server side when it gets the form
When the server gets the form it will only see the last record because each record will overwrite the values that come before it resulting in only getting the data from the last record
What you can do is give each set of values its own form (Wouldn't suggest). But with this method, you can leave your code almost as is, just move the form tags into the while loop. OR write the input names as e_name[], etc.
This way it will be passed as an array to the server and you can loop through to get all your values
On the server end, to get the array you would do something like
$e_names = $_POST['e_name']; //Value will be an array

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)

$_POST Array issue PHP MySQL

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.

Passing a <td> value to a php script

Sorry if this is a noob question, but I'm still getting up to speed with PHP and can't find an answer to this one.
I have a php script that queries a mySQL table and then builds an HTML table from the results. This all works just fine. As part of that script, I add a <td> to each <tr> that gives the user a chance to delete each specific record from the database, one by one, if they so choose.
To make this work, I have to be able to pass over to the php script the unique identifier of that record, which exists as one of the values. Problem is, I don't know how to pass this value.
Here is my php script that builds the HTML table:
while ($row = mysql_fetch_array($result)) {
echo
"<tr class=\"datarow\">" .
"<td id=\"id_hdr\">" . $row['id'] . "</td>" .
"<td id=\"name_hdr\">" . $row['name'] . "</td>" .
"<td id=\"btn_delete\">
<form action=\"delete_item.php\">
<input type=\"image\" src=\"images/delete.png\">
</form>
</td>" .
"</tr>";
}
So, somehow I either need to explicitly pass 'id' along with "delete_item.php" and/or find a way on the php side to capture this value in a variable. If I can accomplish that I'm home free.
EDIT: Trying to implement both suggestions below, but can't quite get there. Here is how I updated my form based on how I read those suggestions:
"<td id='btn_delete'>".
"<form action='scripts/delete_item.php'>".
"<img src='images/delete.png'>".
"<input type='hidden' id='uid' value='" . $row['id'] . "'>".
"<input type='submit' value='Submit'/>".
"</form>".
"</td>" .
Then, in delete_item.php, I have this:
$id = $_POST['uid'];
$sql = "DELETE FROM myTable WHERE id=$id";
$result = mysql_query($sql);
if (!$result) {
die("<p>Error removing item: " . mysql_error() . "</p>");
}
But when I run it, I get the error:
Error removing item: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '' at line 1
And one final thing: this approach gives me a button with the word 'submit' directly under my image. I'd prefer not to have this if possible.
Thanks again!
<form action=\"delete_item.php\">
<input type=\"hidden\" value=\"$row['id']\" name=\"uid\" >
<input type=\"image\" src=\"images/delete.png\">
</form>
The unique id is placed in a hidden input. You can get this value using
$_POST['uid']
But you need to submit the form
<input type=\"submit\" name=\"submit\" value=\"delete\" ">
You could use an anchor tag with parameter for id.
ie, www.example.com/delete.php?id=20
Now you could get that id on page delete.php as $_GET['id']
Using that you could delete the data from the table and return to the required page by setting up header
If you required you could use the same logic with AJAX and with out a page reload you could permenently delete that data. I would recommend AJAX

Categories