I am trying to build a basic quiz system and everything seems ok.
The following code shows how a users choose the correct answer and the getresult.php shows the result. In my database, there is a question, opt1, opt2, opt3 opt4 and answer column.
<form method="POST" action="getresult.php">
<label>Enter Your Name:</label><br>
<input type="text" name="name" required><br><br>
<?php
$db = new mysqli("localhost", "root", "","learndb");
$stmt=$db->prepare("SELECT * FROM quiz");
$stmt->execute();
$result=$stmt->get_result();
while($myrow = $result->fetch_assoc())
{
echo "<form method='POST' action='getresult.php'>";
echo $myrow['id'];
echo ".";
echo $myrow['question'];
echo "<br>";
echo "<input type='checkbox' name='mycheck[]' value=".$myrow['opt1'].">";
echo $myrow['opt1'];
echo "<br>";
echo "<input type='checkbox' name='mycheck[]' value=".$myrow['opt2'].">";
echo $myrow['opt2'];
echo "<br>";
echo "<input type='checkbox' name='mycheck[]' value=".$myrow['opt3'].">";
echo $myrow['opt3'];
echo "<br>";
echo "<input type='checkbox' name='mycheck[]' value=".$myrow['opt4'].">";
echo $myrow['opt4'];
echo "<br><br>";
}
?>
<input type="submit" name="submit" value="Get Results" class="btn btn-primary">
getresult.php
<?php
extract($_POST);
$db = new mysqli("localhost", "root", "","learndb");
$stmt=$db->prepare("SELECT * FROM quiz");
$stmt->execute();
$result=$stmt->get_result();
$myrow = $result->fetch_assoc();
$totalCheckboxChecked = sizeof($_POST['mycheck']);
$submit=isset($_POST['submit']);
$count=0;
if($submit)
{
for($i=0;$i<$totalCheckboxChecked;$i++)
{
if($mycheck[$i]==$myrow['answer'])
{
$count=$count+1;
}
}
echo "Hello ";
echo $_POST['name'];
echo "<br>";
echo "You scored ";
echo $count;
}
Now the problem is with the checkbox, I can check all the values from all the questions. And when I use radio button I can check only one value from all questions. How can I check only one value from one question.
I don't know why you're not using radio buttons if you plan to allow only one selection, but you can set a limit to have the same thing with checkboxes with some JavaScript (or jQuery).
Here is an example: see fiddle demo
var limit = 1;
$('input').on('change', function(event) { // this could've been a 'click' event too.
if($(this).siblings(':checked').length >= limit) {
this.checked = false;
/* OR you can do like:
if($("input[name='mycheck']:checked").length > limit) { //... }
*/
}
});
if the question contain only one answer better use radio buttons to select the option
or
else
use this jquery to select single value from checkbox
$('input[type="checkbox"]').on('change', function() {
$('input[type="checkbox"]').not(this).prop('checked', false);
});
Related
I'm a newbie programmer. I need to select then update data when click a button on each row. now I can select and show data but just first update button is working. I think cause of this issue is button id is same. I can't figure out how to create unique id. I try to change id="updatedb" to id="$i" and nothing working
my script is :
$(function(){
$('#updatedb').click(function(){
var a = $('#updatedb').attr('id');
$('#textstatus').val(a);
alert ($('#updatedb').attr('id'));
});
});
and php is :
$sql = $connectdb->query($checknode);
$i = 0;
echo "<table border=1>";
if (!$sql) {
echo $connectdb->error;
else {
while ($row=$sql->fetch_row()) {
$crow = "updatedb".$i;
//echo $crow."<br />";
echo "<form method='post' action=''>";
echo '<tr><td>'.$row[0].'
</td><td>'.$row[1].'</td><td>'.$row[2].'
</td><td>'.$row[3].'</td><td>'.$row[4].'
</td><td>'.$row[5].'</td><td>
<input type="button" id="updatedb" name="updatedb" value="update">
<input type="text" id="textstatus" name="textstatus"
value="" disabled="disabled"></td></tr>';
$i++;
}
}
echo "</form>";
echo "</table>";
You can use class rather then id for button to update see the code below
jquery
$(function(){
$('.updatedb').click(function(){
var a = $(this).attr('class');
$(this).parents('tr').find('.textstatus').val(a);
alert (a);
});
});
php
$sql = $connectdb->query($checknode);
$i = 0;
echo "<table border=1>";
if (!$sql) {
echo $connectdb->error;
}else
{
while ($row=$sql->fetch_row()) {
$crow = "updatedb".$i;
//echo $crow."<br />";
echo "<form method='post' action=''>";
echo '<tr><td>'.$row[0].'
</td><td>'.$row[1].'</td><td>'.$row[2].'
</td><td>'.$row[3].'</td><td>'.$row[4].'
</td><td>'.$row[5].'</td><td>
<input type="button" class="updatedb" name="updatedb" value="update">
<input type="text" class="textstatus" name="textstatus"
value="" disabled="disabled"></td></tr>';
$i++;
}
}
echo "</form>";
echo "</table>";
I'm trying to make a quiz application that shows answers with radio buttons on the sides. When you press the next button a set of new answers will appear and replace the .
I've managed to make four questions pop up as intended and four new ones popup when I press the next button.
Right now theres one problem, my first set of four answers (with qid = 1) does not dissapear, which is weird since the other set of answers with qid = 2 and 3 does and replace eachother whenever I press the next button.
How do I make it so that the new answers appear and replace the old answers?
Here is my code so far PHP:
$qid1 = 1;
$sql1 = mysqli_query($connect,"SELECT * FROM question where qid ='$qid1'");
while($row=mysqli_fetch_assoc($sql1))
{
echo "<input type='radio' name='answer1' value='".$row['Point']."'>"
.$row['answer'] ."<br>";
}
echo "<input type='submit' name='forward1' value='next'>";
$qid2 = 2;
$sql2 = mysqli_query($connect,"SELECT * FROM question where qid ='$qid2'");
while($row2=mysqli_fetch_assoc($sql2)){
if (isset($_POST['forward1'])) {
echo "<input type='radio' name='answer2' value='".$row2['Point']."'>"
.$row2['answer'] ."<br>";
}
}
echo "<input type='submit' name='forward2' value='next'>";
$qid3 = 3;
$sql3 = mysqli_query($connect,"SELECT * FROM question where qid ='$qid3'");
while($row3=mysqli_fetch_assoc($sql3)){
if (isset($_POST['forward2'])) {
echo "<input type='radio' name='answer3' value='".$row3['Point']."'>"
.$row3['answer'] ."<br>";
}
}
echo "<input type='submit' name='forward3' value='next'>";
You need to separate your inputs with form tags. For each of your loops do something like this..
echo "<form>";
$sql3 = mysqli_query($connect,"SELECT * FROM question where qid ='$qid3'");
while($row3=mysqli_fetch_assoc($sql3)){
if (isset($_POST['forward2'])) {
echo "<input type='radio' name='answer3' value='".$row3['Point']."'>"
.$row3['answer'] ."<br>";
}
}
echo "<input type='submit' name='forward3' value='next'>";
echo "</form>";
Try this..
<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) || die("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
// let's put the qid in a session var
session_start();
$qid = isset($_SESSION['qid']) ? $_SESSION['qid']+1 : 1;
$_SESSION['qid'] = $qid;
ob_start();
echo "<form>";
$sql1 = mysqli_query($connect,"SELECT * FROM question where qid ='$qid'");
while($row1=mysqli_fetch_assoc($sql1))
echo "<input type='radio' name='answer1' value='{$row1['Point']}'>{$row1['answer']}<br>";
echo "<input type='submit' name='forward1' value='next'>";
echo "</form>";
$output = ob_get_clean();
?>
?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php echo $output; ?>
</body>
</html>
I am coding some video upload script and I am with the admin panel right now.
There I have a List with all Videos. And each video has one delete button on the right side.
When I click the button then this video should be deleted from database but its not working after I click the button nothing happens.
<?php
$query = mysql_query("SELECT * FROM `videos`");
while($row = mysql_fetch_assoc($query))
{
$id = $row['id'];
$name = $row['name'];
echo "<a href='watch.php?id=$id'>$name</a><br />
<input type='submit' name='remove' value='Delete'<br />";
}
if (isset($_POST['remove']))
{
foreach ($_POST['id'] as $the_id)
{
if (!mysql_query("DELETE FROM videos WHERE id = '$the_id'"))
{
echo mysql_error();
}
}
}
?>
Of course on the header I have the mysql connect query. This is just the php code for listing all videos and try to delete.
Here is an example of doing this with MySQLi, including binding parameters to avoid SQL injection -
if (isset($_POST['remove'])) {
$remove = $mysqli->prepare("DELETE FROM `videos` WHERE `id` = ?");
$vid_id = $_POST['vid_id'];
$remove->bind_param('s', $vid_id);
if(!$remove->execute() === true) {
echo $mysqli->error;
}
}
$query = "SELECT * FROM `videos`";
if ($result = $mysqli->query($query)) {
while($row = $result->fetch_object()){
$id = $row->id;
$name = $row->name;
echo "<a href='watch.php?id=$id'>$name</a><br />";
echo "<form name='delete_vid' method='post'>";
echo "<input type='hidden' name='vid_id' value='$id'>";
echo "<input type='submit' name='remove' value='Delete'<br />";
echo "</form>";
}
} else {
echo mysqli_error($connection);
}
$result->close();
Of course you will have to provide a $connection` to the database, but thsi should get you started not only with MySQLi but with adding a form for each video.
More on SQL Injection
Maybe the problem is in the html, each delete button must be in and independent form, with a hidden input with the id too.
echo "<a href='watch.php?id=$id'>$name</a><br />
<form method='post'><input type='hidden' value='$id'><input type='submit' name='remove' value='Delete'<br /></form>";
<form method="post" >
<?php
$query = mysql_query("SELECT * FROM `videos`");
while($row = mysql_fetch_assoc($query))
{
$id = $row['id'];
$name = $row['name'];
echo "<a href='watch.php?id=$id'>$name</a><br />
<button name='id' value='".$id."' type='submit' >Delete</button>
<br />";
}
if (!mysql_query("DELETE FROM videos WHERE id = '".$_POST['id']."'"))
{
echo mysql_error();
} else {
echo 'successfully deleted';
}
?>
</form>
<?php
//connection to the database
try {
$pdo = new PDO('mysql:host=localhost;dbname=frostedc_movies;charset=utf8',
frostedc_user, 'pass');
echo "connected";
}
catch(PDOException $e) {
echo $e; //2
}
// select everything from the news table
$query = "SELECT * FROM movie";// Table name NOT database name
foreach ($pdo->query($query) as $row) {
echo "<table border='1'>";
echo "<tr>";
echo "<td width='150'>".$row['movietitle']."</td>";
echo "<td width='150'>".$row['genre']."</td>";
echo "<td width='150'>".$row['LastViewed']."</td>";
echo "<td width='150'>".$row['Location']."</td>";
echo "</tr>";
}
echo "</tr>";
echo "</table>";
echo "<br>";
echo "
<form>
<p>Please Enter a Movie Title</p>
<input type='text' name='new_movie' />
<input type='submit' value='Submit' />
</form>";
echo "
<form>
<p>Please Enter the Genre</p>
<input type='text' name='movie_genre' />
<input type='submit' value='Submit' />
</form>";
echo "
<form>
<p>Please Enter the Last View Date</p>
<input type='text' name='last_view' />
<input type='submit' value='Submit' />
</form>";
echo "
<form>
<p>Please Enter the Location</p>
<input type='text' name='movie_loca' />
<input type='submit' value='Submit' />
</form>";
$pdo = null;
?>
this is the new updated code. I am trying to use the inputs to enter data into my database.
I have researched how to do this, but so far I haven't got anything to work. Any thoughts? Also would it be easier for me to use include and make the inputs in html? if so could i use them to enter the data into the db?
You are doing 2 wrong things here
First : Mixing PDO with MySQL
Second : $query = "SELECT * FROM myDB"; You cant select from a Database.. You need to do a SELECT from your TABLE ! (Are you sure myDB is your table ?)
As you have tagged your question PDO I have removed all unneeded code from your example.
<?php
//connection to the database
try {
$pdo = new PDO('mysql:host=localhost;dbname=frostedc_movies;charset=utf8',
user, 'password'); //1
echo "connected";
}
catch(PDOException $e) {
echo $e; //2
}
// select everything from the news table
$query = "SELECT * FROM myTable";// Table name NOT database name
echo "<table>";
echo "<tr>";
foreach ($pdo->query($query) as $row) {//3
echo "<td>".$row['movietitle']."</td>";
echo "<td>".$row['genre']."</td>";
echo "<td>".$row['LastViewed']."</td>";
echo "<td>".$row['Location']."</td>";
}
echo "</tr>";
echo "</table>";
// disconnect from the database
$pdo = null;//5
?>
The number comments
1 Setting character set Manual
2 Echoing error message only for development.In production you should either do something with it or remove try/catch.
3 As there are no parameters use query()
4 For utf8 Prior to PHP 5.3.6
5 Changed mysql_close();(mysql_) to $pdo = null; (PDO)
<?php // connect to the database
$host = 'localhost';
$username = 'user';
$pass = 'password';
$conn=mysql_connect($host,$username,$pass)or die(mysql_error());
mysql_select_db("myDB");
// select everything from the news table
$query = "SELECT * FROM news";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo "<table>
<tr>
<td>".$row['movietitle']."</td>
<td>".$row['genre']."</td>
<td>".$row['LastViewed']."</td>
<td>".$row['Location']."</td>
</tr>
</table>";
}
// disconnect from the database
mysql_close();
?>
try this code
<?php // connect to the database
$host = 'localhost';
$username = 'user';
$pass = 'password';
mysql_connect($host,$username,$pass);
mysql_select_db("myDB");
// select everything from the news table
$query = "SELECT * FROM `tablename`";
$result = mysql_query($query);
echo "<table>";
echo "<tr>";
while( ($row = mysql_fetch_array($result)))
{
echo "<td>".$row['movietitle']."</td>";
echo "<td>".$row['genre']."</td>";
echo "<td>".$row['LastViewed']."</td>";
echo "<td>".$row['Location']."</td>";
}
echo "</tr>";
echo "</table>";
// disconnect from the database
mysql_close();
?>
<iframe id="frame1" name="frame1" align="center" src="committee_assign1.php" height="400" width="700">
</iframe>
<center><input onClick="submitiframeform(); return false;" type="button" name="submit" value="Submit" />
<script type="text/javascript">
function submitiframeform(){
window.frames['frame1'].document.forms['fypassign'].submit();
}
</script>
The above is the main page name committee_assign.php ..
And below is the page where the iframe called committee_assign1.php.
<?php
include '../database.php';
include 'valid_login.php';
if(isset($_POST['submit'])) {
$continue = FALSE;
$i = 0;
while ($continue == FALSE) {
if (isset($_POST['id_'.$i])) {
$fypcomm = $_POST['fypcomm_'.$i];
$user = $_POST['id_'.$i];
$sql = mysql_query(" UPDATE Lecturer SET LectFypCommittee = '$fypcomm' WHERE LectID = '$user' ")
or die(mysql_error());
mysql_query($sql);
} else
{$continue = TRUE;}
$i++;
}
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.location.href='../committee/committee_assign1.php'
</SCRIPT>");
}
?>
<head>
</head>
<body>
<form id="fypassign" name="fypassign" method="post" action="" target="_self" onSubmit="">
<?php
$counter = 0;
echo "<table class ='box'>";
echo "<thead>";
echo "<tr>";
echo "<th align='left' valign='top'>"."Lecturer Name"."</th>";
echo "<th align='left' valign='top'>"."FYP Committee"."</th>";
echo "</tr>";
$sql = mysql_query(" SELECT * FROM Lecturer ORDER BY LectFypCommittee DESC, LectName ASC ") or die(mysql_error());
while($info = mysql_fetch_assoc($sql)) {
$idcount = "id_".$counter;
echo "<input type='hidden' name='$idcount' id='$idcount' value={$info['LectID']} />";
echo "<tr>";
echo "<td>";
echo $info['LectName'];
echo "</td>";
echo "<td>";
$formname = "fypcomm_".$counter;
echo "<select name='$formname'>";
//to convert the flag value to user understandable language
if ($info['LectFypCommittee'] == '0'){
$dbfyp = 'No';
}
else $dbfyp = 'Yes';
echo "<option selected='selected' value='{$info['LectFypCommittee']}'>".$dbfyp."</option>";
if ($info['LectFypCommittee'] == '0'){
echo "<option value='1'>".'Yes'."</option>";
}
else echo "<option value='0'>".'No'."</option>";
echo "</select>";
echo "</td>";
echo"</tr>";
$counter++;
}
echo "</table>";
?>
</form>
</body>
I clicked submit button at the parent page and the page refresh but the value is not update.
Can anyone here guide me on this please?
So sorry to post such long codes as I hope you guys could understand more what I am doing. TQ
You have no input in your committee_assign.php named submit:
if(isset($_POST['submit']))
You must check with something like this:
if(isset($_POST))
You are checking if submit has been posted but you dont have an input named submit. Add an input named submit with some value and check if that post submit exists. You can make it hidden if you dont want to see an extra input.
if($_POST['submit']) is checking if there is a value with key 'submit' in the post array. All the key and value in $_POST array is name and value of a form element respectively.