RobertB13 Posted August 28, 2012 Share Posted August 28, 2012 I am trying to create an array from the results of a query. This is a database of questions for a survey with a survey ID for each survey. I want to display the results of the query in a form, with one submit button, and have the answers be INSERTed into the database under the user ID. I tried a loop and got the questions to display, but I couldn't figure out how to get the looped questions to output each answer for the looped questions on POST. Do I figured I'd go line by line with the results of the query and drop the info into each form INPUT. $query = 'SELECT * from survey_questions WHERE survey_id = ' . $survID . ''; $result = mysql_query($query); $numRows = mysql_num_rows($result); $activeRow = mysql_data_seek($result,0); // Set active row $row = mysql_fetch_row($activeRow); // Capture active row data $body = $row['question_body']; // Get question This isn't pulling the question data for row[0] into $body. I have no idea why. I am new though... Thanks! Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 28, 2012 Share Posted August 28, 2012 I'm having a little trouble understanding the issue. There's a lot of information NOT stated that could make the solution go one way or the other. But, I *think* you are just having a problem outputting the results of the survey. There is no need to use complicated logic for seeking the data. A simple while() loop is all that is needed. Also, you are assigning a value to $body, but not doing anything with it. So, if you selected a new record and did the same thing you would overwrite what you previously extracted. Try something like this (note I made some assumptions on field names - you need to edit appropriately) $query = "SELECT question_body, answer FROM survey_questions WHERE survey_id = {$survID} ORDER BY question_id"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { echo "<b>Question: {$row['question_body']}</b><br>\n" echo "Answer: {$row['answer']}<br><br>\n" } Quote Link to comment Share on other sites More sharing options...
RobertB13 Posted August 28, 2012 Author Share Posted August 28, 2012 That challenge I'm having is pulling the Answers from the loop and INSERTing them in the survey_answers database. When the while loop goes through the database it pulls the 1st Q, 2nd Q etc... and echo's them. How do I pull those answers to the database when each trip through the assigns name"answer" to each of the questions? Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 28, 2012 Share Posted August 28, 2012 You are talking in circles and not making sense. Slow down and take your time to provide a clear and concise question. It will help all parties involved. For example: That challenge I'm having is pulling the Answers from the loop and INSERTing them in the survey_answers database. That makes no sense to me. The loop in question is a loop that is extracting records from a database query. If you are getting these records from the database, why do you need to INSERT them!? They are already in the database. So, I believe you are misstating the issue. So, this is what I NOW think you are trying to accomplish: 1. You want to pull a list of questions from the DB and create a form for the user to enter their answers. 2. You need to take the answers submitted by the user (sent in POST data) and insert their responses into an appropriate table. OK, so for the first part you would query the questions from the database. You need to get the question_body AND the ID of the question. The ID is needed when processing the responses $query = "SELECT question_id, question_body FROM survey_questions WHERE survey_id = {$survID}"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { echo "Question: {$row['question_body']}<br>\n" echo "<input type='text' name='answers[{$row['question_id']}]'><br><br>\n" } The input fields will look something like this <input type='text' name='answers[2]'> where the 2 will be the id of the question. Then, when the user submits the page you will have an array $_POST['answers'] which will contain all the submitted answers associated with the question IDs. So, when processing the POST data, just loop through the array something like this foreach($_POST['answer'] as $question_id => $answer_text) { //process the data and create INSERT statement } NOTE: Do NOT create multiple INSERT statements. Just create the VALUES part of the INSERT in the foreach() loop then do one INSERT at the end. Quote Link to comment Share on other sites More sharing options...
RobertB13 Posted August 28, 2012 Author Share Posted August 28, 2012 1. You want to pull a list of questions from the DB and create a form for the user to enter their answers. 2. You need to take the answers submitted by the user (sent in POST data) and insert their responses into an appropriate table. Sorry about the vagueness of my questions. I'm new and don't quite know how to ask them. You are correct. My data (questions) are in the database. I want to be able to take the answers as you detailed and put those answers into the database. Can you detail what you mean by the VALUES part of the INSERT being in the FOR loop. I don't really understand how that works. I appreciate your help... Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 29, 2012 Share Posted August 29, 2012 Can you detail what you mean by the VALUES part of the INSERT being in the FOR loop. I don't really understand how that works. I'm a bit apprehensive to write out a solution. This seems like it may be a homework problem. Besides this forum is to get help with code you have written. I'd like to at least see an attempt at you writing a solution. Quote Link to comment Share on other sites More sharing options...
RobertB13 Posted August 29, 2012 Author Share Posted August 29, 2012 I'm not in school unless you count the school of Google. I've been working on this database and survey for my business website. I'm really just trying to learn how this all works because I'm curious. I've been working on this for at minimum 50hrs attempting one solution after another. I am only on here, and I stress ONLY because I'm thoroughly stumped and can't figure it out myself. If you can help, great, if not, I'll keep trying. I really don't know what you mean by the VALUE being inside and the INSERT being outside as it's all one query. I understand the INSERT INFO comes before VALUE, not after. I'm confused. Thanks for any guidance given Quote Link to comment Share on other sites More sharing options...
RobertB13 Posted August 29, 2012 Author Share Posted August 29, 2012 This is what I have so far... Thanks for the lead with the question loop. I modified it to take into account the length of answers. with a default length. <?php session_start(); /* ################################ */ /* ###### Sandbox Document ######## */ /* ################################ */ /* ################################ */ /* #### Get Survey Answers ######## */ /* ################################ */ function getQuestions($dbc) { $survID = $_SESSION["surveyid"]; $ansSizS = $_SESSION["answerSize"]; $query = "SELECT question_id, question_body, answer_length FROM survey_questions WHERE survey_id = {$survID}"; $result = mysql_query($query) or die(mysql_error()); $qNum = 1; echo ' <form action="/survey/functions/results.php" method="post">'; while($row = mysql_fetch_assoc($result)) { // print_r ($row); $ansSiz = $row["answer_length"]; if ($ansSiz==0) { echo "<div class='entry'><span class='qTitle'>{$qNum}: {$row['question_body']}<br>\n"; echo "<input type='text' name='answers[{$row['question_id']}]' size='{$ansSizS}'><br><br>\n</div>"; $qNum = $qNum + 1; } else { echo "<div class='entry'><span class='qTitle'>{$qNum}: {$row['question_body']}<br>\n"; echo "<input type='text' name='answers[{$row['question_id']}]' size='{$row['answer_length']}'><br><br>\n</div>"; $qNum = $qNum + 1; } } echo ' <div class="entry"> <p> <span class="qTitle">Enter email for results</span><br/> <input type="text" name="email" size="45" /> <p> <input type="submit" value="Submit" name="submit" /> <input type="hidden" name="questionid" value="questionid" /> <input type="hidden" name="submitted" value="1" /> </form> </div>'; unset ($_SESSION['surveyid']); } //END function getQuestions ?> I am stuck on the forloop() I don't understand how to output from the array. I told you I'm a newby... Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 29, 2012 Share Posted August 29, 2012 I will try to give you some assistance, but I have no idea what you are talking about. There is no for() loop in that code. That function, named getQuestions(), appears to be made for displaying the questions. The only for() loop we've discussed is the loop that would be used to process the form when the user submits it. That would have nothing to do with the above code. So, what issues are you having with THAT code above? Other than being a little disorganized nothing jumps out at me as being problematic. Here is a rewrite of that code <?php session_start(); /* ################################ */ /* ###### Sandbox Document ######## */ /* ################################ */ /* ################################ */ /* #### Get Survey Answers ######## */ /* ################################ */ function getQuestions($dbc) { $surveyID = intval($_SESSION["surveyid"]); $answerSize = intval($_SESSION["answerSize"]); $query = "SELECT question_id, question_body, answer_length FROM survey_questions WHERE survey_id = {$surveyID}"; $result = mysql_query($query) or die(mysql_error()); $questionNo = 0; $formFields = ''; while($row = mysql_fetch_assoc($result)) { $questionNo++ $length = ($row["answer_length"]!=0) ? $row["answer_length"] : $answerSize; $formFields .= "<div class='entry'><span class='qTitle'>{$questionNo}: {$row['question_body']}<br>\n"; $formFields .= "<input type='text' name='answers[{$row['question_id']}]' size='{$answerSize}'><br><br>\n</div>"; } unset ($_SESSION['surveyid']); return $formFields; } //END function getQuestions ?> <form action="/survey/functions/results.php" method="post"> <?php echo getQuestions($dbc); ?> <div class="entry"> <p> <span class="qTitle">Enter email for results</span><br/> <input type="text" name="email" size="45" /> <p> <input type="hidden" name="survey_id" value="<?php echo $_SESSION["surveyid"]; ?>" /> <input type="hidden" name="user_id" value="<?php echo $_SESSION["userid"]; ?>" /> <input type="submit" value="Submit" name="Submit" /> </form> </div> Now, to process that form here is some sample code to get you started: if(isset($_POST['answers'])) { $insertValues = array(); $surveyID = intval($_POST['surveyid']); $userID = intval($_POST['userid']); foreach($_POST['answers'] as $questionID => $answerText) { $questionID = intval($questionID); $answerText = mysql_real_escape_string($answerText); $insertValues[] = "('{$surveyID}', '{$userID}', '{$questionID}', '{$answerText}')"; } $query = "INSERT INTO anser_table (`surveyid`, `userid`, `questionid`, `answer`) VALUES " . implode(', ', $insertValues); $result = mysql_query($query) or die(mysql_error()); } Quote Link to comment Share on other sites More sharing options...
RobertB13 Posted August 30, 2012 Author Share Posted August 30, 2012 Thank you very much for your help. I only included the getQuestions script for background as to how to create the results.php page. Your re-write is way cleaner and I am learning a ton from that example. Line 26... $length = ($row["answer_length"]!=0) ? $row["answer_length"] : $answerSize; is generating an error. I am willing to try to figure it out, but need help. I am not sure what the "?" ... : does. Can you explain what that code is called and what it's supposed to do? My guess is that it assigns either $row['answer_length'] or $answerSize to the variable $length (like an if statement) I did notice that $length & $formFields arn't referenced after they are defined. Were they supposed to be? I'll apologize if my questions are not clear or concise. I'm new (week 2) to PHP in not just the coding, but the language to describe what I'm trying to understand. I did also want to address what you said earlier. I did copy various parts of this code from other sources, but have modified (combined) it substantially to the point that I feel like I'm working on something that I "wrote". Thanks again Quote Link to comment Share on other sites More sharing options...
Jessica Posted August 30, 2012 Share Posted August 30, 2012 ? : is the ternary operator. If you get errors, it helps if you post what they are. Quote Link to comment Share on other sites More sharing options...
RobertB13 Posted August 30, 2012 Author Share Posted August 30, 2012 Hey Jesirose, I know this is a total nube question, but how do I get the output to show me the error? I am using Mac and Safari and the errors that happen don't display, it just shows me the confirmation of the database connecting. www.robertbartz.com/survey/01Sur.php Quote Link to comment Share on other sites More sharing options...
Christian F. Posted August 30, 2012 Share Posted August 30, 2012 Best way to do this is to edit php.ini and enable display_errors and set error_reporting to E_ALL. However, you want to do this on your development server, and not your live (production) server. If you only have one, make sure you turn it off after you finished with the development, before you put it into production. Quote Link to comment Share on other sites More sharing options...
Jessica Posted August 30, 2012 Share Posted August 30, 2012 You said it has errors, so I assumed you saw them. Read the link in my sig re: errors. Quote Link to comment Share on other sites More sharing options...
RobertB13 Posted August 30, 2012 Author Share Posted August 30, 2012 I put error_reporting(-1); and tried error_reporting(E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); In the beginning of my script and it still doesn't show any... Quote Link to comment Share on other sites More sharing options...
Jessica Posted August 30, 2012 Share Posted August 30, 2012 Line 26... $length = ($row["answer_length"]!=0) ? $row["answer_length"] : $answerSize; is generating an error. ???? Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 30, 2012 Share Posted August 30, 2012 Line 26... $length = ($row["answer_length"]!=0) ? $row["answer_length"] : $answerSize; is generating an error. As my signature states, I do not always test the code I provide. It would take too much time to try and set up the appropriate sample data, databases, etc. to do so for every post. The code I provide is typically meant to be used as guidance on developing a full-fledged solution. I expect that the person receiving my code will perform any basic debugging to fix any minor typos. And, that was the case here: $questionNo++ $length = ($row["answer_length"]!=0) ? $row["answer_length"] : $answerSize; Line 24 needs a semi-colon at the end. Also, If you have an error, don't post that you have an error and leave it at that. Provide the actual error message. Quote Link to comment Share on other sites More sharing options...
RobertB13 Posted August 31, 2012 Author Share Posted August 31, 2012 Is anyone willing to help me with my code? Quote Link to comment Share on other sites More sharing options...
Jessica Posted August 31, 2012 Share Posted August 31, 2012 Considering Psycho posted the corrected code, and I never got an answer to how you know there's an error if you don't see an error, at this point probably not. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.