insert multiple same input fields php - php

Good day.
<input type="text" name="title">
<input type="text" name="name[]">
<input type="text" name="name[]">
<?php
if(isset($_POST['submit']){
$title = $_POST['title'];
$name = $_POST['name'];
$add = "INSERT INTO books (title, name) VALUES ('$title','$name')";
}
?>
How can this code work? It should be inserted with same title and different names at the same time. Thank you.
Sample Form
I want the record to be updated as follows:
---------------------------------
|--bookID--|--Title--|--Author--|
|----1-----|---one---|----me----|
|----2-----|---two---|---you----|
---------------------------------

$_POST['name'] is an array with key 0,1 ...
So in your example you ve got:
//This is just an example
foreach($_POST['name'] as $name) {
}
Hope this helps.

Atul Vekariya example is correct but you need to also execute the query in the loop. That's why this example did not work for you.
if(is_array($_POST['name']) && !empty($_POST['name'])) {
foreach($_POST['name'] as $name) {
$add = "INSERT INTO books (title, name) VALUES ('$title','$name')";
//execute query here. mysqli_query($add) or PDO::query
}
}

Please check below code
if(is_array($_POST['name']) && !empty($_POST['name'])) {
foreach($_POST['name'] as $name) {
$add = "INSERT INTO books (title, name) VALUES ('$title','$name')";
//execute query here. mysqli_query($add) or PDO::query
}
}

After searching different solutions. Here is the one that works. Thank you for all the help.
<?php
include_once 'config/connect.php';
if($_SERVER["REQUEST_METHOD"] == "POST"){
$title = $_POST['title'];
$name = $_POST['name'];
$length = count($name);
$addBook = "INSERT INTO books (title,name) VALUES ";
for($i=0; $i<$length; $i++){
$addBook .= "('$title','$name[$i]'),";
}
$addBook = rtrim($addBook, ',');
if($conn->query($addBook) === TRUE) {
echo "Success";
} else {
echo "Error: ".$addBook."<br>".$conn->error;
}
}
?>
<form action="addBook.php" method="POST">
Title: <input type="text" name="title">
<br/>
Authors: <input type="text" name="name[]"> <input type="text" name="name[]">
<br/>
<input type="submit" name="submit">
</form>

Related

Inserting an array of checkbox values into a database including unchecked

In the form below, students are selected from student table in my DB. For each student selected a checkbox is checked if the student is absent and left unchecked if the student is present. The form is later on submitted for it to be inserted in the exam_status table in my DB.
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
while($row= $result->fetch_assoc())
{
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="matricule[]" value="<?php echo "$studentmatricule)"; ?>" readonly>
<label>Name</label>
<input type="text" name="name[]" value="<?php echo "{$studentname} {$studentsurname}"; ?>" readonly>
<label > Absent
<input type="checkbox" name="absent[]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
</form>
and my action page "action.php" is as follows
$matricule = $_POST['matricule'];
$absent=$_POST['absent'];
for ($i=0; $i<sizeof($matricule); $i++)
{
if($absent[$i]=='absent')
{
$status='absent';
}else{
$status='present';
}
$query = "INSERT INTO exam_status (student_matricule,status) VALUES ('". $matricule[$i] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
Now the issue is it doesn't just work as i want. the result always gives the first student absent and the rest present. I have tried all i can and have really researched too but with no success at all. Please anyone around to help me out?
Thanks in advance!
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
$index = 0;
while($row= $result->fetch_assoc())
{
$index++;
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][matriculate]" value="<?php echo $studentmatricule; ?>" readonly>
<label>Name</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][name]" value="<?php echo $studentname." ".$studentsurname; ?>" readonly>
<label > Absent
<input type="checkbox" name="studenInfo[<?php echo $index; ?>][status]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
Update your mail file like this. I have changed the form names into a single array. The reason is the checkbox values won't post to the page when the values are not checked. So its not possible to track which one was checked and which is not if you have same name.
And update your action.php like this,
<?php
$conn = mysqli_connect("localhost","username","password","db_name"); // update this values as per your configuration
$studenInfo = (!empty($_POST['studenInfo'])) ? $_POST['studenInfo'] : [];
foreach($studenInfo as $value ) {
$status = (isset($value['status'])) ? 'absent' : 'present';
$query = "INSERT INTO exam_status (student_name, student_matricule,status) VALUES ('". $value['name'] . "','". $value['matriculate'] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
?>
I have used my own table schema where i have added student_name in exam_status table for better tracking. Now you can see the values updating correctly. Also we can use bulk insert if we need to insert multiple data (Note : I haved used the bulk insert in this answer, i just followed the way you used)

How to allow NULL value on foreign key on php

Good day. I am seeking for help on what to do with the codes:
The PHP part:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$student = $_POST['student'];
$lecture = $_POST['lecture'];
$room = $_POST['room'];
$students = mysqli_query($con,"SELECT * FROM students WHERE student='$student'");
$lectures = mysqli_query($con,"SELECT * FROM lectures WHERE lecture='$lecture'");
$rooms = mysqli_query($con,"SELECT * FROM rooms WHERE room='$room'");
$student_row = mysqli_fetch_array($students);
$lecture_row = mysqli_fetch_array($lectures);
$room_row = mysqli_fetch_array($rooms);
What I want to do in this part is, if there is no entry on room input insert the value null in the room_id column in the reference table:
if($student != $student_row['student']) {
$addStudent = mysqli_query($con,"INSERT IGNORE INTO students (student) VALUES ('$student')");
$studentID = mysqli_insert_id($con);
}else{
$studentID = $student_row['student_id'];
};
if($lecture != $lecture_row['lecture']) {
$addLecture = mysqli_query($con,"INSERT IGNORE INTO lectures (lecture) VALUES ('$lecture')");
$lectureID = mysqli_insert_id($con);
}else{
$lectureID = $lecture_row['lecture_id'];
};
if($room != $room_row['room']) {
$addRoom = mysqli_query($con,"INSERT IGNORE INTO rooms (room) VALUES ('$room')");
$roomID = mysqli_insert_id($con);
}else{
$roomID = $room_row['room_id'];
};
I think this is the part that needs to be changed:
$addClass = mysqli_query($con,"INSERT INTO classes (student_id,lecture_id,room_id) VALUES ('$studentID','$lectureID','$roomID')");
if($addClass){
echo 'Success';
}else{
echo 'Error: '.mysqli_error($con);
};
};
?>
The HTML part:
<html>
<title>Add Class</title>
<body>
<form name="Add Class" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Student: <input type="text" name="student" />
</br></br>
Lecture: <input type="text" name="lecture" />
</br></br>
Room: <input type="text" name="room" />
</br></br>
<input type="submit" value="Add Class">
</form>
</body>
</html>
Thank you.
You can simply insert NULL as value. Like this:
if(empty($room))
$room = "NULL";
right before the mysqli insert. Make sure you actually pass the string null not empty or 0.
Oh and you obviously need to make sure the column is not marked as NOT NULL

Storing database value into variable

My table category has these columns:
idcategory
categorySubject
users_idusers
I have a form with a simple radio buttons and a textbox.
I have a select all statement for category and need to get the idcategory stored into a variable ($getCatId) so I can use this statement:
$sql="INSERT INTO topic(subject, topicDate, users_idusers, category_idcategory, category_users_idusers) VALUES('($_POST[topic])', '$date', '$_SESSION[userid]', '$getCatId', '$_SESSION[userid]');";
What is the best way to get and store categoryid?
if($_SERVER['REQUEST_METHOD'] != 'POST') //show form if not posted
{
$sql = "SELECT * FROM category;";
$result = mysqli_query($conn,$sql);
?>
<form method="post" action="createTopic.php">
Choose a category:
</br>
</br>
<?php
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class= 'choice'><input type='radio' name='category' value='". $row['idcategory'] . "'>" . $row['categorySubject'] ."</div></br>";
}
echo 'Topic: <input type="text" name="topic" minlength="3" required>
</br></br>
<input type="submit" value="Add Topic" required>
</form>';
}
if ($_POST){
if(!isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == false)
{
echo 'You must be signed in to contribute';
}
else{
$sql="INSERT INTO topic(subject, topicDate, users_idusers, category_idcategory, category_users_idusers) VALUES('($_POST[topic])', '$date', '$_SESSION[userid]', '$getCatId', '$_SESSION[userid]');";
$result = mysqli_query($conn,$sql);
echo "Added!";
If I understand this question correctly, you'll have your $getCatId (id of the category) in $_POST['category'] (after sending form) in your case
The first thing you should do is protect yourself from SQL injection by parameterizing your queries before old Bobby Tables comes to pay you a visit.
You might also look into using PDO as I've demonstrated below because it's a consistent API that works with a lot of different database management systems, so this leads to wonderfully portable code for you. Here's an annotated working example on Github:
<?php
// returns an intance of PDO
// https://github.com/jpuck/qdbp
$pdo = require __DIR__.'/mei_DV59j8_A.pdo.php';
// dummy signin
session_start();
$_SESSION['signedIn'] = true;
$_SESSION['userid'] = 42;
//show form if not posted
if($_SERVER['REQUEST_METHOD'] != 'POST'){
$sql = "SELECT * FROM category;";
// run query
$result = $pdo->query($sql);
?>
<form method="post" action="createTopic.php">
Choose a category:
</br>
</br>
<?php
// get results
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "
<div class= 'choice'>
<input type='radio' name='category' value='$row[idcategory]'/>
$row[categorySubject]
</div>
</br>
";
}
echo '
Topic: <input type="text" name="topic" minlength="3" required>
</br></br>
<input type="submit" value="Add Topic" required>
</form>
';
}
if ($_POST){
if(!isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == false){
echo 'You must be signed in to contribute';
} else {
// simulate your date input
$date = date("Y-m-d");
// bind parameters
$sql = "
INSERT INTO topic (
subject, topicDate, users_idusers, category_idcategory, category_users_idusers
) VALUES(
:subject, :topicDate, :users_idusers, :category_idcategory, :category_users_idusers
);
";
// prepare and execute
$statement = $pdo->prepare($sql);
$statement->execute([
'subject' => "($_POST[topic])",
'topicDate' => $date,
'users_idusers' => $_SESSION['userid'],
// to answer your question, here's your variable
'category_idcategory' => $_POST['category'],
'category_users_idusers' => $_SESSION['userid'],
]);
echo "Added!";
}
}

insert multiple fields using foreach loop

I have a problem when I want to insert multiple fields into one table.
Here's my form:
<h1>Add user</h1>
<form method="post" action="index.php">
<table>
<thead>
<th>Name</th>
<th>Age</th>
</thead>
<tr>
<td><input name="name[]" type="text" /></td>
<td><input name="age[]" type="text" /></td>
</tr>
<tr>
<td><input name="name[]" type="text" /></td>
<td><input name="age[]" type="text" /></td>
</tr>
<tr>
<td><input name="name[]" type="text" /></td>
<td><input name="age[]" type="text" /></td>
</tr>
</table>
<input type="submit" name="submit" value="Submit" />
</form>
And here's the submit code:
if (isset($_POST['submit'])) {
foreach ($_POST as $val) {
$name = $val['name'];
$age = $val['age'];
mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
}
}
The query inserts into the database, but not the values that I've entered.
Can someone please help me?
You are doing a foreach on $_POST rather than on the name/age arrays. You should be doing foreach on name or age array like this:
if (
!empty($_POST['name']) && !empty($_POST['age']) &&
is_array($_POST['name']) && is_array($_POST['age']) &&
count($_POST['name']) === count($_POST['age'])
) {
$name_array = $_POST['name'];
$age_array = $_POST['age'];
for ($i = 0; $i < count($name_array); $i++) {
$name = mysql_real_escape_string($name_array[$i]);
$age = mysql_real_escape_string($age_array[$i]);
mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
}
}
I would also note that you are currently susceptible to SQL injection so I added the step of escaping your strings for name/age.
I would also highly suggest simply making a single bulk insert into the DB instead of an insert of each record individually (I will leave that up to you to implement). This approach is almost always preferable from a performance standpoint.
Finally, you REALLY should not be using mysql_* functions as they are deprecated. Consider changing to mysqli or PDO.
if (isset($_POST['submit'])) {
$i = 0;
foreach ($_POST as $val) {
$name = $_POST['name'][$i];
$age = $_POST['age'][$i];
mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
$i++;
}
}
This will solve your problem !
foreach($_POST['firstname'] as $key=>$value) {
$firstname = $_POST['firstname'][$key];
$lastname = $_POST['tipo'][$key];
echo "Parte: $lastname";
echo "<br>";
echo "Tipo: $firstname";
echo "<br>";
}
A little bit easier code which works for me well.
if (isset($_POST['submit'])) {
$i = 0;
for ((array) $_POST as $val) {
$sql = "INSERT INTO users (name, age) VALUES (
'{$_POST["name"][$i]}','{$_POST["age"][$i]}'
);
mysql_query($sql);
echo (!mysql_affetced_rows()) ? "Query Wrong" : "Query Okay";
$i++;
}
}
below is the fxample how to inset multi row at one time
$query_string = "INSERT INTO YOURTBL_NAME(column_1,column_2)VALUES";
$data ="";
for($i=0;$i<count($YOUR FILE ARRAY);$i++)
{
$data .='("'.$paramater_1[$i].'","'.$paramater_2.'"),';
}
$qry = substr($query_string.$data, 0, -1);
$result = mysql_query($qry);
$education_institute_array = $_POST['education_institute'];
$education_qualification_array = $_POST['education_qualification'];
$education_start_date_array = $_POST['education_start_date'];
$education_end_date_array = $_POST['education_end_date'];
$education_note_array = $_POST['education_note'];
for ($i = 0; $i < count($education_institute_array); $i++) {
$education_institute = mysql_real_escape_string($education_institute_array[$i]);
$education_qualification = mysql_real_escape_string($education_qualification_array[$i]);
$education_start_date = mysql_real_escape_string($education_start_date_array[$i]);
$education_end_date = mysql_real_escape_string($education_end_date_array[$i]);
$education_note = mysql_real_escape_string($education_note_array[$i]);
$sql_education_insert = "INSERT INTO `education` (`user_id`, `education_institute`, `education_qualification`, `education_start_date`, `education_end_date`, `education_note`) VALUES ('$user_id', '$education_institute', '$education_qualification', '$education_start_date', '$education_end_date', '$education_note')";
$sql_result_education = mysql_query($sql_education_insert);
}

PHP & MySQL INSERT INTO problem

Any ideas why the following code is not adding anything into the database once the user fills out the form? I'd really appreciate it.
Thank you!
if($_SESSION['loginSuccess']==1) {
// ============================================================
// = Create the table of current tasks stored in the database =
// ============================================================
$userID = $_SESSION['userID'];
$result = mysql_query("SELECT * FROM Tasks WHERE userID = '$userID'");
echo "<div id=\"draggable\" class=\"ui-widget-content\"><table border='5'><tr class=\"ui-widget-header\"><td><u>Task Name:</u></td><td><u>Class:</u></td><td><u>Due Date:</u></td><td><u>Task Type:</u></td></tr>";
echo $_SESSION['userID'];
while($row = mysql_fetch_array($result)) {
$taskName = $row[1];
$class = $row[2];
$taskDueDate = $row[3];
$taskType = $row[4];
echo "<tr><td>'$taskName'</td><td>'$class'</td><td>'$taskDueDate'</td><td>'$taskType'</td></tr>";
}
echo "</table>";
function addNewTask ($name, $class, $dueDate, $type) {
mysql_query("INSERT INTO Tasks VALUES ('$userID','$name', '$class', '$dueDate', '$type')");
}
if($_POST['taskName'] != NULL) {
addNewTask($_POST['taskName'], $_POST['class'], $_POST['dueDate'], $_POST['dueDate']);
}
?>
<!-- <img border="1" alt="New" src="/newTask.png" id="newTask" onmouseClick="showTaskField"/> -->
<p><form name="newTask" method="post" action="index.php" id="newTask"><br>
Task Name: <input name="taskName" type="text"> (necessary)<br>
Class: <input name="class" type="text"><Br>
Due Date: <input name="dueDate" type="text" id="datepicker"><Br>
Type:
<input type="submit"></p></div>
Try getting rid of the ' around the variables in the insert statement. If that does nothing echoing mysql_error().

Categories