I need your help with my form. I'm trying to build a dynamic forms, whereby a specific integer entered in a previous form sp1.php is used to display the number of input boxes.
The variables from the first forms are $state and $number. Then on the handling page sp2.php, the value of $number is put into a for loop to display the input boxes.
What I'm trying to do now is that the values entered into the tinput boxes are inserted into a mysql table.
The error I'm getting are
1) Undefined Index : DISTRICT
2) Invalid Argument supplied for foreach()
Please how can I make this work. Thank you.
My Code is below.. I'll be more than happy to show other parts of the code, if required.
Thank you.
<?php
$state=htmlspecialchars(($_POST['state'])) ;
$number = intval(($_POST['number']));
for ($i = 0; $i < $number ; $i++ ) {
echo "
<form action='sd2.php' method='post'>
<label for='name'>Districts</label>
<input type='text' name='district[]'>
<br/><br/>
</form>";
}
?>
<?php
foreach($_POST['district'] as $senatorial) {
$query = "INSERT INTO state ( `state_id`, `state`, `senatorial`)
VALUES (NULL, '".$state."', '".$senatorial."') ";
mysql_query($query) or die (mysql_error());
}
?>
This must work:
$count = count($_POST['district']);
for ($i=0; $i<$count; $i++){
$district = $_POST['district'][$i];
//do this
//do that
}
Related
I stored the data in a supposed to be an array but what happens is that only the last checked checkbox is the only one that is registered in the idSkills. This is the part of the code wherein the skills are displayed through a query in the database
<?php
$i=0;
while ($row = mysqli_fetch_assoc($result)) {
$id=$row['id'];
$skillName=$row['skillName'];
?>
<input type="checkbox" name="skills[]" value="<?php echo $id; ?>"><?php echo $skillName; ?><br>
<?php
$i++;
}
?>
Here is the part where the loop unveil all of the selected checkbox
//QUERY TO INSERT
$conn = new mysqli($config['servername'], $config['username'], $config['password'], $config['database']);
$idSkills = $_GET['skills'];
if(empty($idSkills))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($idSkills);
echo("You selected $N door(s): ");
echo("$idSkills[1] ");
for($i=0; $i < $N; $i++) {
echo "Skill ID: "
$sql = "INSERT INTO volunteer_skills (idskill,idVolunteer)
VALUES ('$idSkills[$i]','$idVolunteer')";
$result = $conn->query($sql);
}
}
$conn->close();
It would be best to use a prepared statement instead of substituting a variable into the SQL. But if you're going to do it this way, you need to use the correct syntax:
$sql = "INSERT INTO volunteer_skills (idskill,idVolunteer)
VALUES ('{$idSkills[$i]}','$idVolunteer')";
You need to put {} around an array reference in order to get the variable inside the brackets to be evaluated. See the section on Complex (curly) Syntax in the PHP Strings documentation.
I am currently running into an issue, where I have this form consisting of checkboxes. I get the values of user preferences for the checkboxes from a database. Everything works great, and does what is supposed to do, however after I change and check some boxes and then hit the submit button, it will still show the old values to the form again. If I click again in the page again it will show the new values.
The code is shown below with comments.
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk
FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name
FROM categories
INNER JOIN portals on categories.portal_id=portals.portal_id
ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
<?php
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
if(isset($_POST['submit'])){
if(!empty($_POST['categories'])){
$cats= $_POST['categories'];
$result = mysqli_query($conn,$qry_del_usrcats); //delete all
for ($x = 0; $x < count($cats); $x++) {
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`)
VALUES ('".$_SESSION['user_id']."', '".$cats[$x]."');";
$result = mysqli_query($conn,$qry_add_usrcats);
}
echo "success";
}
elseif(empty($_POST['categories'])){ //if nothing is selected delete all
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
I am not sure what is causing to do that. Something is causing not to update the form after the submission. However, as i said everything works great meaning after i submit the values are stored and saved in the DB, but not shown/updated on the form. Let me know if you need any clarifications.
Thank you
Your procedural logic is backwards and you're doing a bunch of INSERT queries you don't need. As #sean said, change the order.
<?php
if(isset($_POST['submit'])){
if(isset($_POST['categories'])){
$cats= $_POST['categories'];
// don't do an INSERT for each category, build the values and do only one INSERT query with multiple values
$values = '';
for($x = 0; $x < count($cats); $x++) {
// add each value...
$values .= "('".$_SESSION['user_id']."', '".$cats[$x]."'),";
}
// trim the trailing apostrophe and add the values to the query
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`) VALUES ". rtrim($values,',');
$result = mysqli_query($conn,$qry_add_usrcats);
echo "success";
}
elseif(!isset($_POST['categories'])){ //if nothing is selected delete all
// you may want to put this query first, so if something is checked you delete all, so the db is clean and ready for the new data.
// and if nothing is checked, you're still deleting....
$qry_del_usrcats="DELETE FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name FROM categories INNER JOIN portals on categories.portal_id=portals.portal_id ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
Typically this occurs due to the order of your queries within the script.
If you want to show your updated results after submission, you should make your update or insert queries to be conditional, and have the script call itself. The order of your scripts is fine, but you just need to do the following:
Take this query:
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
and put it inside the if statement so it looks like this:
if (isset($_POST['submit'] {
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
$result = mysqli_query($conn,$qry_del_usrcats);
[along with the other updates you have]
}
Also, you will need to move this entire conditional above the form itself; typically any updates, inserts, or deletes should appear year the top of the form, and then call the selects afterward (outside of the conditional)
I had successfully pulled out students details that is name , class , section .. as it is a attendance management system. But i facing problem in saving all the values ie Name , Class, Section , Status (P/A) in my database. Bellow the attendance submit code ... please guide me.
// showing values
<input type="hidden" id="" name="locationID[]"/><?=$i;?></div></input>
<input type="hidden" id="" name="name[<?=$name;?>]"/><?=$name;?></input>
<?php
include('config.php');
#session_start();
$sessionName = $_SESSION['NAME'];
$date = date('d-m-y');
$loc= $_POST['locationID'];
$name = $_REQUEST['name'];
$status = $_POST['status'];
$class = $_POST['class'];
$section = $_POST['section'];
for( $i = 0; $i < count($loc); $i++ )
{
$sql = "INSERT INTO tbl_attendence (fld_studentname,fld_status,fld_class,fld_section,fld_date,fld_takenby)
VALUES ('$name','$status','$class','$section','$date','$sessionName')";
//echo $sql; exit;
mysql_query($sql);
}
?>
After running this code i am getting Array, in all columns ... please guide me...
Assuming that you are return arrays of values in POST, a possible solution could be
$sql = "INSERT INTO tbl_attendence (fld_studentname,fld_status,fld_class,fld_section,fld_date,fld_takenby)
VALUES ('{$name[$i]}','{$status[$i]}','{$class[$i]}','{$section[$i]}','{$date[$i]}','{$sessionName[$i]}')";
Suggestions:
1. Avoid your code from SQL Injection
2. Use XDebug or use print_r() whenever you see this kind of problem of Array instead of values to debug properly what is the problem.
I need to create n number of users with n username and password.
If I give the input 5, abc. 5 Users should be created with the username and password such as abc1, abc2, abc3, abc4 and abc5.
How can I do this in for loop by giving the mysql insert query?
Here are my forms
create.php
Create User :
<br><br>
<form action="add_res.php" method="post">
Count : <input type = "text" name="count"><br>
Name : <input type = "text" name="val">
<input type = "submit">
</form>
and the add_res.php
<?php
$count=$_POST['count'];
$val=$_POST['val'];
include ('config.php');
echo "<b>".$count." Users Created"."</b>"."<br>";
echo "<u>"."The Users' List is given below"."</u>";
for ($i=1; $i <=$count; $i++)
{
$select=mysql_query("insert into student (username, password) VALUES
('$con', '$con')");
}
?>
I don't have idea about implementing the proper for loop and the proper insert query. How can i achieve it?
Use the for loop and the insert query by the below format,
<?php
$count=$_POST['count'];
$val=$_POST['val'];
include ('config.php');
echo "<b>".$count." Users Created"."</b>"."<br>";
echo "<u>"."The Users' List is given below"."</u>";
for ($i=1; $i <=$count; $i++)
{
echo "<br>";
echo $val.$i;
$con=$val.$i;
$select=mysql_query("insert into student (username, password) VALUES
('$con', '$con')");
}
?>
Several of the other answers here have indicated how to properly set up the variables to send with your MySQL query, but every single one of them, as well as your original code, contains a classic SQL injection vulnerability! Especially since you are getting your input directly from $_POST, this will allow an attacker complete control over your database -- reading data, resetting passwords, anything.
One way to solve the problem is to escape the input to mysql_query. A version which both solves your original question and the security issue might look like this:
<?php
include ('config.php');
$count = $_POST['count'];
$val = $_POST['val'];
echo "<b>".$count." Users Created</b><br>";
echo "<u>The Users' List is given below</u>";
echo "<ul>";
for ($i = 1; $i <= $count; $i++)
{
echo "<li>";
$name = $val . $i;
$name = mysql_real_escape_string($name);
mysql_query("insert into student (username, password) VALUES ('$name', '$name')");
}
echo "</ul>";
However, this still uses mysql_query, and while mysql_real_escape_string solves the aforementioned security problem, is not the preferred way to write MySQL queries. I believe PDO is the recommended way to do so now.
Just create a variable with the $val variable then put the $i variable at the end. Then insert that.
for ($i=1; $i <=$count; $i++)
{
$con = $val.$i;
$select=mysql_query("insert into student (username, password) VALUES ('$con', '$con')");
}
Replace this instead of your loop
for ($i=1; $i <=$count; $i++)
{
echo "<br>";
echo $val.$i;
$con=$val.$i;
$select=mysql_query("insert into student (username, password) VALUES ('".$con."', '".$con."')");
}
This is a continuation of the discussion at
PHP Multiple Dropdown Box Form Submit To MySQL
which ended with the words: "Once you have the variables, it is trivial to create new rows." No doubt that's generally true, but apparently not for this learner... :-D
Given the following form:
<form action="form.php" method="POST">
<select name="colors[]" multiple="yes" size="2">
<option>Red</option>
<option>Blue</option>
</select>
<input type="submit" value="Go!">
</form>
how do I create new rows? The following script
foreach($_POST['colors[]'] as $color)
{
$id = mysqli_real_escape_string($link, $color);
$sql = "INSERT INTO colors SET id = '$id'";
}
raises the error
Warning: Invalid argument supplied for foreach() in form.php on line ...
whereas the following
$colors = $_POST['colors[]'];
for ($i = 0; $i < count($colors); $i++)
{
$color = $colors[$i];
$sql = "INSERT INTO colors SET id = '$color'";
}
raises no errors but does no row creation.
What triviality am I missing here?
Use:
foreach($_POST['colors'] as $color)
No need to specify [] here, php knows that it is an array.
Inside of your foreach loop I did not see that you are executing the query. You need to execute mysql_query with your INSERT statement.
foreach($_POST['colors'] as $color) {
$id = mysqli_real_escape_string($link, $color);
$sql = "INSERT INTO colors SET id = '$id'";
if (!mysql_query($sql)) { // if the query encountered a problem.
die('Invalid query: ' . mysql_error());
}
}