While loop and for statement - php

I am trying to build an online reading test for my students. I currently have two tables in my database : 'student' and 'questions'. In 'student', I have a row for each student which containts it's name, group number and answers to the questions. Questions cols are called question[1], question [2], and so on.
In 'questions', I have 4 cols : ID, 'first', 'chapter' and 'question'. 'first' is a true/false field, if it is the first question to a chapter its value is 1. I call those with a while loop.
echo '<ol>';
$query = mysql_query("SELECT * FROM `question`");
while($row_q = mysql_fetch_assoc($query)) {
if($row_q['first']==1){
echo '<h2>Chapter '.$row_q['chapter'].'</h2><br>';
}
echo '<li>';
echo $row_q['question'];
echo '</li>';
echo '<br>';
}
echo '</ol>';
It echoes beautifuly. Now, I'm trying to put an input field under each question so the student can give an answer and submit it at the end of the page. How can I do this? I tried using a for($i=1;$i<=10;$i++) statement since I want each field to be named with a different number, but no matter where I insert it, I either end up with a bunch of identical fields next to each other or my questions echoed over and over again.
I'm open to all suggestions. Thanks!

there's no need to do a for loop, you're already in a loop :) just set a variable called question number and increment it in the while loop.
$question_number =1;
echo '<ol>';
$query = mysql_query("SELECT * FROM `question`");
while($row_q = mysql_fetch_assoc($query)) {
if($row_q['first']==1){
echo '<h2>Chapter '.$row_q['chapter'].'</h2><br>';
}
echo '<li>';
echo "<label>$question_number".$row_q['question']."</label>";
echo "<input type='text' name='$row_q[\'ID\']'></input>";
echo '</li>';
echo '<br>';
$question_number++;
}
echo '</ol>';

echo '<input name="answer[' . htmlspecialchars($row_q['ID']) . ']" type="text" value="" />';
under the question text... Then in PHP var_dump($_REQUEST) to see the answers...
EDIT:
For displaying the saved answer, you'll want to do something like this:
echo '<input name="answer_' . $idx . '" type="text" ' .
value="' . htmlspecialchars($student_row["answer_$idx"]) . '" />';
and maintain a counter $idx as you loop...
That's if your answer are laid out flat in the student table per your description and the answer value columns are named "answer_1" etc.
If the answers are normalized in a separate table, you can join the tables together:
select * from question q left join answer a on a.question_id = q.question_id and
a.student_id = <current student id>

Related

How can I use the results of my query in a dropdown menu?

I am trying to create a dropdown menu that will have as options certain fields recovered from a database using a for loop.
I am doing the following:
for ($article_id=1; $article_id <=30; $article_id++)
{
$sqltitles = "SELECT title FROM articles WHERE article_id='$article_id'";
$cursor = mysqli_query($db, $sqltitles) or die($sqltitles."<br/><br/>".mysql_error());
$row = mysqli_fetch_row($cursor);
$titles = $row[0];
echo $titles;
echo "</br>";
}
Which draws all the titles from the database and shows them one at a time.
Is there any way to make all those titles appear as options to a dropdown menu, so the user can select which one to read?
Something like this should work. I made a modification to how the query is working. If you specify article IDs for a range of articles in your query rather than just one specific ID, you should be able to execute only one query instead of one for each ID you want to retrieve. Regardless of whether or not you decide to use the approach I suggested, the syntax for creating the dropdown menu should be the same.
<select>
<?php
$sqltitles = "SELECT title FROM articles WHERE article_id BETWEEN 1 AND 30" ;
$cursor = mysqli_query($db, $sqltitles) or die($sqltitles."<br/><br/>".mysql_error());
while ($row = mysqli_fetch_row($cursor)) {
echo '<option value ="' . $row[0] . '">' . $row[0] . '</option>';
}
?>
</select>
Here is a good reference for how to create HTML <select> tags.
try something along the lines of...
echo '<select name="dropdownname">';
foreach ($titles as $key => $val) {
echo('<option value="' . $val .'">' . $val . '</option>');
}
echo '</select>';

Displaying values from multiple MySql database fields together as one

I'm doing a project where I have to take in information from a user on a web page and store it in a MySql database. Some of the fields the user has to fill out are his street number, name and suburb and these are separate fields and are stored as separate values in the database.
So, part of the project is to display all of the entries in a table, but combine the info from above (Street no, name, suburb) and display it together in one cell under the heading 'Address' so it shows as full address.
So my question is, what are some ways of doing this?
Everything is working so far and I can display each field individually, so it's just the question of formatting.
Hopefully, you guys can give me a hand,
Cheers!
EDIT: This is how I'm displaying the table right now:
$QueryResult = mysql_query("SELECT * FROM booking");
$row = mysql_fetch_row($QueryResult);
echo "<table width='100%' border='1'>";
echo "<tr><th>Booking No</th><th>Passanger Name</th><th>Phone</th><th>Unit</th>";
echo "<th>Street No</th><th>Street Name</th><th>Pick-up Suburb</th><th>Destination Suburb</th>";
echo "<th>Pick-up Date</th><th>Pickup time</th></tr>";
$countRows = 0;
$tweight=0;
while($row){
$countRows++;
echo "<tr><td>{$row[0]}</td>";
echo "<td>{$row[1]}</td>";
echo "<td>{$row[2]}</td>";
echo "<td>{$row[3]}</td>";
echo "<td>{$row[4]}</td>";
echo "<td>{$row[5]}</td>";
echo "<td>{$row[6]}</td>";
echo "<td>{$row[7]}</td>";
echo "<td>{$row[8]}</td>";
echo "<td>{$row[9]}</td></tr>";
$row = mysql_fetch_row($QueryResult);
}
How would I use CONCAT in this case?
Thanks
In php:
$address = $row[4] . ' ' . $row[5] . ' ' . $row[6];
In mysql:
SELECT CONCAT(street_no, ' ', street_name, ' ', suburb) AS address FROM ...
Choose one of them and change this code depending on the variable names you have.

PHP, MYSQL noob joining(?) tables specifics

I am new to PHP and am making a social network as practice and to apply what I have learned in the "real world". Anyhow, I have two tables in a MySQL database that i am trying to display on my site in the same html table that is being rendered through an php echo.
here are the tables
(table1)
note_system:
-id,
-username,
-note
(table2)
comments:
-id,
-cid (equals id from note_system),
-username,
-comment
so someone makes a post and it saves to the note_system table then someone comments on the post and it saves to the comment table with the id from the note_system table so a relation can be established.
So what I am trying to do is get the post comments to display with the relevant post. I have gathered that I need maybe a JOIN or UNION to make this happen but I am at a complete loss on how to do it. Been racking my brain and doing tons of google searches but I am not really getting anywhere. Everything I try gives me errors. The Notes display just fine and as intended but I can't for the life of me figure out how to get the comments to show up there too.
Here is my code (don't laugh at the noob-ness of my PHP, this is my 2nd PHP program ever and I obviously have much to learn, I would like to clean it up at some point but for now I just want it to be functional)
<?php
// Display Note_Wire
$con=mysqli_connect($host,$username,$password,$dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//format and display the Note_Wire results with comments
$result = mysqli_query($con,"SELECT * FROM note_system");
while($row = mysqli_fetch_array($result))
{
echo "<center>";
echo "<table class='note_wire'>";
echo "<tr>";
echo "<td>" . $row['username'] . "</td>" ;
echo "</tr><tr>";
echo "<td><a href=''>vote up</a>" . " " . $row['rank'] . " " . "<a href=''>vote down</a></td>" ;
echo "</tr><tr>";
echo "<td> <a href='{$row['link']}' target='blank'>{$row['link']}</a>";
echo "</tr><tr>";
echo "<td>" . $row['note'] . "</td>" ;
echo "</tr> ";
//add comments attempt this is where I would like the comments to be displayed
echo '
<td><form action="add_comment.php" method="POST">
<input type="hidden" name="username" value="';
echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
echo '" />';
echo '<input type="hidden" name="cid" value="';
echo $row['id'];
echo '" />';
echo '<textarea name="comment">comment...</textarea></td></tr>
<tr><td><input type="submit" value="comment" />
</form></td></tr>
';
echo "</table>";
// break before next note-wire record renders
echo "<br />";
}
echo "</center>";
?>
I hope my chicken scratch programming makes sense. Thanks for your time and knowledge.
Really the comments are a different data set from the actual post you could just use a second query to get all of the comments related to the post. But table joins are very useful and you should learn them. In this case you would join the note_system and comments table on the shared ID (the foreign key).
So like so:
SELECT *
FROM note_system
LEFT JOIN comments ON comments.cid=note_system.id
This is a literal joining of the tables so your output will include all columsn from both tables as long as there is a match for the joining expression. If there isn't a CID column in the comments table that matches then the values for those columns will be NULL in your output. (If you wanted to only return rows where there is a match you could use an INNER join as opposed to the LEFT OUTER join I've used above.)
This is a good page explaining SQL table joins.
Heres the basics step for you if your a beginner in using php and mysql..
FIRST : SET UP CONFIGURATION FOR DATABASE USER,PASS,HOST,DBNAME
$conn = new mysqli('database_server','database_username','database_password','database_name');
SECOND : Create a Query(you may insert your query here)..
$result= $conn->query("SELECT SUM(Total_Steps) AS value_sum FROM users");
FINAL : SHOWN RECORDS USING MYSQL FUNCTIONS LIKE..
while($row = $result->fetch_assoc()){
echo $row['dabatase_columnname'];
echo $row['database_columnname'];
}
for your query try to use this one or either create a relative one.
SELECT 'enter column needed here with their specific database allias ex. TABLE1.ID'FROM NOTE_SYSTEM TABLE1 LEFT JOIN COMMENTS TABLE2 ON TABLE1.ID = TABLE2.CID;

Dynamicly creating and checking checkboxes in php

I am trying to dynamically create php check-boxes linked to an MSSQL-Database. The idea is to List every item in the table, with a check box. From there the user will be able to check the check-boxes and click submit to change the value in 1 field of the Database to "A". I have the database linked to the php and It outputs the check-checkboxes and table values, however I do not know from there how to dynamically check the check-boxes to see if they are checked, or to use it from there.
This is roughly the approach you want to take to dynamically create checkboxes. There are of course prettier ways to accomplish this (i.e. Smarty templates).
<html>
...
<form method="post" action="submit.php">
<?php
// connect to DB here
$result = mysql_query("SELECT l.id, l.name, u.checked FROM List l LEFT JOIN UserAnswers u ON l.id = u.list_id WHERE u.user_id = 5");
while ($row = mysql_fetch_assoc($result))
{
echo '<input type="checkbox" name="cb_' . $row['id'] . '" ' .
'id="cb_' . $row['id'] . '" ';
if($row['checked'])
echo 'checked';
echo " />\n"
echo '<label for="cb_' . $row['id'] . '">' . $row['name'] . "</label><br />\n";
}
?>
<input type="submit" value="Submit" />
</form>
...
</html>
submit.php is a bit trickier. When a checkbox is checked, it will set a post item. However if it's unchecked, you won't get ANYTHING back, so you need to check your database for all the items you'll be expecting.
<?php
// connect to DB here
$result = mysql_query("SELECT id, name, checked FROM things");
$answers = Array();
while ($row = mysql_fetch_assoc($result))
{
$checked = isset($_POST['cb_' + $row['id']]);
$answers[$row['id']] = $checked;
}
// update your database here using $answers
foreach ($answers as $id => $checked)
{
$query = "REPLACE INTO UserAnswers SET user_id=5, list_id=" . $id . ", checked=";
if($checked)
$query .= "1";
else
$query .= "0";
mysql_query($query);
}
This is all off the top of my head, there are better ways to do most of this. It's just a general direction. I make no guarantees about any of this. Oh and it looks quite vulnerable to SQL injection, watch out for that.

Query Issue - Trying to group comments within a discussion

I've spent the last few days wrestling with a MYSQL query issue. I hope someone can point me in the right direction.
I'm querying two tables ('questions' and 'comments') with the goal of returning the following layout:
Question 1
Comment 1
Comment 2
Comment 3
Question 2
Comment 4
Comment 5
And so on...
Comments are unique to a question (i.e. comments live under a parent question).
My query (which I know is incorrect) looks like this:
<?php
$query = "SELECT discussion.*, comments.* FROM discussion LEFT JOIN comments ON discussion.referenceID = comments.commentID";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['question']. " - ". $row['comment']. "<br /><br />";
}
?>
The result:
Question 1 - Comment 1
Question 1 - Comment 3
Question 2 - Comment 2
I'm close, but can't achieve the multiple comments under the single question. I tried a 'GROUP BY discussion.question' but that limited my results to:
Question 1 - Comment 1
Question 2 - Comment 2
To put it in context I'm trying to allow users to submit comments on multiple questions displayed on a single page.
Thanks in advance.
RR
try this:
$query = "SELECT *
FROM discussion, comments
WHERE discussion.referenceID = comments.commentID
GROUP BY discussion.referenceID;
Just store the previous question and compare it to the current.
Sketch:
$prev_question = null;
while($row = mysql_fetch_array($result)) {
if ($prev_question != $row['question']) {
echo '<b>' . $row['question'] . '<b><br />';
$prev_question = $row['question'];
}
echo $row['comment'] . '<br />';
}
Zerkms, brilliant! Thanks for the response. Works perfectly, aside from one issue.
The questions only appear if there is a comment associated (an issue I caused myself, at some point). The goal is to display all comments regardless of if comments are assigned.
Working code:
<?php
$query = "SELECT discussion.*, comments.* FROM discussion LEFT JOIN comments ON discussion.referenceID = comments.commentID";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$prev_question = null;
while($row = mysql_fetch_array($result)) {
if ($prev_question != $row['question']) {
echo "<h3>" . $row['question'] . "</h3>";
$prev_question = $row['question'];
}
echo "<img src=\"images/bg_addform_topFull.gif\" width=\"446\" height=\"11\" /><div class=\"comment\"><h3>" . $row['author'] . "</h3><div class=\"greyText\">" . $row['dt'] . "</div><p>" . $row['comment'] . "</p></div><img src=\"images/bg_addform_bottom.gif\" width=\"446\" height=\"11\" class=\"footerImage\" />";
}
}
?>
Again, thanks for the help.

Categories