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

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.

Related

How to get all passed parameters from POST and then insert them in db

I have a php file and a sample form which is quite big ( around 60 fields and all optional )
Now What i want to do is get whatever parameters were passed and insert them to the table. I created a sample for 15 fields, but i can't go on and keep doing this for 60 items.
$a1 = $_REQUEST['a1'];
$a2= $_REQUEST['a2'];
$a3= $_REQUEST['a3'];
$a4= $_REQUEST['a4'];
$a5= $_REQUEST['a5'];
$a6= $_REQUEST['a6'];
$a7= $_REQUEST['a7'];
$a8= $_REQUEST['a8'];
$a9= $_REQUEST['a9'];
$a10= $_REQUEST['a10'];
$a11 = $_REQUEST['a11'];
$a12 = $_REQUEST['a12'];
$a13 = $_REQUEST['a13'];
$a14 = $_REQUEST['a14'];
$id = $_REQUEST['id'];
include 'conn.php';
$sql = "insert into med_history (a1 ,a2 ,a3 ,a4 ,a5 ,a6 ,a7 ,a8 ,a9 ,a10 ,a11 ,a12 ,a13,a14,id) values(
'$a1','$a2','$a3','$a4','$a5','$a6','$a7','$a8','$a9','$a10','$a11','$a12','$a13','$a14','$id')";
#mysql_query($sql);
echo "Inserted successfully";
Also with this one the problem is error is recieved if some parameter is not passed. So, how to fix it.
I am not using PDO or mysqli because this is done on testing server and not on actual server. When i migrate to the production server i will make the PDO connection
I hope this piece of code would help you:
$a = array();
foreach ( $_REQUEST AS $key => $value ) {
# !!! make some tests on key and value ... e.g.
if ( preg_match("/^a\d+$/", $key) ) {
$a[] = ' `'.$key.'` = "'.mysql_real_escape_string($value).'"';
}
}
if ( count($a) ) {
$sql = "insert into med_history SET ".implode(', ', $a);
mysql_query($sql) or exit(mysql_error());
echo "Inserted successfully";
}
simple solution
<?php
$first_string="";
$second_string="";
if(isset($_REQUEST['a1']))
{
$first_string.=",a1";
$second_string.=",$a1"
}
//do this to all values and after u finish u need delete the first (,) from first and second string
$first_string=substr($first_string,1);
$second_string=substr($second_string,1);
include 'conn.php';
$sql="insert into med_history(".$first_string.",$id)values(".$second_string.",id)";
#mysql_query($sql);
echo "Inserted successfully";
?>
u can use your skills as a programmer to make the code good and small using for loops,for each ..etc , but this is the general idea to help you with the (not passed parameters error) i hope this is what you looking for

php mysql issue with check if record exist before insert

I'm having a little problem with the codes given below. When I'm using the name="staff_number[]" then it insert the record with everything ok even if it is already in the database table and when i use name="staff_number" it does check the record and also give me alert box but when insert the record if it is not in the database it stores only the first number of the staff number like the staff no is 12345 it stores only 1. can anyone help in this record i think there is only a minor issue what I'm not able to sort out.
PHP Code:
<select placeholder='Select' style="width:912px;" name="staff_number[]" multiple />
<?php
$query="SELECT * FROM staff";
$resulti=mysql_query($query);
while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['staff_no']?>"><?php echo $row['staff_name']?></option>
<?php } ?>
</select>
Mysql Code:
$prtCheck = $_POST['staff_number'];
$resultsa = mysql_query("SELECT * FROM staff where staff_no ='$prtCheck' ");
$num_rows = mysql_num_rows($resultsa);
if ($num_rows > 0) {
echo "<script>alert('Staff No $prtCheck Has Already Been Declared As CDP');</script>";
$msg=urlencode("Selected Staff ".$_POST['st_nona']." Already Been Declared As CDP");
echo'<script>location.href = "cdp_staff.php?msg='.$msg.'";</script>';
}
Insert Query
$st_nonas = $_POST['st_nona'];
$t_result = $_POST['st_date'];
$p_result = $_POST['remarks'];
$arrayResult = explode(',', $t_result[0]);
$prrayResult = explode(',', $p_result[0]); $arrayStnona = $st_nonas;
$countStnona = count($arrayStnona);
for ($i = 0; $i < $countStnona; $i++) {
$_stnona = $arrayStnona[$i];
$_result = $arrayResult[$i];
$_presult = $prrayResult[$i];
mysql_query("INSERT INTO staff(st_no,date,remarks)
VALUES ('".$_stnona."', '".$_result."', '".$_presult."')");
$msg=urlencode("CDP Staff Has Been Added Successfully");
echo'<script>location.href = "cdp_staff.php?msg='.$msg.'";</script>';
}
Your $_POST['staff_number'] is actually an array.
So you have to access it like $_POST['staff_number'][0] here, 0 is a index number.
If the name of select is staff_number[] then $prtCheck will be a array so your check query must be in a loop to make sure your check condition.
if the name is staff_number then the below code is fine.
The answer of amit is right but I will complete it.
Your HTML form give to your PHP an array due to the use of staff_number[] with [] that it seems legit with the "multiple" attribute.
So you have to loop on the given values, you do it with a for and a lot of useless variables without really checking it. From a long time, we have the FOREACH loop structure.
I could help you more if i know what is the 'st_nona', st_date' and 'remarks' values.
According to your question you are getting difficulty in storing the data. This question is related to $_POST array.
Like your question we have selected following ids from the select : 1,2,3,4
It is only storing 1.
This is due to you have not used the loop when inserting the data.
Like below:
<?php
foreach($_POST['staffnumber'] as $staffnumber){
$query=mysql_query("select * from staff where staff_number =".$staffnumber);
if(mysql_num_rows($query)>0){
//action you want to perform
}else{
//action you want to perform like entering records etc. as your wish
}
}
?>
And I would like to suggest you that use the unique keys in database for field and use PHP PDO for database, as it is secure and best for OOPs.
Let me know if you have any queries.

Insert statement for variables that will always be different

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
}

Inserting form values with spaces into mysql 4.1

I'm trying to insert form data into a MySQL 4.1 DB. The problem I'm having is form fields that include spaces get truncated before insertion. The POST variables are complete, spaces and all. Just being cut off somewhere. For instance, "South Lake Tahoe" is inserted simply as "South". Zip codes and telephone numbers with dashes are also fine. The site I'm working on is hosted by Yahoo Small Business, and they're still using MySQL 4.1. I don't know if that is the problem, but I do know I never had issues doing this with MySQL 5+. The user fills out a form to add a new member. Upon Submit, the form data is POSTED to another page for processing:
$k = array();
$v = array();
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$result = mysql_query("SELECT * FROM members WHERE first_name='$first_name' AND last_name='$last_name'");
if(mysql_num_rows($result)>0){
mysql_free_result($result);
exit("Duplicate User in Database");
}
mysql_free_result($result);
array_pop($_POST);//Don't need the Submit value
foreach($_POST as $key=>$value){
array_push($k, "$key");
array_push($v, "$value");
}
$fields = implode(", ", $k);
$values = array();
foreach($v as $key=>$value){
array_push($values, '"'.$value.'"');
}
$values_string = implode(", ", $values);
$result = mysql_query("INSERT INTO members($fields) VALUES($values_string)");
I'm sure there are better ways of doing this, but I'm still on the way up the learning curve. Please point out any obvious flaws in my thinking.
Any suggestions are greatly appreciated.
EDIT: The field types in MySQL are correct and long enough. For example, the field for City is set as VARCHAR(30).
Thanks much,
Mark
This code is horrifically insecure - you're taking user-supplied values and plopping them directly into your SQL statements without any sanitization. You should call http://php.net/manual/en/function.mysql-real-escape-string.php on anything you insert into a query this way (parameterized queries with PDO are even better).
You also make some assumptions, such as $_POST always being ordered a certain way (is that guaranteed?) and that you have exactly as many elements in your form as you have fields in your table, and that they're named identically. The code as it's written is the kind of thing a lot of beginning programmers do - it feels efficient, right? But in the end it's a bad idea. Just be explicit and list out the fields - e.g.
$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
$sql = "insert into mytable (field1, field2) values ('" . mysql_real_escape_string($field1) . "', '" . mysql_real_escape_string(field2) . "')";
mysql_query($sql);
I haven't touched on why stuff would cut off at the first space, as this would imply that your code as you have it presented is salvageable. It's not. I get the feeling that reworking it as I described above might make that problem go away.
<?php
// Remember to always escape user input before you use them in queries.
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$result = mysql_query("SELECT * FROM members WHERE first_name='$first_name' AND last_name='$last_name'");
if (mysql_num_rows($result) > 0) {
mysql_free_result($result);
exit("Duplicate User in Database");
}
mysql_free_result($result);
// I removed your loop around $_POST as it was a security risk,
// and could also become non-working. (What would happen if the order
// of the $_POST keys were changed?)
// Also the code become clearer this way.
$result = mysql_query("INSERT INTO members(first_name, last_name) VALUES('$first_name', '$last_name')");

Unfilled form values creating empty rows in mysql via php

First time poster, long time lurker :)
I have a form setup that posts data for multiple rows in a single table with seven colums to a php function to insert it as new records in a database. The form is working great, however, if one of the rows in the form is left unfilled then the php function is creating a blank row in the database. I am attempting to figure out how to avoid this. I am certain it has nothing to do with the form itself, and rather has to do with the php. Please have a look at it. I'm totally open to suggestions.
<?php
require("header.php");
require("dbinc.php");
foreach($_POST['card'] as $row=>$cardcounted)
{
$model=$_POST['model'];
$serial=$_POST['serial'][$row];
$card=$cardcounted;
$status=$_POST['status'];
$date=$_POST['date'];
$location=$_POST['location'];
$query = mysql_query("INSERT INTO receivers (`id`, `model`, `serial`, `card`, `status`, `date`, `location`) VALUES ('null','$model','$serial','$card','$status','$date','$location')");
if(!isset($serial[$row]) || $serial[$row] == '') {
// error message here, redisplay form if desired
} else {
// no errors - process data
}
if (!$query)
{
die('Error: ' . mysql_error());
}
}
echo $row+1 . " record(s) added";
mysql_close()
?>
I added in the !isset on the serial numbers by row to check for null posts but am unsure as to how to incorporate that properly. i think im on the right track, just need that little push :)
First choice is to use JavaScript validation to find out invalid form submits, Some users may disable JavaScript, so its always recommended to do server-side validations
So write a method like
isValid($postArray) {
foreach($postArray as $key => $value) {
if ($value == "") {
return false;
}
}
return true;
}
If form field names and db column names are similar you can use
$sql = "INSERT INTO receivers ";
$keys = "(";
$values = "(";
foreach($postArray as $key => $value) {
if ($value != "") {
$keys += $key;
$values += $value;
}
}
$sql = $sql + $keys +" VALUES "+ $values;
Maybe try moving your mysql query into your else currently you insert values into the database regardless of whether you have form errors or not. Also you will need to secure anything that you are inserting into your database. Its an SQL injection field trip right now ;)

Categories