Insert statement for variables that will always be different - php

I have a page that is putting random test questions on the page. The database has a bank of over 200 questions. The questions are grabbed randomly for a 20 question test. Upon submit, I need to insert a record for each question with the question number, user ID and answer provided. I have this working fine previously but as the question bank has grown and the need to change up the test grows, I spend far too much time changing hard coded variables and insert statements on the script that processes the test and inserts the results to the database.
$fname=$_POST['EmployeeFirstM'];
$lname=$_POST['EmployeeLast'];
$ruser=$_POST['User'];
$1=$_POST['q1'];
$2=$_POST['q2'];
$3=$_POST['q3'];
With the variables on up to 200+. What comes from the previous page could be any mix of 20 questions. I need to do:
$sql="INSERT INTO $tbl_name(empID, empf, empl, QuestionNumber, AnswerGiven)VALUES('$ruser','$fname', '$lname','1', '$1')";
20 times with whatever mix of questions come across. Am I going to have to hard code in 200+ insert statements for every question possible and just have it skip over the insert statements that aren't in the mix for each submission? The prior version of the test recorded to one line item but I had to keep adding columns to the table to accept more questions. I don't think that's efficient. Please and thanks.
After much trial and error this works for recording the question IDs into the database tables. I still can't figure out how to get the corresponding selected radio button input into the mix to record the answer.
foreach( $_POST as $q_id ) {
if( is_array( $q_id ) ) {
foreach( $q_id as $qid ){
$sql="INSERT INTO $tbl_name(empID, empf, empl, QuestionNumber, AnswerGiven)VALUES('$ruser','$fname', '$lname','$qid', '$q')";
$result=mysql_query($sql);
}
}
}

You certainly shouldn't have to hard-code values for every record in your database. The kind of defeats one of the reasons for having a database in the first place, separating the data from the logic.
Why do you have 200+ variables? When you're rendering the page with the questions, I imagine you would randomly select 20 questions from the database, right? And each of those questions would have some sort of unique ID, yes? So the structure for rendering the questions to the page might be something like:
<input type="hidden" name="qid[]" value="<?php echo $id ?>" />
<?php echo $question ?>
<input type="text" name="answer[]" />
This would be in a loop of some sort, where $id and $question are the values changing in each iteration of the loop for the 20 questions selected from the database.
Then when the form is posted with the answers, you have your question IDs here:
$_POST["qid"][]
and your answers here:
$_POST["answer"][]
As arrays. Add in some error checking to ensure both arrays have 20 values and you can loop from 0-19 to insert them into the database:
for ($i = 0; $i < 20; $i++) {
// $_POST["qid"][$i] is the ID of the question being answered
// $_POST["answer"][$i] is the answer given
// Sanitize the inputs and insert into the database accordingly
}

Put your values in an array, then just loop through it so you can insert them in a loop.
$answerGiven[];// have all your answers here
$questionNumber[]; // have all your questions in here
foreach ($questionNumber as $key=>$value){
$sql="INSERT INTO $tbl_name(empID, empf, empl, QuestionNumber, AnswerGiven)VALUES('$ruser','$fname', '$lname','$questionNumber[$key]', '$answerGiven[$key]')";
// execute
}
If you are looking for a more efficient way of doing it, use prepared statements... this will also prevent SQL Injection
$sql="INSERT INTO $tbl_name(empID, empt, empl, QuestionNumber, AnswerGiven)VALUES(?,?,?,?,?)";
if($stmt = $mysqli->prepare($sql)){
foreach ($questionNumber as $key=>$value){
$stmt->bind_param('sssis',$ruser, $fname, $lname, $questionNumber[$key], $answerGiven[$key]);
$stmt->execute();
}
$stmt->close();
}else die("Failed to prepare query");

Use name="q[]" in the input elements that are repeated. Then PHP will create an array named $_POST['q'] and you can process them in a loop.
foreach ($_POST['q'] as $i => $q) {
$sql="INSERT INTO $tbl_name(empID, empf, empl, QuestionNumber, AnswerGiven)VALUES('$ruser','$fname', '$lname', $i, '$q')";
// submit query
}

Related

Can't INSERT $_POST ARRAY to MySQL - JQuery DataTables Checkboxes by Gyrocode

I am aware that there have been a lot of questions on $_POST ARRAY and MySQL, and I've been through a lot of them. However, none of the ones I have looked at do the trick for me.
I am trying to pass the row id's from a JQuery DataTable (using Gyrocode's ckeckboes plugin), form submit.
If I use:-
$i = 0;
foreach($_POST['id'] as $value){
echo "value : ".$value. '<br/>';
$i++;
}
I get output of
value: 1
value: 25
value: 32
value: 5
value: 17
Which is what I would expect (the amount of lines and the number values depend on how many checkboes I check).
But when I put the query in, it won't save to the database:-
$i = 0;
foreach($_POST['id'] as $value){
$sql = "INSERT INTO attendance (rider_id, at_date) VALUES ('$value', NOW())";
$i++;
}
I have tried all kinds of variations of this but nothing I do seems to work and it seems like a dumb mistake I'm making :)
Thanks
Thanks for the comments. The js and HTML are the samples taken from Gyrocode. I know it's open to SQL injection attacks, but this is not for an open network, just something I am playing with.
I managed to get it working with the following PHP
session_start();
include_once('connection.php');
$rider_id = isset($_POST['id']) ? $_POST['id'] : [];
foreach($rider_id as $k=>$id) {
$query = "INSERT INTO attendance (rider_id, at_date) VALUES ('{$id}', NOW())";
$conn->query($query);
}
header('location: index.php');
Just need to add some error handling.

PHP Store unknown array length into database

So I have a form that lets people add a list of grades, and using jQuery they are able to add up to 9 extra fields. (Meaning they can submit any number from 1 to 10 grades). What I want to know is how I can go about storing this in my database, as I do not want to convert them all into one string. My concern is that because I don't know how many grades the user is going to enter, I can't set a definitive array number to store (or can I?)
Sorry if this is not terribly well explained, I'm still relatively new to PHP and SQL!
A quick assumption if I am not mistaken would be: saving one user with multiple grades for multiple subjects can be achieved like this.
Firstly we get one user id from the form and put it in PHP:
$id = isset($_POST['id'])? $_POST['id']:'';
Then get multiple grades and subjects which would be sent as comma separated values:
//$id= explode(',',$_POST['id']);// For multiple users
$grade= explode(',',$_POST['grade']);
$subj= explode(',',$_POST['subject']);
$entry= explode(',',$_POST['entry']);
Now count the number of grades: $count= count($grade);
Use the count in a for loop to have insert in loop:
for ($i = 0; $i < $count; $i++) {
try {
$dbh->beginTransaction(); //$dbh is your PDO connection
$insertQ = "INSERT INTO `grades` (id, grade, subject, entry)
VALUES('$id', '$grade[$i]', '$subj[$i]','$entry[$i])";
$dbh->query($insertQ);
$dbh->commit();
} catch (Exception $e) {
$error = $e->getMessage();
}
}
Hope this may help.

Seemingly identical sql queries in php, but one inserts an extra row

I generate the below query in two ways, but use the same function to insert into the database:
INSERT INTO person VALUES('','john', 'smith','new york', 'NY', '123456');
The below method results in CORRECT inserts, with no extra blank row in the sql database
foreach($_POST as $item)
$statement .= "'$item', ";
$size = count($statement);
$statement = substr($statement, 0, $size-3);
$statement .= ");";
The code below should be generating an identical query to the one above (they echo identically), but when I use it, an extra blank row (with an id) is inserted into the database, after the correct row with data. so two rows are inserted each time.
$mytest = "INSERT INTO person VALUES('','$_POST[name]', '$_POST[address]','$_POST[city]', '$_POST[state]', '$_POST[zip]');";
Because I need to run validations on posted items from the form, and need to do some manipulations before storing it into the database, I need to be able to use the second query method.
I can't understand how the two could be different. I'm using the exact same functions to connect and insert into the database, so the problem can't be there.
below is my insert function for reference:
function do_insertion($query) {
$db = get_db_connection();
if(!($result = mysqli_query($db, $query))) {
#die('SQL ERROR: '. mysqli_error($db));
write_error_page(mysqli_error($db));
} #end if
}
Thank you for any insite/help on this.
Using your $_POST directly in your query is opening you up to a lot of bad things, it's just bad practice. You should at least do something to clean your data before going to your database.
The $_POST variable often times can contain additional values depending on the browser, form submit. Have you tried doing a null/empty check in your foreach?
!~ Pseudo Code DO NOT USE IN PRODUCTION ~!
foreach($_POST as $item)
{
if(isset($item) && $item != "")
{
$statement .= "'$item', ";
$size = count($statement);
$statement = substr($statement, 0, $size-3);
$statement .= ");";
}
}
Please read #tadman's comment about using bind_param and protecting yourself against SQL injection. For the sake of answering your question it's likely your $_POST contains empty data that is being put into your query and resulting in the added row.
as #yycdev stated, you are in risk of SQL injection. Start by reading this and rewrite your code by proper use of protecting your database. SQL injection is not fun and will produce many bugs.

PHP MYSQL Check & Append Function

I hope someone can help. Basically I'm fairly OK with PHP and MySQL,
however, I need some advice on how to complete this task.
As my system is to complex to explain, I've condensed it down so it's clearer.
Basically, I have an simple PHP Form that asks the user for their:
Name,Item Ordered, Item Quantity. The OrderID is autogenerated and is a random
4 number. So at the moment I do it with this:
$sql="INSERT INTO system_orders
(orderid,name,itemordered,itemquantity) VALUES
('$randomgeneratednumber', '$_POST[name]','$_POST[itemordered]','$_POST[itemquantity]')"; and
run $sql
Now what I want is if they put the quantity as "2", I want it to create an additional row and append
the randomgeneratednumber. For example, if the randomgeneratednumber was 9876 and the quantity was 2, it would create an additional new row, with the $randomgeneratednumber-2, in this example 9876-2
Would anyone know how to achieve this?
I have temporarily used an if statement (which I know is really bad programming practice)
to append the -2 manually, but there must be a function out there to detect if $quantity = 2
then create additional row with the appended -2 and so on for 3,4,5,6,7,8...
Use a loop:
if ($quantity > 1) {
for ($q = 2; $q <= $quantity; $q++) {
$sql = "INSERT INTO system_orders
(orderid,name,itemordered,itemquantity) VALUES
('$randomgeneratednumber-$q', '$_POST[name]', '$_POST[itemordered]', '$_POST[itemquantity]')";
// run $sql
}
}
You also should switch to a database API that supports parametrized queries, or escape the user-supplied inputs.
$sql="INSERT INTO system_orders
(orderid,name,itemordered,itemquantity) VALUES
('$randomgeneratednumber', '$_POST[name]','$_POST[itemordered]','$_POST[itemquantity]')"; and
run $sql
if ($_POST['itemquantity']>1) {
$multipleorderid = $randomgeneratednumber."-".$POST['itemquantity'];
$sql="INSERT INTO system_orders
(orderid,name,itemordered,itemquantity) VALUES
('$multipleorderid', '$_POST[name]','$_POST[itemordered]','$_POST[itemquantity]')"; and
run $sql
}

Mysql query within for loop not inserting all values

I have the following for loops, which should insert values into a mysql table. There is a users array and it is looping over the array and calculation statistics, and it should be inserting all the values into the mysql table, but it only inserts the operation done on the first element of the users array and not the rest. It is ignoring the first for loop, and only inserts for the second for loop, even though, I can see that the loops are doing what they are supposed to do, it is just not being inserted into mysql.
for($i=0; $i<count($users); $i++)
{
for($j=$i+1; $j<count($users); $j++)
{
$user1=$users[$i];
$user2=$users[$j];
$dat1=getData($user1);
$dat2=getData($user2);
$union=count(array_unique(array_merge($dat1, $dat2)));
$intersect=count(array_intersect($dat1, $dat2));
$rate=$intersect/$union;
$sql = "INSERT IGNORE into dat_net VALUES ($user1,$user2,$union,$intersect,$rate)";
$sqlresults = mysql_query($sql);
echo " ".$user1." ".$user2." \n";
if ($sqlresults === false) {
// An error has occured...
echo mysql_error();
}
}
}
Solved due to tips in the comments: I had inadvertently set up keys for the columns, so it wasn't inserting due to duplication.
First of all insert all data using one query. Generate it in for loop and call mysql query once.
You can check if your generated query works simply by echo it before execute and try to run it using some sql client.
try this,
$sql = "INSERT IGNORE into dat_net VALUES ('{$user1}','{$user2}','{$union}','{$intersect}','{$rate}')";
But it will be good if you create a insert query in foreach loop and then fire it once after completing foreach loop.

Categories