Inserting values into database by looping - php

I'm creating a script where I'm getting information from a database and automatically importing it into a table using PHP and creating a form. In the form I'm naming the fields by whatever the data in they contain in the database. I'm having trouble in the values part of the query inserting the form values into the database because I'm not sure how to loop through and add all the input fields. How would I do this?
while ($aRow = mysql_fetch_assoc($aResult)) {
if ($aRow['correct'] == 1) {
$tableString .= "<input name=". $qRow['questionID'] ."
type='radio'
>" .
$aRow['answerValue'] . "<br />";
} else {
$tableString .= "<input name=". $qRow['questionID'] ."
type='radio'
>" .
$aRow['answerValue'] . "<br />";
}
$answer= [$aRow];
$question= [$qRow];
$student= [$username];
// Insert data into mysql
//$sql="INSERT INTO $userexam(answerID, questionID, userID)VALUES('$answer', '$question', '$student')";
//$result=mysql_query($sql);
$query = " INSERT INTO userexam (
answerID,
questionID,
userID)
VALUES ( '" . $_POST['/* answerID */'] . "', '" .
$_POST['/* questionID */'] . "', '" .
$_POST['/* userrole */'] . "')";
}

The Problem with radio buttons is: They are not send via $_POST if they are not checked. You need to "know" what radiobuttons exist and those who are not send with $_POST are not checked.
As for the looping:
You can give your radio buttons a "main" name in addition to your IDs:
<form method="POST">
<input type="radio" name="foo[23]">
<input type="radio" name="foo[45]">
<input type="submit" value="foo">
</form>
Take a look at the $_POST variable and you see that both radio buttons are within an array. You can use that array to iterate through all checked radio buttons.
And please start using PDO instead of mysql_ :)

Related

Session Value always equals last instance

I have a page that is running an SQL query. I am displaying information for each row that the query results in. I am now trying to implement a way to update the information for the things being displayed.
My understanding is that in order to get information from one page to another you need to use sessions.
My code is displaying the information from the MySQL tables, then underneath it is giving the user the choice to edit the information in a form then send it to another file
One way of easily doing this is to use <input type="hidden"> so that you can include $row['Toy_ID'] in your form.
Something like this:
$row = $result->fetch_assoc();
while ($row){
echo "Toy Name: " . $row['Toy_Name'] . "<br>" .
"Store Name: . $row['Store_Name'] . "<br>" .
"Cost: " . $row['Cost'] . "";
echo "<form action='update.php' method='post'>" .
"<input type='hidden' name='toyid' value='".$row['Toy_ID']."'>" . // here's the hidden input, which you can call by using `$_POST['toyid']`
"<label>Toy Name: </label><input name='tname'; value='" . $row['Toy_Name'] . "'><br>" .
"<label>Store Name: </label><input name='storename'; value='" . $row['Store_Name'] . "'><br>" .
"<label>Cost: </label><input name='cost'; value='" . $row['Cost'] . "'><br>" .
"<input type='submit' value='Submit'>" .
"</form></div><br><br>";
$row = $result->fetch_assoc();
}
Then change your query to make use of $_POST['toyid'] instead of $_SESSION['toyid']

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.

Save several checked values to MySQL database

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.

POST variable to another class

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

Categories