Data insertion using array in PHP - php

I have a php script for conducting online test. while taking test, I am using post method to get the answers in the action page.The answers are passed as an array with question id and the selected option value(true or false/the answers the candidate entered like that).Then I have to insert the answers marked by the candidate in the database. The code is as shown below:
$student_id=$_POST['name'];
$survey_id=$_POST['survey_id'];
$store = array();
if (isset($_POST['question_id'])) {
foreach ($_POST['question_id'] as $key => $option) {
$option1 = array_filter($option);
print_r($option1);
if (count($option1) > 1) {
$option2 = implode("^", $option1);
$store[] = $option2;
} else {
$value = $option1;
$i = implode(null, $option1);
$store[] = $i;
}
}
print_r($store);
}
$t = new DateTime();
$t->setTimestamp($time = time());
$t->setTimeZone(new DateTimeZone("Asia/Singapore"));
$date = $t->format(DateTime::RFC850);
$SQL = "INSERT INTO answer_table(student_id ,survey_id, ans_1, ans_2, ans_3, ans_4, ans_5, ans_6, ans_7, ans_8, ans_9, ans_10, timestamp) VALUES ('$student_id','$survey_id', '$store[0]', '$store[1]', '$store[2]', '$store[3]', '$store[4]', '$store[5]', '$store[6]', '$store[7]', '$store[8]', '$store[9]', '$date')";
$result = mysql_query($SQL);
If the student answers the test in sequential order(from question number 1 to 10) the code works fine. But when the candidate answers in random manner(first 10 then 5 like that),the table field named,ans_1 will get inserted with answer of question number 10. I need to insert fields with corresponding answers ,(ans_1 with answer of question 1 like that) what ever pattern,the candidate takes test.
Can anyone help me to solve this issue. Thanks in advance.

For achieving you goal.you should store question_id with answers or create another table which store question_id and corresponding answers, with id of answer table.

If you have the question id in the $key variable, you could use
$store[$key] = $option2;
instead of
$store[] = $option2;
With that the first question is the first entry in the array regardless of the order of the answers in the post array.

You can replace $store[] = $option2; with:
$store[$_POST['question_id']] = $option2;

Related

Add a count of one in every iteration in while loop, to dynamic array key

Hi I am making a polling functionality. In the below code I am trying to get count of answers by storing the key of array $count as id of the answer and += to count how many times it was chosen as an answer.
The problem that I am having is that $count[$option_id] += 1; doesn't work. Not sure what I am doing wrong with the logic. In the database the records exist and I can confirm that query run fine and gets the result.
There are 2 answers possible per vote. For eg: lets take answer with Id 1 and 2. So, in the end, it should output something like
details: {1: 20, 2: 50}
This means that 20 people have voted for Answer 1 and 50 people for 2.
Any help will be great, Thanks
$answer_count = 0;
$count = array();
$query = "SELECT * FROM `votes` where ques_id = 55";
$stmt = $this->db_obj->query_exec($query);
while($info = mysqli_fetch_array($stmt)){
$answer_count++;
$option_id = $info['option_id'];
$count[$option_id] += 1;
}
return json_encode(array("success" => "1","total" => $answer_count,"details" => $count));

Select pairs of value from 2 columns from table A and insert it into another table B in random order

I'm developping a quiz app, and for this I use 2 different tables:
One is "question", where there are questions and answers
the other one is "answer_quizz_user" with a unique id depending on the candidate, where I have exactly the same column than "question", with the answer in a random order.
My goal is to show the same question with the same answer in a random order, and to save it in the db like this.
This is what my table looks like
I would like to select the column by pair
(answer"X"_right_answer is a boolen which mean right or wrong answer):
(answer1,answer1_right_answer),
(answer2,answer2_right_answer),
(answer3,answer3_right_answer),
(answer4,answer4_right_answer),
(answer5,answer5_right_answer),
(answer6,answer6_right_answer)
to shuffle it, and insert it in "answer_quizz_user".
I tried different things like :
for ($n=1; $n <=6 ; $n++) {
INSERT INTO answer_quizz_user SELECT
answer".$n." FROM question
WHERE question_question = "q1"
ORDER BY RAND()}
but none worked. I have absolutely no idea how to manage this select->insert. I know that I should have done another table for answers, but now it's too late, the app is almost finish, I just need this random part...
Thanks for your help and sorry for my bad english..
Something like this should work, although your database structure is quite bad. Next time use a separate table for your answers.
It isn't a copy-and-paste solution (I would needed to know more about your code to do that), but I hope it will be enough to set you on the right path.
The basic idea is, you get your pairs from the db, put them in an array, use php's built-in shuffle() function, then insert your rows.
// Gets the required row from database
$query = "select * from question where question_question = 'q1';";
$result = $db->query($query);
if($result->num_rows > 0) {
$question = $result->fetch_assoc();
// Create an array with the pairs
$pairs = array();
for($n = 1; $n <= 6; $n++) {
$pairs[] = array(
'Answer' => $question['answer' . $n],
'IsRight' => $question['answer' . $n . '_right_answer'],
);
}
// Arrange pairs in random order
shuffle($pairs);
// Insert the new rows
foreach($pairs as $pair) {
$query = "insert into answer_quizz_user values ('" . $pair['Answer'] . "', '" . $pair['IsRight'] . "');";
$db->query($query);
}
}
I hope, I could be of any help.

Passing multiple checkbox values to different columns of database

I am pretty new to PHP, but have tried searching for other questions similar to mine and been unable to find anything that is close enough to my situation to help me solve this.
I am trying to code a web page that allows users to select as many or as few items as they would like to order. The item values are identical to their Primary Key in the Item table.
Once submitted, each different item value should be input into the same row of a database table based on the date{pk}. Within that row, there are numerous columns: Item1ID, Item2ID, Item3ID, etc.
So far, the value of each item selected is assigned to a new array. However, I cannot simply input the array values into a column -- I need each array index to be placed into a sequential column. The code is below:
$date = new DateTime();
$td = $date->format('Y-m-d');
$x = 1;
$checkedItems = $_POST['Item'];
$count = count($checkedItems);
echo $count;
$foodID = "Item".$x."ID";
While($x<=$count){
if(isset($_POST['Item'])){
if (is_array($_POST['Item'])) {
foreach($_POST['Item'] as $values){
$selectedFoods = substr($values,0,4);
$addFoodOrderQuery= sprintf("UPDATE WeeklyBasketFoodOrder SET '%s' = %s WHERE `foodOrderDate` = '%s'",
$foodID, $selectedFoods, $td);
$result= mysqli_query($db, $addFoodOrderQuery);
}
}
} else {
$values = $_POST['Item'];
echo "You have not selected any items to order.";
}
$x++;
}
If you need any further clarification, please let me know. After submitting the code, the database item#ID tables are different, but they are now empty instead of "NULL."

Data Looping from MYSQL Database

I am having a problem of data looping here. Basically the questions keep looping whenever there are answers for it . I am trying to display something like :
Question
Answer 1
Answer 2
Answer 3
instead of
Question
Answer 1
Question
Answer 2
Question
Answer 3
Anyone know how to solve this ?
<?php
$auctionSurvey = "SELECT questions.question_id, answers.question_id, answers.survey_id, question_body, answer_body FROM questions
INNER JOIN answers ON answers.question_id = questions.question_id
WHERE answers.survey_id='1'";
$aucResult = mysql_query($auctionSurvey) or die (mysql_error());
while ($auctionRow = mysql_fetch_assoc($aucResult)) {
echo $auctionRow['question_body'] . $auctionRow['answer_body'];
}
$questionId = 0;
while($auctionRow = mysql_fetch_assoc($aucResult)){
if($auctionRow['question_id'] != $questionId){
echo $auctionRow['question_body'];
$questionId = $auctionRow['question_id'];
}
echo $auctionRow['answer_body'];
}
Add some HTML to format it and that should work for ya.
Edit: Proof: http://ideone.com/Gkq2hd

How can I copy a database table to an array while accounting for skipped IDs?

I previously designed the website I'm working on so that I'd just query the database for the information I needed per-page, but after implementing a feature that required every cell from every table on every page (oh boy), I realized for optimization purposes I should combine it into a single large database query and throw each table into an array, thus cutting down on SQL calls.
The problem comes in where I want this array to include skipped IDs (primary key) in the database. I'll try and avoid having missing rows/IDs of course, but I won't be managing this data and I want the system to be smart enough to account for any problems like this.
My method starts off simple enough:
//Run query
$localityResult = mysql_query("SELECT id,name FROM localities");
$localityMax = mysql_fetch_array(mysql_query("SELECT max(id) FROM localities"));
$localityMax = $localityMax[0];
//Assign table to array
for ($i=1;$i<$localityMax+1;$i++)
{
$row = mysql_fetch_assoc($localityResult);
$localityData["id"][$i] = $row["id"];
$localityData["name"][$i] = $row["name"];
}
//Output
for ($i=1;$i<$localityMax+1;$i++)
{
echo $i.". ";
echo $localityData["id"][$i]." - ";
echo $localityData["name"][$i];
echo "<br />\n";
}
Two notes:
Yes, I should probably move that $localityMax check to a PHP loop.
I'm intentionally skipping the first array key.
The problem here is that any missed key in the database isn't accounted for, so it ends up outputting like this (sample table):
1 - Tok
2 - Juneau
3 - Anchorage
4 - Nashville
7 - Chattanooga
8 - Memphis
-
-
I want to write "Error" or NULL or something when the row isn't found, then continue on without interrupting things. I've found I can check if $i is less than $row[$i] to see if the row was skipped, but I'm not sure how to correct it at that point.
I can provide more information or a sample database dump if needed. I've just been stuck on this problem for hours and hours, nothing I've tried is working. I would really appreciate your assistance, and general feedback if I'm making any terrible mistakes. Thank you!
Edit: I've solved it! First, iterate through the array to set a NULL value or "Error" message. Then, in the assignations, set $i to $row["id"] right after the mysql_fetch_assoc() call. The full code looks like this:
//Run query
$localityResult = mysql_query("SELECT id,name FROM localities");
$localityMax = mysql_fetch_array(mysql_query("SELECT max(id) FROM localities"));
$localityMax = $localityMax[0];
//Reset
for ($i=1;$i<$localityMax+1;$i++)
{
$localityData["id"][$i] = NULL;
$localityData["name"][$i] = "Error";
}
//Assign table to array
for ($i=1;$i<$localityMax+1;$i++)
{
$row = mysql_fetch_assoc($localityResult);
$i = $row["id"];
$localityData["id"][$i] = $row["id"];
$localityData["name"][$i] = $row["name"];
}
//Output
for ($i=1;$i<$localityMax+1;$i++)
{
echo $i.". ";
echo $localityData["id"][$i]." - ";
echo $localityData["name"][$i];
echo "<br />\n";
}
Thanks for the help all!
Primary keys must be unique in MySQL, so you would get a maximum of one possible blank ID since MySQL would not allow duplicate data to be inserted.
If you were working with a column that is not a primary or unique key, your query would need to be the only thing that would change:
SELECT id, name FROM localities WHERE id != "";
or
SELECT id, name FROM localities WHERE NOT ISNULL(id);
EDIT: Created a new answer based on clarification from OP.
If you have a numeric sequence that you want to keep unbroken, and there may be missing rows from the database table, you can use the following (simple) code to give you what you need. Using the same method, your $i = ... could actually be set to the first ID in the sequence from the DB if you don't want to start at ID: 1.
$result = mysql_query('SELECT id, name FROM localities ORDER BY id');
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[(int) $row['id']] = array(
'id' => $row['id'],
'name' => $row['name'],
);
}
// This saves a query to the database and a second for loop.
end($data); // move the internal pointer to the end of the array
$max = key($data); // fetch the key of the item the internal pointer is set to
for ($i = 1; $i < $max + 1; $i++) {
if (!isset($data[$i])) {
$data[$i] = array(
'id' => NULL,
'name' => 'Erorr: Missing',
);
}
echo "$i. {$data[$id]['id']} - {$data[$id]['name']}<br />\n";
}
After you've gotten your $localityResult, you could put all of the id's in an array, then before you echo $localityDataStuff, check to see
if(in_array($i, $your_locality_id_array)) {
// do your echoing
} else {
// echo your not found message
}
To make $your_locality_id_array:
$locality_id_array = array();
foreach($localityResult as $locality) {
$locality_id_array[] = $locality['id'];
}

Categories