Inserting Multiple data into MYSQL database - php

I am having problem inserting multiple data into MYSQL database. With the code below, I am only able to insert the data I have input. Let's say there are 3 questions and I must submit 3 inputs, it only submitted the last one.
<?php
include('questionDB.php');
if(isset($_POST['submit'])){
$questionID = $_POST['id'];
$answer = mysql_real_escape_string(htmlspecialchars($_POST['answer']));
$insert = mysql_query("INSERT INTO answers(survey_id, question_id, answer_body) VALUES ('1','" . $questionID . "', '" . $answer . "')");
if ($insert){
echo "Success";
} else {
echo "Failed";
}
}
$startTimeAuc = mysql_query("SELECT startTime FROM questions WHERE survey_id='1'");
$startTime = mysql_fetch_assoc($startTimeAuc);
$startTime = ($startTime['startTime']);
$endTimeAuc = mysql_query("SELECT endTime FROM questions WHERE survey_id='1'");
$endTime = mysql_fetch_assoc($endTimeAuc);
$endTime = ($endTime['endTime']);
$currentTimeAuc =(date("Y-m-d H:i:s"));
if( ( $currentTimeAuc >= $startTime && $currentTimeAuc <= $endTime)){
?>
<form name="auctionQuestion" method="post">
<?php
$auctionSurvey = "SELECT question_id, survey_id, question_body FROM questions
WHERE survey_id='1'";
$aucResult = mysql_query($auctionSurvey) or die (mysql_error());
while($auctionRow = mysql_fetch_assoc($aucResult)){
echo "<p class=\"questions\">". $auctionRow['question_body']."</p>". "<input type=\"text\" name=\"answer\" class=\"answerField\"><BR>";
?>
<input type="hidden" name="id" value="<?php echo $auctionRow ['question_id'] ?>">
<?php
}
?>
<input type="submit" class="submit" name="submit" value="Submit">
</form>
</div>
<?php
}
?>

Few points:
1. your code is vulnerable to sql injection, use prepared data or SQLI/PDO
2. All your questions and answers are given the same name that's why you get only one inserted. Try giving them different names (using -1/-2/-3 sufix etc.), or if I make this, I would have 3 questions and 3 answers in the same record in database instead of inserting 3 times.
3. See below part. You need to add variables to both answer and id. Otherwise they are getting the same name.
<input type=\"text\" name=\"answer\" class=\"answerField\">
<input type="hidden" name="id" value="<?php echo $auctionRow ['question_id'] ?>">

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)

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!";
}
}

Saving multiple form data to mysql using php

I have a table form which has a add new row button which upon clicked adds a new row to the table. I am trying to save all the rows in MySQL on clicking save button.
The code I wrote saves only one row no matter how many row I add. Could someone please tell my what am I doing wrong.
I searched Google but couldn't get anywhere.
Here are my codes:
save.php
<?php
include('connection.php');
if(isset($_POST['submit'])){
$row_data = array();
foreach($_POST['category'] as $row=>$category){
$category = mysql_real_escape_string($category);
$itemName = mysql_real_escape_string($_POST['itemName'][$row]);
$brand = mysql_real_escape_string($_POST['brand'][$row]);
$model = mysql_real_escape_string($_POST['model'][$row]);
$sellingPrice = mysql_real_escape_string($_POST['sellingPrice'][$row]);
$row_data[] = "('$category','$itemName','$brand','$model','$sellingPrice')";
}
}
if(!empty($row_data)){
$insert_query = mysql_query("INSERT INTO sale(Category,ItemName,Brand,Model,SellingPrice) VALUES".implode(',', $row_data));
if(!$insert_query){
echo "Error: " . mysql_error();
}else{
echo "Data Saved Successfully";
}
}
?>
and this is my html form
<form name="form1" id="myForm" action="saveSale.php" method="post">
<tr class="cloneme">
<td><input type="text" name="category[]"></td>
<td><input type="text" name="itemName[]"></td>
<td><input type="text" name="brand[]"></td>
<td><input type="text" name="model[]"></td>
<td><input type="text" name="sellingPrice[]"></td>
</tr>
</tbody>
</table>
</div>
<div class="eventButtons">
<input type="submit" name="submit" id="submit" value="Save">
<input type="reset" name="reset" id="reset" value="Clear" class="btn">
</div>
</form>
You are inserting data outside the for loop so it inserts only the last row or data.. What you have to do is to place insert query within foreach or for loop
if(isset($_POST['submit'])){
$row_data = array();
for($i = 0 ; $i < count($_POST['category']);$i++){
$category = mysql_real_escape_string($_POST[$i]['category']);
$itemName = mysql_real_escape_string($_POST[$i]['itemName']);
$brand = mysql_real_escape_string($_POST[$i]['brand']);
$model = mysql_real_escape_string($_POST[$i]['model']);
$sellingPrice = mysql_real_escape_string($_POST[$i]['sellingPrice']);
$insert_query = mysql_query("INSERT INTO sale(Category,ItemName,Brand,Model,SellingPrice) VALUES ('$category','$itemName','$brand','$model','$sellingPrice')");
if(!$insert_query){
echo "Error: " . mysql_error();
}else{
echo "Data Saved Successfully";
}
}
}
As I dont have enough reputation I am adding my comment as answer.
Your code is fine. It should work. There might be problem while you are cloning the row, may be it is not getting added under the form tag. You can verify it by dumping the $row_data variable.
Please share your javascript code which makes clone of the row, it will help us to solve your problem.
You need to run your query in for loop by counting the array value using count($_POST['category'])
if(isset($_POST['submit'])){
$row_data = array();
for($i= 0; $i <count($_POST['category']);$i++){
$category = mysql_real_escape_string($_POST[$i]['category']);
$itemName = mysql_real_escape_string($_POST[$i]['itemName']);
$brand = mysql_real_escape_string($_POST[$i]['brand']);
$model = mysql_real_escape_string($_POST[$i]['model']);
$sellingPrice = mysql_real_escape_string($_POST[$i]['sellingPrice']);
$insert_query = mysql_query("INSERT INTO sale(Category,ItemName,Brand,Model,SellingPrice) VALUES ('$category','$itemName','$brand','$model','$sellingPrice')");
if(!$insert_query){
echo "Error: " . mysql_error();
}else{
echo "Data Saved Successfully";
}
}
}

Unable to insert multiple data into MYSQL database

I am unable to insert the data entered in the text box into MYSQL database. I am trying to insert inputs from multiple textboxes into the database.
<?php
include('questionDB.php');
if(isset($_POST['submit'])){
$questionID = $_POST['id'];
$answer = mysql_real_escape_string(htmlspecialchars($_POST['answer']));
mysql_query("INSERT INTO answers(question_id, answer_body) VALUES ($questionID, $answer)");
}
?>
<form name="auctionQuestion" method="post">
<?php
$auctionSurvey = "SELECT question_id, survey_id, question_body FROM questions
WHERE survey_id='1'";
$aucResult = mysql_query($auctionSurvey) or die (mysql_error());
while($auctionRow = mysql_fetch_assoc($aucResult)){
echo $auctionRow['question_body']. "<input type=\"text\" name=\"answer\"><BR>";
?>
<input type="hidden" name="id" value="<?php echo $auctionRow['question_id'] ?>">
<?php
}
?>
<input type="submit" name="submit" value="Submit">
</form>
Use either:
VALUES ('$questionID', '$answer')
or:
VALUES ('" . $questionID . "', '" . $answer . "')
instead of VALUES ($questionID, $answer)
First thing to do is to generate the correct HTML, so that you will get back arrays of variables.
I think it will be something like this
echo $auctionRow['question_body'] . "<input type=\"text\" name=\"answer[]\"><BR>";
Similar for the other fields.
Then, when you get the post in, use print_r($_POST) to see exactly what you have got. Go from there.

How to read/send post data with php and hold a variable in it

I have this code in a loop in my code, The loop makes one submit button for every member found. I need each button to have the members name stored in it, in a way it can be sent though post when that button is clicked. Im not sure if this is possible with post but i was trying a way i do it with URLS. Does anyone know how to do this?
<input type="submit" value="Attack" name="Attack?name=<?php echo $Member_name; ?>" />
<?php
if(isset($_POST['Attack'])){
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_GET['name'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
}
Here is the whole code i was trying to store it in a hidden form but it only grabs the last member found and wont get others.
<?php
$sql = "SELECT name, rank FROM users ORDER BY rank DESC"; // Searches the database for every one who has being last active in the last 5 minute
$query = mysql_query($sql) or die(mysql_error());
$count = mysql_num_rows($query);
$i = 1;
while($row = mysql_fetch_object($query)) {
$Member_name = htmlspecialchars($row->name);
$Member_level = htmlspecialchars($row->rank);
?>
<td><?php echo $i; ?></td>
<td><?php echo $Member_name; ?></td><td><?php echo $Member_level; ?></td><td>
<input type="hidden" name="thename" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
</td>
<?
if($i != $count) { // this counts the amount of people that are online and display the results.
echo "</tr><tr>";
}
$i++;
}
?>
<?php
if(isset($_POST['Attack'])){
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_POST['thename'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$profile_id = htmlspecialchars($row->id);
$profile_userip = htmlspecialchars($row->userip);
$profile_name = htmlspecialchars($row->name);
$profile_money = htmlspecialchars($row->money);
$profile_gang = htmlspecialchars($row->gang);
$profile_exp = htmlspecialchars($row->exp);
$profile_profile = htmlspecialchars($row->profile);
$profile_rank = htmlspecialchars($row->rank);
$profile_health = htmlspecialchars($row->health);
$profile_defence = htmlspecialchars($row->defence);
$profile_stanima = htmlspecialchars($row->stanima);
?>
OK, assuming everything else is working ok, and you are retrieving data.
Change this:
<input type="hidden" name="thename" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
To this:
<form method="POST" action="">
<input type="hidden" name="name" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
</form>
And also in your PHP, change this line:
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_GET['name'])."'";
To:
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_POST ['name'])."'";
This isn't the best way to do this, you will be generating loads of HTML elements depending how many users you have, but it should solve you problem (providing everything else is working and receiving data).
HTML 5 & Javascript would be perfect for this and is something you should look into.

Categories