Get existing form with earlier values in sql - php

I'm getting questions from questions table in db.
I'm saving question_id and answer_value with an unique form_id and user_id to answers table in database.
I would like for the user to be able to update the form another day. So how can i get and display the form with answer_value already filled out based on the users earlier answer?
This is how i display questions from db:
<form action="/form/insert.php" method="POST">
$query = "SELECT * FROM questions where active=1 AND question_sort=1 ORDER BY sort_by";
$result = #mysqli_query($con, $query);
if ($result) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$body = $row['question_body'];
$question_id = $row['question_id'];
echo '<tr>
<td class="question">'.$body.'</td>
<td class="answer"><input type="radio" name="answer_value['.$question_id.']" value="0" ></td>
<td class="answer"><input type="radio" name="answer_value['.$question_id.']" value="1" ></td>
<td class="answer"><input type="radio" name="answer_value['.$question_id.']" value="2" ></td>
</tr>';
}
</form>
This is how i save every unicqe form to db:
$question_id = mysqli_real_escape_string($con, $_POST['question_id']);
$user_id = mysqli_real_escape_string($con, $_POST['user']);
$form_id = mysqli_real_escape_string($con, $_POST['form_id']);
$form_date = gmdate('Y-m-d H:i:s');
foreach ($_POST['answer_value'] as $question_id => $answer_id){
$sql="INSERT INTO answers (question_id, answer_value, user_id, form_id, form_date)
VALUES ({$question_id}, {$answer_id}, $user_id, {$form_id}, '$form_date')";

you have to loop through the values and match to the answer value you stored
<form action="/form/insert.php" method="POST">
<?php
$vals=array(0,1,2);
$query = "SELECT * FROM questions where active=1 AND question_sort=1 ORDER BY sort_by";
$result = #mysqli_query($con, $query);
if ($result) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$body = $row['question_body'];
$question_id = $row['question_id'];
echo '<tr>
<td class="question">'.$body.'</td>';
foreach($vals as $x){
$s='';
if($x==$row['answer_value']){
$s="selected";
}
echo '<td class="answer"><input type="radio" name="answer_value['.$question_id.']" value="'.$x.'" '.$s.'></td>';
}
echo '</tr>';
}
}
?>
</form>

Related

delete from MySQL database using checkboxes

I'm attempting to delete a row from a table with data that is generated from a MySQL table. I took a look at both of these questions:
1. How to delete rows of database results using checkbox
2.Deleting multiple rows using checkboxes, PHP and MySQL.
I need help for code delete using checkboxes..
<?php
$sql = mysqli_query($conn, "SELECT * FROM leads ORDER BY lid ASC");
if(mysqli_num_rows($sql) == 0){
echo '<tr><td colspan="8">No Data Entry</td></tr>';
}else{
while($row = mysqli_fetch_assoc($sql)){
echo '<tr>
<td> <input name"checkbox[]" value"'.$row['lid'].'" type="checkbox"></td>
<td>'.$row['name'].'</td>
<td>'.$row['sex'].'</td>
<td>'.$row['phone'].'</td>
<td>'.$row['company'].'</td>
<td>'.$row['vehicle'].'</td>
</tr>';
}
}?>
Cancel
<?php
$del_lid = $_POST['checkbox'];
if (isset($_POST['submit'])) {
foreach($del_lid as $value){
$sql = "DELETE FROM leads WHERE lid='".$value."'";
$result = mysqli_query($conn, $sql);
}
}
?>
The checkboxes were missing the equals sign so effectively none of them had a value. The sql could be streamlined to use the in operator rather than a loop.
<table>
<?php
$sql = mysqli_query($conn, "SELECT * FROM leads ORDER BY lid ASC");
if( mysqli_num_rows($sql) == 0 ){
echo '<tr><td colspan="8">No Data Entry</td></tr>';
}else{
while($row = mysqli_fetch_assoc($sql)){
echo '
<tr>
<td> <input name="checkbox[]" value="'.$row['lid'].'" type="checkbox"></td>
<td>'.$row['name'].'</td>
<td>'.$row['sex'].'</td>
<td>'.$row['phone'].'</td>
<td>'.$row['company'].'</td>
<td>'.$row['vehicle'].'</td>
</tr>';
}
}
?>
</table>
<input type="submit" name="delete" class="btn btn-sm btn-primary" value="delete">
Cancel</td>
</form>
</div>
<?php
$del_lid = $_POST['checkbox'];
if ( isset($_POST['submit'] ) ) {
$sql='delete from `leads` where `lid` in ( ' . implode( ',', $del_lid ). ' )';
$result = mysqli_query($conn, $sql);
}
?>

How to insert multiple rows of student records scores in a while loop in a database table?

I want to create a table with input fields where student records can be inserted. The name of the students are in the first column of the table fetched from the database with a while loop. The other columns contain fields for inputing the student scores. The challenge I'm facing is how to insert the records of all the students in different row of a table called result_sec into the database. I've search for similar post but couldn't get a suitable answer. Below is the code. Thanks in advance.
<?php require('header.php'); ?>
<?php
$query_form = sprintf("SELECT * FROM regform LIMIT 2");
$form = mysqli_query($conn, $query_form) or die(mysqli_error($conn));
$formdata = mysqli_fetch_assoc($form);
if(isset($_POST['submit']))
{
$exes = $_POST['exe'];
$asss = $_POST['ass'];
$ca1s = $_POST['ca1'];
$ca2s = $_POST['ca2'];
$exams = $_POST['exam'];
foreach($exes as $key => $exe)
{
$sql = "INSERT INTO result_sec (exe, ass, ca1, ca2, exam) VALUES ('$exe', '$asss[$key]', '$ca1s[$key]', '$ca2s[$key]', '$exams[$key]')";
}
$insert = mysqli_multi_query($conn, $sql);
}
?>
<form method="POST">
<table>
<thead>
<tr>
<th>Name</th>
<th>Ass.</th>
<th>Exe.</th>
<th>1st C.A.</th>
<th>2nd C.A.</th>
<th>Exam</th>
</tr>
</thead>
<tbody>
<?php do { ?>
<tr>
<td><?php echo $formdata['surname']." ".$formdata['firstname']; ?></td>
<td><input name="ass[]" size="1px"/></td>
<td><input name="exe[]" size="1px" /></td>
<td><input name="ca1[]" size="1px" /></td>
<td><input name="ca2[]" size="1px" /></td>
<td><input name="exam[]" size="1px" /></td>
<input type="hidden" name="regformid[]" value="<?php echo $formdata['regformid'];?>" />
</tr>
<?php } while ($formdata = mysqli_fetch_assoc($form)); ?>
</tbody>
</table>
<button type="submit">Insert Student Record</button>
</form>
<?php require('footer.php'); ?>
See If this resolve your problem
if(isset($_POST['submit'])){
$exes = $_POST['exe'];
$asss = $_POST['ass'];
$ca1s = $_POST['ca1'];
$ca2s = $_POST['ca2'];
$exams = $_POST['exam'];
//You can use a foreach loop to loop over one of the repeated inputs, and then use the index to access the corresponding elements in the others:
foreach ($exes as $i => $exe) {
$exee = mysqli_real_escape_string($exe);
$ass = mysqli_real_escape_string($asss[$i]);
$ca1 = mysqli_real_escape_string($ca1s[$i]);
$ca2 = mysqli_real_escape_string($ca2s[$i]);
$exam = mysqli_real_escape_string($exams[$i]);
$sql = "INSERT INTO result_sec (exe, ass, ca1, ca2, exam)
VALUES ('$exee', '$ass', '$ca1', '$ca2', '$exam')";
$insert = mysqli_multi_query($conn, $sql);
}
}

Trying to insert all the information in the form to update in the database

thanks for taking a look at this. I have been stuck at this problem for awhile basically i am doing a recruitment agency website for my school project. I am doing the function where i can view all the candidate who applied for any job and i can choose from the dropdown box whether to "approval", "denied", or remain as "pending" which it should update the table in the database to the option i chose and it will reflect at the candidate's page. However with the codes i am using right now, it is able to display all the information i need from the different table on the page but when i try to submit the details, it only works for the last guy that applied and not the rest.
This is the form :
<form method="post" action="doEditStatus.php">
<div align ="center">
<table border='1' width ="500">
<tr>
<td> <b> ID </b></td>
<td> <b> Candidate name </b></td>
<td> <b> Job ID </b></td>
<td> <b> Job title </b></td>
<td> <b> Company </b></td>
<td> <b> Shortlist status </b></td>
</tr>
while ($row = mysqli_fetch_array($result)) {
$jobid = $row['Job_id'];
$canid = $row['Candidate_id'];
?>
<tr>
<td><?php echo $canid; ?></td>
<input type="hidden" name="can_id" value=<?php echo $canid ?>>
<input type="hidden" name="job_id" value=<?php echo $jobid ?>>
<?php
$query2 = "SELECT * FROM candidate WHERE Candidate_id =$canid";
$result2 = mysqli_query($link, $query2) or die(mysqli_error($link));
while ($row2 = mysqli_fetch_array($result2)) {
$canname = $row2['First_name']." ".$row2['Last_name'];
?>
<td><?php echo $canname; ?></td>
<?php
}
$query3 = "SELECT * FROM jobs WHERE Job_id =$jobid";
$result3 = mysqli_query($link, $query3) or die(mysqli_error($link));
while ($row3 = mysqli_fetch_array($result3)) {
$jobname = $row3['Job_title'];
$comid = $row3['Company_id'];
?>
<td><?php echo $jobid; ?></td>
<td><?php echo $jobname; ?></td>
<?php
}
$query4 = "SELECT * FROM company WHERE Company_id =$comid";
$result4 = mysqli_query($link, $query4) or die(mysqli_error($link));
while ($row4 = mysqli_fetch_array($result4)) {
$comname = $row4['Company_name'];
?>
<td><?php echo $comname; ?></td>
<?php
}
?>
<td>
<select id="id_status" name="shortlist_status">
<option value="0">Pending...</option>
<option value="1">Shortlist</option>
<option value="2">Denied</option>
</select>
</td>
</tr>
<?php
}
?>
</table>
</div>
<input type="submit" value="Submit"/>
</form>
This is the dosubmit page:
<?php
include "dbFunctions.php";
session_start();
$candidate_id = $_POST['can_id'];
$job_id = $_POST['job_id'];
$status = $_POST['shortlist_status'];
$insertQuery = "UPDATE application SET Shortlist_status = '$status' WHERE Candidate_id = $candidate_id AND Job_id = $job_id";
$inserted = mysqli_query($link, $insertQuery) or die(mysqli_error($link));
if($inserted)
{
$message = 'Profile edited successfully <br>Home';;
echo $candidate_id;
echo $status;
}
else
{
$message = "Profile edited failed";
}
echo $message;
?>
Give all your inputs names that end with []. PHP will then create an array for each of them in $_POST. E.g.
<input type="hidden" name="can_id[]" value=<?php echo $canid ?>>
<input type="hidden" name="job_id[]" value=<?php echo $jobid ?>>
Then your PHP can do:
$insertQuery = "UPDATE application SET Shortlist_status = ? WHERE Candidate_id = ? AND Job_id = ?";
$insertStmt = mysqli_prepare($link, $insertQuery);
mysqli_stmt_bind_param($insertStmt, "iii", $status, $candidate_id, $job_id);
foreach ($_POST['can_id'] as $i => $candidate_id) {
$job_id = $_POST['job_id'][$i];
$status = $_POST['shortlist_status'][$i];
$inserted = mysqli_execute($insertStmt) or die(mysqli_error($insertStmt));
if ($inserted) {
...
} else {
...
}
}

Image is not storing in mysql database via php

I am trying to upload image and store it in mysql database through php. but no image is storing in database.
<form action="" method="get" name="frmPostImage" class="box" enctype="multipart/form-data">
<table>
<tr>
<td><b>City:</b></td>
<td>
<select name="cityid">
<?php
$sql = "SELECT cityid, cityname, countryname
FROM $t_cities ct
INNER JOIN $t_countries c ON ct.countryid = c.countryid
ORDER BY c.pos, ct.pos";
$res = mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($res))
{
echo "<option value=\"$row[cityid]\"";
if ($row['cityid'] == $_REQUEST['cityid']) echo " selected";
echo ">$row[countryname] > $row[cityname]</option>";
}
?>
</select>
</td>
</td>
</tr>
<tr>
<tr>
<td><b><?php echo $lang['POSTIMG_IMAGE_TITLE']; ?>:</b><span class="marker">*</span></td>
<td><input name="imgtitle" type="text" id="imgtitle" size="55" maxlength="100" value="<?php echo isset($data
['imgtitle']); ?>"><br><img
src="images/spacer.gif"></td>
</tr>
<tr>
<td><b><?php echo $lang['POSTIMG_IMAGE_FILE']; ?>:</b><span class="marker">*</span></td>
<td><input name="img" type="file" size="45"><br><img src="images/spacer.gif"></td>
</tr>
<tr>
<td><b><?php echo $lang['POSTIMG_IMAGE_DESCRIPTION']; ?>:</b></td>
<td><textarea name="imgdesc" type="text" rows="5" cols="54"><?php echo $data['imgdesc']; ?></textarea><br><img
src="images/spacer.gif"></td>
<td> <input type="hidden" name="do" value="save"><button type="submit">Go</button></td>
</tr>
</table>
</form>
and following code to store it into database.
$expiry = time()+($expire_images_after*24*60*60);
$expiry_dt = date("Y-m-d H:i:s", $expiry);
$city = $_REQUEST['cityid'];
// Temporary file name stored on the server
$tmpName = $_FILES['img']['tmp_name'];
$sql = "INSERT INTO $t_imgs
SET imgtitle = '$_GET[imgtitle]',
imgfilename = '$tmpName',
imgdesc = '$_GET[imgdesc]',
postername = '$data[postername]',
cityid = '$city',
ip = '$ip',
verified = '1',
enabled = '1',
createdon = NOW(),
expireson = '$expiry_dt',
timestamp = NOW()";
mysql_query($sql) or die($sql.mysql_error());
if (mysql_affected_rows())
{
// Get ID
$sql = "SELECT LAST_INSERT_ID() FROM $t_imgs";
list($imgid) = mysql_fetch_array(mysql_query($sql));
}
}
?>
<h2><?php echo $lang['POST_IMAGE_SUCCESS']; ?></h2>
i am able to store every other value except the image. tried different combination but nothing worked. Guide me...:)
I think there can be issues with mysql statement:
instead $sql = "INSERT INTO $t_imgs SET imgtitle
you should probably use $sql = "INSERT INTO $t_imgs values (imgtitle, ...);
check here:
http://dev.mysql.com/doc/refman/5.5/en/insert.html

Inserting multiple checkbox values to MySQL

I know there are multiple questions here on SO regarding this same issue already and I've looked into them but didn't quite get a satisfying answer. So here goes my question,
I have a form which consists of a few textboxes and checkboxes. It looks like this,
The user can select multiple checkboxes. I'm trying to insert the values(not the displaying text string) of those checkboxes into a MySQL table. It should look like this,
One Service ID(SID) can have multiple Locations(Loc_Code). Those location codes (CO, GQ) are the values of the checkboxes.
I've written this following code so far.
<html>
<head>
</head>
<body>
<?php
require_once("db_handler.php");
$conn = iniCon();
$db = selectDB($conn);
/* Generating the new ServiceID */
$query = "SELECT SID FROM taxi_services ORDER BY SID DESC LIMIT 1";
$result = mysql_query($query, $conn);
$row = mysql_fetch_array($result);
$last_id = $row["SID"];
$id_letter = substr($last_id, 0, 1);
$id_num = substr($last_id, 1) + 1;
$id_num = str_pad($id_num, 3, "0", STR_PAD_LEFT);
$new_id = $id_letter . $id_num;
//Selecting locations
$query = "SELECT Loc_Code, Name FROM districts";
$result = mysql_query($query, $conn);
$count = mysql_num_rows($result);
?>
<?php
if(isset($_POST["savebtn"]))
{
//inserting the new service information
$id = $_POST["sid"];
$name = $_POST["name"];
$cost = $_POST["cost"];
if($_POST["active"] == "on") $active = 1; else $active = 0;
$query = "INSERT INTO taxi_services(SID, Name, Cost, Active) VALUES('$id', '$name', '$cost', '$active')";
$result = mysql_query($query, $conn);
//inserting the location details
for($j = 0; $j < $count; $j++)
{
$loc_id = $_POST["checkbox2"][$j];
$query = "INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id')";
$result5 = mysql_query($query, $conn);
}
if (!$result || !$result5)
{
die("Error " . mysql_error());
}
else
{
?>
<script type="text/javascript">
alert("Record added successfully!");
</script>
<?php
}
mysql_close($conn);
}
?>
<div id="serv">
<b>Enter a new taxi service</b>
<br/><br/>
<form name="servForm" action="<?php $PHP_SELF; ?>" method="post" >
<table width="300" border="0">
<tr>
<td>Service ID</td>
<td><input type="text" name="sid" readonly="readonly" value="<?php echo $new_id; ?>" style="text-align:right" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name" style="text-align:right" /></td>
</tr>
<tr>
<td>Cost</td>
<td><input type="text" name="cost" style="text-align:right" onkeypress="return isNumberKey(event)" /></td>
</tr>
<tr>
<td>Active</td>
<td><input type="checkbox" name="active" /></td>
</tr>
</table>
</div>
<div id="choseLoc">
Locations <br/><br/>
<table border="0">
<?php
$a = 0;
while($row = mysql_fetch_array($result))
{
if($a++ %5 == 0) echo "<tr>";
?>
<td align="center"><input type="checkbox" name="checkbox2[]" value="<?php echo $row['Loc_Code']; ?>" /></td>
<td style="text-align:left"><?php echo $row["Name"]; ?></td>
<?php
if($a %5 == 0) echo "</tr>";
}
?>
</table>
</div>
<br/>
<div id="buttons">
<input type="reset" value="Clear" /> <input type="submit" value="Save" name="savebtn" />
</form>
</div>
</body>
</html>
It inserts the Service details correctly. But when it inserts location data, a problem like this occurs,
I selected 4 checkboxes and saved. The 4 location codes gets saved along with the service ID. But as you can see from the screenshot above, a bunch of empty rows gets inserted too.
My question is how can I stop this from happening? How can I insert the data from the checkboxes only I select?
Thank you.
One way would be to only loop over the checkboxes that were submitted:
//inserting the location details
foreach($_POST["checkbox2"] as $loc_id)
{
$query = "INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id')";
$result5 = mysql_query($query, $conn);
}
I reiterate here the SQL injection warning given above: you would be much better off preparing an INSERT statement and then executing it with parameters. Using PDO, it would look something like:
//inserting the location details
$stmt = $dbh->prepare('
INSERT INTO service_locations(SID, Loc_Code) VALUES(:id, :loc)
');
$stmt->bindValue(':id', $id);
$stmt->bindParam(':loc', $loc_id);
foreach($_POST["checkbox2"] as $loc_id) $stmt->execute();
from these sentence:
for($j = 0; $j < $count; $j++)
{
$loc_id = $_POST["checkbox2"][$j];
$query = "INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id')";
$result5 = mysql_query($query, $conn);
}
i find the problem is that the value of loc_code must be the last loction you selected. because in this loop, the value of loc_code will replaced everytime. if you want to insert all the location, you should put it on the one sentence, like INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id'), the value of $loc_id should be CO,GQ,GL.
This is happening because the checkboxes that weren't ticked still get posted, they just have empty values. Before you do your insert to service_locations just check if $loc_id is empty or not, only do the insert if it isn't.

Categories