I have a form that allows for the duplication of fields. The form is posted via php and inserted into a database. My problem is I cannot seem to loop through the array correctly. Am I setting up the form correctly (are the name's formatted correctly) and am I looping through the arrays correctly? I am not successful in getting any data inserted.
The trick is that the duplicated fields need to stick together.
Think of the fields as sets of questions and answers.
Each question has a title, the question text and a file input.
Each answer has a title, the answer text a file input, and a check box to note the correct answer.
I have the name's set up like so:
name='question[1][title]'
name='question[1][text]'
name='question[1][file]'
answer[1][title][]
answer[1][text][]
answer[1][file][]
answer[1][correct][]
The php to insert the form is as follows:
$insert_question = $db->prepare(
'insert into questions (title, text) values (?, ?)');
$insert_answer = $db->prepare(
'insert into answers (question_id, title, text, correct)'.
' values (?, ?, ?, ?)');
foreach ($_POST['question'] as $q_num => $q)
{
$insert_question->execute(array($q['title'], $q['text']));
$q_id = $db->lastInsertId();
//********************
// insert files
//********************
foreach ($_POST['answer'][$q_num] as $a)
{
$insert_answer->execute(
array($q_id, $a['title'], $a['text'], $a['correct']));
}
}
Sorry that this is such a huge question. I have been working on this for two days now and have run out of ideas.
I'm not sure I understood your problem (I don't speak english fluently).
But here you need an other loop instead of this one:
foreach ($_POST['answer'][$q_num] as $a)
{
$insert_answer->execute(
array($q_id, $a['title'], $a['text'], $a['correct']));
}
like :
$lim = count($_POST['answer'][$q_num]['title']);
for($i=0;$i<$lim;++$i){
$insert_answer->execute(
array($q_id, $_POST['answer'][$q_num]['title'][$i], $_POST['answer'][$q_num]['text'][$i], $_POST['answer'][$q_num]['correct'][$i]));
}
It didn't test anything and it should work only if you always get title, text and correct in an answer.
The issue is with the second loop (answer array). Try this
<?php
foreach ($_POST['answer'][$q_num]['title'] as $a => $value)
{
$insert_answer->execute(
array($q_id, $_POST['answer'][$q_num]['title'][$a], $_POST['answer'][$q_num]['text'][$a], $_POST['answer'][$q_num]['correct'][$a]));
}
?>
Related
I have an input form with two values as a key, constructed this way:
<input name="verificarPago['.$x['pagoID'].'-'.$x['userID'].']" type="text">
So, the HTML would look like, for example, like this:
<input name="verificarPago[4-10]" type="text">
Besides that I have the value that the user can type, for example "Juan".
The inputs are created programmatically, and I want to save them each three values (in the example: 4, 10, Juan) into a database.
So, when the user submits the form, I thought on using foreach in order to access the elements in that array, but my problem is: How may I explode the keys to access the two values separately?
I've tried this (I'm not taking into account security now, I'm trying to prove the concept):
$verificar = $_POST['verificarPago'];
foreach ($verificar as $pago => $curso) {
//I'm pretty much stuck here.
$verificar= array_flip(explode("-", $verificar));
//I want to insert the three items into the database
$verificarPago = "INSERT pagosVerificados SET userID = '$usuario', pagoID = '$pago', cursoID = '$curso'";
$cargarPago = mysqli_query($conectar, $verificarPago);
}
I've tried adding to the form another input type, so the values wouldn't be together, but that way I should do a foreach inside a foreach and that renders duplicated results (and with errors as well).
Without addressing any architectural issues, adding error-checking, or addressing security problems, here's how to do what you're asking for
$verificar = $_POST['verificarPago'];
foreach ($verificar as $ids => $text) {
list($pagoID, $cursoID) = explode("-", $ids);
$sql = "INSERT INTO pagosVerificados (userID, pagoID, cursoID, someVarcharField)
VALUES ($usuario, $pagoID, $cursoID, '$text');";
$cargarPago = mysqli_query($conectar, $sql);
}
This is a tad inefficient though - executing an insert for every iteration. Since mysql supports bulk inserts, you can modify the generation of the query to leverage that.
$verificar = $_POST['verificarPago'];
$rows = array();
foreach ($verificar as $ids => $text) {
list($pagoID, $cursoID) = explode("-", $ids);
$rows[] = "($usuario, $pagoID, $cursoID, '$text')";
}
$sql = "INSERT INTO pagosVerificados (userID, pagoID, cursoID, someVarcharField) VALUES "
. implode(',', $rows)
. ";";
$cargarPago = mysqli_query($conectar, $sql);
Now it's just one round-trip to the database
This is a bizarre way of passing values over POST. But, to expand on Peter's answer and address the glaring security issues, you can also use prepared statements. They're designed to be prepared once and then executed multiple times so are perfect for the job.
$verificar = $_POST['verificarPago'];
$sql = "INSERT INTO pagosVerificados (userID, pagoID, cursoID, someVarcharField) VALUES (?, ?, ?, ?)"
$stmt = $conectar->prepare($sql);
foreach ($verificar as $ids => $text) {
list($pagoID, $cursoID) = explode("-", $ids);
$stmt->bindParam("iiis", $usuario, $pagoID, $cursoID, $text);
$stmt->execute();
}
It's been years since I've worked with mysqli, but this should do the trick. You'll want to include some error checking in there as well.
Thank you in advance for any help given! I'm very new to PHP and would love some advice/help! i want many id fields separated by comma to be inputted into a database separately with the same resource id variable.
Find a link to a picture here! Here, a user enters many ids for the name, and only one ID for the resource, I would like all ids to be entered into the database with the same resource id beside it
//so this is creating the array to split up the ids
$array = explode(",", $id);
//finding length of array
$length = count($array);
//now we want to loop through this array, and pass in each variable to the db
for ($x = 0; $x < $length; $x++) {
$sqlinsert= "INSERT INTO ids_to_resources (id, resource_id)
VALUES ($id [$x], $resource_id)"
$result = mysqli_query($dbcon,$sqlinsert);
}
I think it could be something like this code above but it doesnt seem to be working for me...
In short i want a user to enter many ID fields and only one resource field, and for this to be inputed into the database separately. I hope this makes sense!
Thanks again for any help given!
To only answer your question and not questioning your database schema. Have a look at the following code:
$ids = explode(",", $id);
$inserts = array();
foreach ($ids as $id) {
$inserts[] = "($id,$resource_id)";
}
$query = "INSERT INTO ids_to_resources (id,resource_id) VALUES " . implode(',', $inserts) . ";";
You can insert multiple rows in one sql query by seperating them with a comma. The code should generate a query like this:
INSERT INTO ids_to_resources (id,resource_id) VALUES (1,4),(2,4),(3,4);
You would be better off creating a separate table which has a new row for each record... the columns would be ID, NINJA_ID, RESOURCE_ID. Then insert it that way. Put an Index on RESOURCE_ID. This way you can easily search through the database for specific records, updating and deleting would be a lot easier as well.
But if you insist on doing commas,
$comma_ids = implode("," $array);
You don't have semicolon after this line and you musnt't have a space between $id and [$x]
$sqlinsert= "INSERT INTO ids_to_resources (id, resource_id)
VALUES ($id[$x], $resource_id)";
for example i have an array of images of a specific location lets say of new york...which i want to store in mysql... these images are coming directly from wikipedia...how can i insert these images in a loop with each image entry would get the same location name?..like this
1|Newyork|img1.jpg
2|Newyork|img2.jpg
3|Newyork|img3.jpg...so on...
what i have done so far is..
foreach($images as $record)//'$images' is the array of images..
{
$sql="INSERT INTO `search`(`id`, `name`, `image`) VALUES ('','".$data"','".$record."',} //$data is the name of location
if I understood well, even if I don't see your array, sth like that would be the query loop:
//if id is a primary key autoincrement
foreach ($images as $data => $record){
$dbh->query("INSERT INTO search (name, image) VALUES ('".$data."','".$record."') ");
}
but most possibly the array is of that form
for($i=0; $i<count($images); $i++){
$dbh->query("INSERT INTO search (name, image) VALUES ('".$images[$i]['data']."','".$images[$i]['record']."') ");
}
It depends of the array form.
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
}
I am trying to get the data to insert into the specified database but it just wont. Ive looked at the manual tried examples and all of that but I cant get the data to pass through to the database I can however echo/print_r/var_dump it so I know I have data. Here is my code:
public function insertJson($url, $subId)
{
$json_file = file_get_contents(KHAN_BASE.$url.'/videos');
if(isset($json_file))
{
$json_decoded = json_decode($json_file, true);
}else{
$this->error = 'A valid JSON file was not specified';
}
// var_dump($json_decoded); <--- This return all of the data needed from the json pull so i know I have data
//m3u8, mp4, png,
//". $row['m3u8'] .",". $row['mp4'] .",". $row['png'] .",
foreach($json_decoded as $row)
{
//echo $row['backup_timestamp'].'<br/>'; <--- This outputs the correct information so I know I can access it that way
$sql = "INSERT INTO tbl_khan_videos (sub_subject_id, backup_timestamp, date_added, description,
duration, extra_properties, has_questions, ka_url, keywords, kind, position, readable_id, relative_url, title, url, views,
youtube_id) VALUES (:subid, :backup_timestamp, :date_added, :description, :duration, :extra_properties, :has_questions, :ka_url, :keywords, :kind, :position,
:readable_id, :relative_url, :title, :url, :views, :youtube_id)";
$stmt = $this->db->prepare($sql);
$stmt->bindValue(":subid", $subId);
$stmt->bindValue(":backup_timestamp", $row['backup_timestamp']);
$stmt->bindValue(":date_added", $row['date_added']);
$stmt->bindValue(":description", $row['description']);
$stmt->bindValue(":duration", $row['duration']);
$stmt->bindValue(":extra_properties", $row['extra_properties']);
$stmt->bindValue(":has_questions", $row['has_questions']);
$stmt->bindValue(":ka_url", $row['ka_url']);
$stmt->bindValue(":keywords", $row['keywords']);
$stmt->bindValue(":kind", $row['kind']);
$stmt->bindValue(":position", $row['position']);
$stmt->bindValue(":readable_id", $row['readable_id']);
$stmt->bindValue(":relative_url", $row['relative_url']);
$stmt->bindValue(":title", $row['title']);
$stmt->bindValue(":url", $row['url']);
$stmt->bindValue(":views", $row['views']);
$stmt->bindValue(":youtube_id", $row['youtube_id']);
$stmt->execute();
}
}
Im not sure what I am doing wrong. I have tried binding it as an array (ex: $array = array(':subId' => $subId); $stmt->execute($array);) and still get no data through to the database. I know my config for the $this->db is good because I can pull other forms of already populated data with it. Any help would be very much appreciated.
I figured out my problem through some of the advice on here. What had been happening is I was trying to bind null values so the bindValue would cause the execute to go through without producing an error. Simple fix was doing this through foreach loops with a couple if statements which allowed me to set a value to the fields that were null. This solved the error. Again thank you to those who attempted to set in the correct path to finding the solution.