I have a need to check the checkboxes which values are available in the database, with that i has to display additional options avaialable also.
I was trying, as i am using two loops it's repeating the same set of checkboxes and check differnt values in each instance.
I need to check the appropriate checkboxes in first loop itself. Is there any way to achieve this
The following was my output
Output of the code
Following is the code i am using
$sid;//Retrived from DB
$iDLst=array();
$sql1 = "SELECT
`id1`
FROM `tbl1`
where `tbl1_sid`='" . $sid . "'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while ($row = $result1->fetch_assoc()) {
$iDLst[]=$row['id1'];
}
}
foreach ($iDLst as $id){
$sql2 = "SELECT
`id`,
`nme`
FROM `tbl2`;
";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while ($rowC = $result2->fetch_assoc()) {
if (strpos($rowC['id'], $id) !== FALSE ) {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" checked/> <label>' . $rowC['nme'] . ' </label>';
} else {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" /> <label>' . $rowC['nme'] . ' </label>';
}
}
}
}
Note: I have changed to general code, There is no errors in code. I am getting the display. I need the solution regarding the logic part...
I think you can replace this:
if (strpos($rowC['id'], $id) !== FALSE ) {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" checked/> <label>' . $rowC['nme'] . ' </label>';
} else {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" /> <label>' . $rowC['nme'] . ' </label>';
}
with this:
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" ' . strpos($rowC['id'], $id) ? 'checked ' : '' . '/> <label>' . $rowC['nme'] . ' </label>';
It's a ternary statement that says if strpos($rowC['id'], $id) evaluates true, 'checked ' will be in the enclosing echo statement, otherwise '' will be in the enclosing echo statement.
I have found the way after some research.
The way i am doing is only half part.
Following code will do the work addition to the provided code.
//Print the checkbox with checeked for the values in array
foreach ($iDLst as $id){
$sql2 = "SELECT
`id`,
`nme`
FROM `tbl2`;
";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while ($rowC = $result2->fetch_assoc()) {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" checked/> <label>' . $rowC['nme'] . ' </label>';
}
}
}
//Print the checkbox without checeked for the values Not in array
$sql3 = "$sql2 = "SELECT
`id`,
`nme`
FROM `tbl2` where id NOT IN (" . implode(',', array_map('intval', $iDLst)) . "); ";
$result3 = $conn->query($sql3);
if ($result3->num_rows > 0) {
while ($rowC = $result3->fetch_assoc()) {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]"/> <label>' . $rowC['nme'] . ' </label>';
}
}
the following questions lead me the way to do this
MySQL PHP - SELECT WHERE id = array()? [duplicate]
mysql syntax on not equal many values
Related
I have a form that queries my server for data using MySQL. I am using a form that sends get requests. It doesn't show anything and I don't know why. I is so strange because my query is valid and I tested it on PHPmyadmin..I am not striving for answers only, I want to know why this happened and what is the reason behind it.
Here is my code:
<form name="get" action="Roster.php" method="get">
<select name="course" id="course">
<?php
$get = mysqli_query($con, "SELECT teaching.Course_ID FROM `teaching` WHERE teaching.F_ID=213000000 ");
while ($row = mysqli_fetch_assoc($get)) {
echo '<option value ="' . $row["Course_ID"] . '"> ' . $row["Course_ID"] . ' </option>';
}
?>
</select>
<select name="group">
<?php
$get = mysqli_query($con, "SELECT `Group_ID` FROM `teaching` WHERE `teaching`.F_ID= 213000000");
while ($row = mysqli_fetch_array($get)) {
echo '<option value ="' . $row["Group_ID"] . '"> ' . $row["Group_ID"] . ' </option>';
}
?>
</select>
<date-util format="yyyy-mm-dd">
<label for="Date" > Date </label><input id="meeting" name="date" type="date" />
</date-util>
<input type="submit" name="Send" value="Get"/>
</form>
<?php
if ($_GET['submit']) {
$sql = " SELECT enrollment.S_ID,student.ID,student.F_Name,student.L_name,attendance.Status,attendance.Date
From enrollment
INNER JOIN student On enrollment.S_ID
INNER JOIN attendance On enrollment.S_ID
where enrollment.Course_ID =" . $_GET["course"] . "and enrollment.Group_ID =" . $_GET["group"] . "and attendance.date =" . $_GET["date"] . " ";
$result = mysqli_query($con, $sql);
$message = "Please Choose Course_ID and Group_ID ";
if ($result > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "Hello";
echo "<tr>";
echo '<td>' . $row['ID'] . '</td>';
echo '<td>' . $row['F_Name'] . " " . $row['L.name'] . '</td>';
echo '<td>' . $row['Date'] . '</td>';
echo '<td>' . $row['Status'] . '</td>';
echo "</tr>";
}
} else {
echo "<tr>";
echo '<td>' . $message . '</td>';
}
}
?>
$_GET['submit'] does not exist. You need to add submit as your name attribute to your button like so
<input type="submit" name="submit" value="Get"/>
Also you should use prepared statements to prevent SQL injection attacks.
Fetching questions from database and displaying in screen now what should be the logical part or how to implement for checking if selected answer is correct or not and how to store correct answer in database and verifying them.
Here is the code
<?php
// Create connection
$conn = new mysqli("localhost","root","","QuizQuestions");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br><br>";
$sql = "SELECT Question, Answer1, Answer2, Answer3, Answer4 FROM Questions";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 1;
while ($row = $result->fetch_assoc()) {
echo "<br>Question: " . $row["Question"] . "<br>";
echo ' A) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer1"] . '">' . $row["Answer1"] . '<br>';
echo ' B) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer2"] . '">' . $row["Answer2"] . '<br>';
echo ' C) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer3"] . '">' . $row["Answer3"] . '<br>';
echo ' D) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer4"] . '">' . $row["Answer4"] . '<br>';
$i++;
}
} else {
echo "0 results";
}
$conn->close();
?>
Because all of the radio inputs have the same name. They all will be considered as same radio group. You need to have different names for different questions. Something like -
$i = 1;
while ($row = $result->fetch_assoc()) {
echo "<br>Question: " . $row["Question"] . "<br>";
echo ' A) <input type="radio" name="ans' . $i . '" value="' . $row["Answer1"] . '">' . $row["Answer1"] . '<br>';
echo ' B) <input type="radio" name="ans' . $i . '" value="' . $row["Answer2"] . '">' . $row["Answer2"] . '<br>';
echo ' C) <input type="radio" name="ans' . $i . '" value="' . $row["Answer3"] . '">' . $row["Answer3"] . '<br>';
echo ' D) <input type="radio" name="ans' . $i . '" value="' . $row["Answer4"] . '">' . $row["Answer4"] . '<br>';
$i++;
}
You also can use the row id instead of the of $i.
You have set same name for all radio buttons. You should group the radio buttons for each question. For that you can get the question id from the database and set the radio button name like
echo ' A) <input type="radio" name="ans'.$row["id"].'"
value="'.$row["Answer1"].'">'.$row["Answer1"].'<br>';
Make sure you have different names for each input field in the radio group so that it treats each question as a different record.
I know there are a lot of topics on this, and I've looked at them all, and they don't help me. My table name is correct, no spaces or anything out of the ordinary. I've checked 100 times and checked 100 more. I'll post both bits of my code, and hopefully someone can help.
I get this error when I try to use the submit button:
Error updating odds: Unknown column 'homeOdds' in 'field list'
POST:
if ($_POST['action'] == 'Update') {
foreach($_POST['game'] as $game) {
$homeScore = ((strlen($game['homeScore']) > 0) ? $game['homeScore'] : 'NULL');
$homeOdds = (str_replace("\xBD", ".5", $homeScore));
$visitorScore = ((strlen($game['visitorScore']) > 0) ? $game['visitorScore'] : 'NULL');
$visitorOdds = (str_replace("\xBD", ".5", $visitorScore));
$sql = "update " . $db_prefix . "schedule ";
$sql .= "set homeOdds = '" . $homeOdds . "', visitorOdds = '" . $visitorOdds . "' ";
$sql .= "where gameID = " . $game['gameID'];
mysql_query($sql) or die('Error updating odds: ' . mysql_error());
}
header('Location: index.php');
}
Table/Form & Update button:
<form id="scoresForm" name="scoresForm" action="odds.php" method="post">
<input type="hidden" name="week" value="<?php echo $week; ?>" />
<?php
$sql = "select s.*, ht.city, ht.team, ht.displayName, vt.city, vt.team, vt.displayName ";
$sql .= "from " . $db_prefix . "schedule s ";
$sql .= "inner join " . $db_prefix . "teams ht on s.homeID = ht.teamID ";
$sql .= "inner join " . $db_prefix . "teams vt on s.visitorID = vt.teamID ";
$sql .= "where weekNum = " . $week . " ";
$sql .= "order by gameTimeEastern";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
echo '<table cellpadding="4" cellspacing="0" class="table1">' . "\n";
echo ' <tr><th colspan="6" align="left">Week ' . $week . '</th></tr>' . "\n";
$i = 0;
while ($result = mysql_fetch_array($query)) {
$homeTeam = new team($result['homeID']);
$visitorTeam = new team($result['visitorID']);
$rowclass = (($i % 2 == 0) ? ' class="altrow"' : '');
echo ' <tr' . $rowclass . '>' . "\n";
echo ' <td><input type="hidden" name="game[' . $result['gameID'] . '][gameID]" value="' . $result['gameID'] . '" />' . date('D n/j g:i a', strtotime($result['gameTimeEastern'])) . ' ET</td>' . "\n";
echo ' <td align="right"><input type="hidden" name="gameID[' . strtolower($visitorTeam->team) . ']" value="' . $result['gameID'] . '" />' . $visitorTeam->teamName . '</td>' . "\n";
echo ' <td><input type="text" name="game[' . $result['gameID'] . '][visitorScore]" id="game[' . $result['gameID'] . '][visitorScore]" value="' . $result['visitorOdds'] . '" size="3" /></td>' . "\n";
echo ' <td align="right"><input type="hidden" name="gameID[' . strtolower($homeTeam->team) . ']" value="' . $result['gameID'] . '" />at ' . $homeTeam->teamName . '</td>' . "\n";
echo ' <td><input type="text" name="game[' . $result['gameID'] . '][homeScore]" id="game[' . $result['gameID'] . '][homeScore]" value="' . $result['homeOdds'] . '" size="3" /></td>' . "\n";
echo ' </tr>' . "\n";
$i++;
}
echo '</table>' . "\n";
}
?>
<br><input type="submit" name="action" value="Update" />
</form>
Any help is appreciated.
For debugging this, echo (or var_dump) the dynamically generated SQL contained in the $sql variable, before you submit it to the database.
Then take that statement to another client to test it.
MySQL is telling you that the table schedule which you are referencing doesn't contain a column named homeOdds.
We don't see the contents of all the variables that are being incorporated into the SQL text. (The code appears to be vulnerable to SQL Injection.
I'm working with an examination page using php connected to a MySQL database. I'm currently on the part where i need to check if the the answers checked on the radiobutton is correct.
QUESTION: How will i know which radiobutton is checked, and how will i know if the answer on that radiobutton is equal to the data in the database? I want to display the "CORRECT" if it's the same or "INCORRECT" if it's wrong in a different page.
Here is my PHP code for the radiobuttons:
$sql = 'SELECT q_question, q_correct, q_answer2, q_answer3, q_answer4 FROM tblquestions WHERE q_category = "' . $legend3 . '" ORDER BY rand() LIMIT ' . $limit3;
$retval = mysql_query($sql,$conn);
if(!$retval)
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$span1 = $row['q_question'];
$obj1 = $row['q_correct'];
$obj2 = $row['q_answer2'];
$obj3 = $row['q_answer3'];
$obj4 = $row['q_answer4'];
$my_array = array($obj1, $obj2, $obj3, $obj4);
shuffle($my_array);
$rad1 = $my_array[0];
$rad2 = $my_array[1];
$rad3 = $my_array[2];
$rad4 = $my_array[3];
echo '<table width="100%" border="0" cellpadding="1" cellspacing="1">';
echo '<tbody><tr><td colspan="2" width="300" height="40"><span id="question1">' . $count . '. ' . $span1 . '</span></td></tr>';
echo '<tr><tbody><tr><td width="50%"><input name="q' . $nameCTR1 . '" type="radio" class="validate[required] checkbox" id="a[I1A]" value="'. $rad1 .'">A. ' . $rad1 . '</td>';
echo '<td width="50%"><input name="q' . $nameCTR1 . '" type="radio" class="validate[required] checkbox" id="a[I1B]" value="' . $rad2 . '">B. ' . $rad2 . '</td></tr></tbody></tr></tbody>';
echo '<tr><tbody><tr><td width="50%"><input name="q' . $nameCTR1 . '" type="radio" class="validate[required] checkbox" id="a[I1C]" value="' . $rad3 . '">C. ' . $rad3 . '</td>';
echo '<td width="50%"><input name="q' . $nameCTR1 . '" type="radio" class="validate[required] checkbox" id="a[I1D]" value="' . $rad4 . '">D. ' . $rad4 . '</td></tr></tbody></tr></tbody></table>';
echo '<hr width="100%"></hr>';
$nameCTR1 = $nameCTR1 + 1;
Checkbox and radio type filed does not get posted when they are unchecked or not-selected.
So in your action script(the one which you have set in action attribute of form) you can check whether their value has been set in $_POST (if your form method is POST) or not.
If it exist then it implies that fields are checked or selected else not.
I made a function for you. Just call the function getRadio(name of radiobutton here) and it will return the value if it was checked.
function getRadio( $radioName ) {
$radio = $_POST[ $radioName ]; // RADIO NAME IS DEFINED IN HTML
if( isset( $radio ) ) {
return $radio;
}
return $radioName . " is not set";
}
*Also this assumes you are using the post method
I have an code that gets the 'branches' from the database. Each company can have multiple 'branches'.
Only thing is, that is doesn't work. Can you guys figure out what's wrong?
$getbranches = "SELECT * FROM branches ORDER BY naam ASC";
$querygetbranches = mysql_query($getbranches);
while($rijbranche = mysql_fetch_assoc($querygetbranches))
{
echo "<tr>";
echo "<td width='400'>";
echo $rijbranche['naam'];
echo "</td>";
echo "<td>";
$get2 = "SELECT * FROM bedrijf_branche WHERE bedrijf_id = '$id'";
$query2 = mysql_query($get2);
while ($rij20 = mysql_fetch_assoc($query2))
{
$branche_id = $rij20['branche_id'];
}
if($branche_id == $rijbranche['id_branche']){
?>
<input type="checkbox" name="branche[]" value="<?php echo $rijbranche['id_branche']; ?>" CHECKED></input>
<?php
}
else
{
?>
<input type="checkbox" name="branche[]" value="<?php echo $rijbranche['id_branche']; ?>"></input>
<?php
}
echo "</td>";
}
Try the following code
<?php
$id = $_GET['id'];
// Output BRANCHES
$getbranches = "SELECT * FROM branches ORDER BY naam ASC";
$querygetbranches = mysql_query($getbranches);
while ($rijbranche = mysql_fetch_array($querygetbranches)) {
echo ' <tr>' . "\n";
echo ' <td width="400">' . $rijbranche['naam'] . '</td>' . "\n";
// Output CHECKBOX
$get2 = mysql_query("SELECT * FROM bedrijf_branche WHERE bedrijf_id = '" . $id . "' AND branche_id = '" . $rijbranche['id_branche'] . "'");
$rij20 = mysql_fetch_array($get2);
$branche_id = $rij20['branche_id'];
if ($branche_id == $rijbranche['id_branche']) {
$checkbox = '<input type="checkbox" name="branche[]" value="' . $rijbranche['id_branche'] . '" checked="checked" />';
}
else {
$checkbox = '<input type="checkbox" name="branche[]" value="' . $rijbranche['id_branche'] . '" />';
}
echo ' <td>' . $checkbox . '</td>' . "\n";
echo ' </tr>' . "\n";
}
?>
Found a couple of errors I fixed in the above code.
You're closing the <input> fields incorrectly
Your second while() loop is unnecessary as there should only be one row returned
You have to add branche_id to your second mysql_query!
Don't close and re-open your <?php ?> tags for every HTML line when you can just add an echo
Your HTML-syntax is wrong.
The way you close the input tag and the way you want to check the chechbox is wrong
Try this
<input type="checkbox" name="branche[]" value="<?php echo $rijbranche['id_branche']; ?>" checked="checked" />