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)
Related
I am currently creating a survey where the answers are entered into a database.
I have 2 main tables:
questions, with 2 columns: questionID and questionBody
answers, with 3 columns: answerID, questionID (I want this to be tied to the column in table questions) and answerBody.
On the HTML page I am planning to create there will be multiple questions with multiple text boxes to fill in correlating to each quesiton. Is it possible that when the person submits the form, the answers are inserted into table answers with the questionID being based on what field was filled out?
So for example, If I have questionBody as "What is this Question asking?" and the questionID as 1 in table questions, when I submit the form I want table answers to also have questionID 1 in there.
At the moment this is my code:
//Check if error variables have any values assigned
if (empty($answerError))
{
//Prepare database insert
$sql = "INSERT INTO answers (questionID, answerBody) VALUES (?,?)";
//Check if the statement has the connect and sql variables
if ($statement = mysqli_prepare($connect, $sql))
{
//Add variables to the statement
mysqli_stmt_bind_param($statement, "ss", $paramQuestion, $paramAnswer);
//Set the parameter to the answer
$paramQuestion = getQuestionName($connect);
$paramAnswer = $answer;
//Execute statement with entered variable
if (mysqli_stmt_execute($statement))
{
//Redirect user to success page
header("location: thankyou.php");
}
else
{
echo "Something went wrong. Please try again later.";
}
//Close statement
mysqli_stmt_close($statement);
}
}
and for the function getQuestionName():
function getQuestionName($connect)
{
$query = "SELECT * FROM questions";
$result = mysqli_query($connect, $query);
if ($result)
{
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$questionID = $row['questionID'];
return $questionID;
}
}
}
The code I am using to output the form into a HTML page is:
function getQuestions($connect)
{
$query = "SELECT * FROM questions";
$result = mysqli_query($connect, $query);
if ($result)
{
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$body = $row['questionBody'];
echo '<div class="entry">
<div class="questionTitle"><h3>' . $body . '</h3>
<form action="survey.php" method="POST">
<input type="text" name="answer" size="50" />
<input type="submit" value="Submit" name="submit" />
</form>
</div>
</div>';
}
}
Any help on this would be greatly appreciated :)
Yes it's completely possible. Just put the question ID as a hidden field in the form, and it will be submitted along with the answer data when the form is submitted. Then you can retrieve it from the $_POST data just like the answer, and use it in your SQL query.
For example:
HTML form:
<form action="survey.php" method="POST">
<input type="hidden" name="questionID" value="<?php echo $row["questionID"]; ?>" />
<input type="text" name="answer" size="50" />
<input type="submit" value="Submit" name="submit" />
</form>
survey.php:
$paramQuestion = $_POST["questionID"];
From your question, I will suggest you make use of input with a hidden attribute.
something like this
<input type='text' name='question-id' value="<?php echo $questionId ;?>" hidden>
The user doesn't see the input it get filled from whatever you are providing into it.
Editing your code, you should do something like this.
function getQuestions($connect)
{
$query = "SELECT * FROM questions";
$result = mysqli_query($connect, $query);
if ($result)
{
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$body = $row['questionBody'];
$questionId = $row['questionId'];
echo '<div class="entry">
<div class="questionTitle"><h3>' . $body . '</h3>
<form action="survey.php" method="POST">
<input type="text" name="answer" size="50" />
<input type="number"name="question-id" value="'.$questionId.'" hidden>
<input type="submit" value="Submit" name="submit" />
</form>
</div>
</div>';
}
}
I have this table in with some rows and values in it, i get those values in my php page and user selects them and submits the same to insert the selected into another page.
So, here the main catch,
I wrote a sql query with 3 input boxes in which one takes input number from user and multiplies it with other default number in input box 2(which get the value from table1) and prints it out in input box 3.
I wrote JS code for it and it works fine. now i added php to it, in a way that input box 1 takes value directly from php table row and multiplies it with user inserted value in box2 and prints it in box 3
It still works fine even with multiple queries, cause i have made the id value of each box dynamic.
But the problem rises as when i try to submit the three input box values, it works fine for one query/when one row in table1 but when there are multiple queries, it only inserts the first query (3 input box values) and skips the rest of the queries.
My Php , Js, Html code goes as:
<?php
$sql2 = "SELECT * FROM table1 WHERE value= '$value'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
?>
<input type="number" name="input1" form="checkout" class="input1" id="input1_<?php echo $row2['id']; ?>" value="<?php echo $row2['price']; ?>">
<input type="text" name="input2" class="input2" id="input2_<?php echo $row2['id']; ?>" value="0" >
<input type="text" name="output" class="output" form="checkout" id="output_<?php echo $row2['id']; ?>" value="">
<form method="post" action="submit.php" id="checkout">
<input type="hidden" value="<?php echo $row2["id"]; ?>" name="id"/>
<button type="submit" class="btn btn-primary btn-sm btn-block">
<h4>Submit</h4>
</button>
</form>
The submit page looks like this..
$input1 = $_POST['input1'];
$output = $_POST['output'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO table2 (input1, output)
VALUES ('$input1', '$output')";
if ($conn->query($sql) === TRUE) {
}
else {
echo "ERROR" . $sql . "<br>" . $conn->error;
}
Now the problem is , it works fine inserting data from input1 and output boxes into tabll2 when there is only one query in table 1,
but when there are multiple queries in table 1, it only inserts the first query leaving the rest untouched with no error.
Any help is appreciated..
Then main reason is that all the text boxes for input1 field have one name, then at the result there is only one variable $_POST["input1"], so for other text boxes.
You must set an array-like names for your text boxes:
<?php
$sql2 = "SELECT * FROM table1 WHERE value= '$value'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
?>
<form method="post" action="submit.php" id="checkout">
<?php
while($row2 = $result2->fetch_assoc()) {
?>
<input type="number" name="input1-<?php echo $row2['id']; ?>" form="checkout" class="input1" id="input1_<?php echo $row2['id']; ?>" value="<?php echo $row2['price']; ?>">
<input type="text" name="input2-<?php echo $row2['id']; ?>" class="input2" id="input2_<?php echo $row2['id']; ?>" value="0" >
<input type="text" name="output-<?php echo $row2['id']; ?>" class="output" form="checkout" id="output_<?php echo $row2['id']; ?>" value="">
<?php
}
?>
<input type="hidden" value="<?php echo $row2["id"]; ?>" name="id"/>
<button type="submit" class="btn btn-primary btn-sm btn-block">
<h4>Submit</h4>
</button>
</form>
<?php
}
?>
Then you must set the submit page:
<?php
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql2 = "SELECT * FROM table1 WHERE value= '$value'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$input1 = $_POST['input1-'.$row2['id']];
$output = $_POST['output-'.$row2['id']];
$sql = "INSERT INTO table2 (input1, output) VALUES ('$input1', '$output')";
if ($conn->query($sql) === TRUE) {
}
else {
echo "ERROR" . $sql . "<br>" . $conn->error;
}
}
?>
I created a form that populates a database containing customer data. What i'd like to do is that when isset($_POST["submit"]), a GET parameter is appended to the URL, like &customer=<?php echo $last_id ?> where $last_id = mysqli_insert_id($connection);
Is this possible? Would this be a true GET parameter inserted in the GET array? Is also possible to populate the form with this newly added parameter?
Thank you very much!
This is the code, simplified
<?php
if(isset($_POST["submit"]) {
$nome_paciente = mysql_pre($_POST["nome"]);
$query = "INSERT INTO pacientes (";
$query .= "id, nome";
$query .= ") VALUES (";
$query .= "$id, \"{$nome_paciente}\"
$query .= ")";
$result = mysqli_query($connection, $query);
?>
<form action="cadastro_paciente.php?subject=1&paciente=<?php echo $_POST["id"]; ?>" method="post" class="form-cadastro">
<div class="first-value">
<p class="opensans">Nome: </p>
<input type="text" class="table-nome" name="nome" value="<?php echo $nome ?>">
</div>
<input type="text" class="id" name="id" style="display:none" value="$_GET['id']">
<?php } else { ?>
<form action="cadastro_paciente.php?subject=1&paciente=<?php echo $_POST["id"]; ?>" method="post" class="form-cadastro">
<div class="first-value">
<p class="opensans">Nome: </p>
<input type="text" class="table-nome" name="nome" value="<?php echo $nome ?>">
</div>
<input type="text" class="id" name="id" style="display:none" value="$_GET['id']">
?php } ?>
but i keep getting in my url:
&paciente=<br%20/><b>Notice</b>:%20%20Undefined%20index:%20id%20in%20<b>C:\xampp\htdocs\...
Thanks
I have a problem to visualize the solution for the problem that I have now.
The user is allowed to insert a row in a table.
And I try to display a button (input) +1 who allow the user to increment a column (vote) in a selected row among all created.
The problem is that I don't get the thing for rely incrementation to the desired id.
Here my code :
<form action="" method="post">
<input type="text" name="disease">name
<input name="mainsubmit" type="submit" value="submit">
</form>
</body>
</html>
<?php
if(isset($_POST['mainsubmit']))
{
$nameDisease = $_POST['disease'];
$req = $db->prepare('INSERT into disease(name) VALUES(:name)');
$req->execute(array('name' => $nameDisease));
}
$query = $db->query('SELECT * FROM disease');
while ($result = $query->fetch())
{
$id = $result['id'];
echo $id ?>
<form action="" method="post"> <input name="secondsubmit" type="submit" value="+1"> </form><?php
if(isset($_POST['secondsubmit']))
{
$db->exec("UPDATE disease SET vote = vote + 1 WHERE id = " .$id);
}
}
Logically, the code above doesn't work but I don't understand how find the solution.
In brief, i want to allow the user to increment a column in a selected row.
Thanks
Edit: Shadow, it's not my problem because your solution is used for automatically chose between INSERT or UPDATE if the line doesn't exist or exist. Me, I want allow the user to create rows and allow he to vote +1 on each of one that exist, and it will not be possible for he to insert a row from the input +1.
I created code snippet similar to your code style.
You have two submit buttons so you need to separate handling of those two requests.
The $id of the item you want to update in the second submit need's to come from hidden value in form.
In order for this to work you need to create table in mysql:
create table disease (id MEDIUMINT NOT NULL AUTO_INCREMENT, name VARCHAR(20), vote INTEGER, PRIMARY KEY (id)); - for example like this
<html>
<body>
<form action="" method="post">
<input type="text" name="disease">name
<input name="mainsubmit" type="submit" value="submit">
</form>
</body>
</html>
<?php
$db = new PDO('mysql:dbname=phpapp;host=db', 'root', 'phpapptest');
if (isset($_POST['mainsubmit'])) {
$nameDisease = $_POST['disease'];
$req = $db->prepare('INSERT into disease (name, vote) VALUES(:name, 0)');
$req->bindParam(':name', $nameDisease);
$req->execute();
$query = $db->query('SELECT * FROM disease');
while ($result = $query->fetch()) { ?>
<form action="" method="post">
<p><?php echo $result['name'] . " : " . $result['vote'];?>
<input name="secondsubmit" type="submit" value="+1" />
<input type="hidden" name="id" value="<?php echo $result['id'];?>" />
</p>
</form>
<?php }
}
if (isset($_POST['secondsubmit'])) {
$req = $db->prepare("UPDATE disease SET vote = vote + 1 WHERE id = " . $_POST['id']);
$req->execute();
$query = $db->query('SELECT * FROM disease');
while ($result = $query->fetch()) {?>
<form action="" method="post">
<p><?php echo $result['name'] . " : " . $result['vote'];?>
<input name="secondsubmit" type="submit" value="+1" />
<input type="hidden" name="id" value="<?php echo $result['id'];?>" />
</p>
</form>
<?php }
}
?>
I am trying to create a form that will edit rows from my db table. (Based on some code I got from a StackOverflow page.)
I am able to populate the form with relevant data, but when I submit the form, the row isn't updated. In fact, some of my columns are deleted.
What did I do wrong?
edit.php
<?php
$UID = (int)$_GET['f'];
$query = mysql_query("SELECT * FROM user_feeds WHERE feed_id = '$UID'") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$feedtitle = $row['feed_title'];
$feedurl = $row['feed_url'];
$feedorder = $row['feed_order'];
$feedowner = $row['feed_owner'];
}
?>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?=$UID;?>">
Title:<br /> <input type="text" name="ud_feedtitle" value="<?=$feedtitle?>"><br>
URL: <br /> <input type="text" name="ud_feedurl" value="<?=$feedurl?>"><br>
Order: <br /> <input type="text" name="ud_feedorder" value="<?=$feedorder?>"><br>
Owner:<br /> <input type="text" name="ud_feedowner" value="<?=$feedowner;?>"><br>
<input type="Submit">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
</div>
</body>
</html>
update.php
<?php
$ud_ID = $_REQUEST["ID"];
$ud_feedtitle = $_POST["feed_title"];
$ud_feedurl = $_POST["feed_url"];
$ud_feedorder = $_POST["feed_order"];
$ud_feedowner = $_POST["feed_owner"];
$query = "UPDATE user_feeds SET feed_title = '$ud_feedtitle', feed_url = '$ud_feedurl', feed_order = '$ud_feedorder', feed_owner = '$ud_feedowner', WHERE feed_id = '$ud_ID'";
$res = mysql_query($query);
if ($res)
echo "<p>Record Updated<p>";
else
echo "Problem updating record. MySQL Error: " . mysql_error();
?>
Reason:
The name of the input field is the same name by which $_POST is populated. The variables you are currently requesting :
$_POST["feed_title"];, $_POST["feed_url"];, $_POST["feed_order"];, $_POST["feed_owner"];
are all empty as they don't exist. When updating, you are replacing the values in your table with blank values.
Solution:
In your update.php, the following should be there instead.
$ud_ID = $_POST["ID"];
$ud_feedtitle = $_POST["ud_feedtitle"]; //corresponding to <input type="text" name="ud_feedtitle" ...
$ud_feedurl = $_POST["ud_feedurl"]; //corresponding to <input type="text" name="ud_feedurl" ...
$ud_feedorder = $_POST["ud_feedorder"]; //corresponding to <input type="text" name="ud_feedorder" ...
$ud_feedowner = $_POST["ud_feedowner"]; //corresponding to <input type="text" name="ud_feedowner" ...