PHP update database with checkbox - php

I am a newbie on ajax and I try to change a value on my database pending a checkbox. I am using following code:
<script type="text/javascript">
function update(id_submit, check){
check = (check==true ? 1 : 0);
var url = "check_validate.php.php?id_submit="+id_submit+"&chkYesNo="+check;
if(windows.XMLHttpRequest){
req = new XMLHttpRequest();
}
else if(windows.ActiveXObject){
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("GET", url, true);
req.send(null);
}
</script>
Then I get a other value from my database:
while ($row = mysqli_fetch_array( $result, MYSQL_ASSOC))
{
$check = $row['checkbox'];
$id_submits = $zeile['id_submits'];
?>
<td style='text-align:center;width:120px;'>
<input name="check" type="checkbox" id="check_<?php echo $id_submits; ?>" value="<?php echo $id_submits; ?>" onclick="check(<?php echo $id_submits; ?>, this.checked);"
<?php if($check == 1){ echo "checked"; }else{ echo "";} ?>/>
</td><?php
And then I have my "check_validate.php"
$id_submit = $_GET['id_submit'];
$chkYesNo = $_GET['chkYesNo'];
require_once('config.php');
$sql = "UPDATE table1
SET checkbox =$chkYesNo WHERE id_submits = $id_submits";
$result = mysqli_query( $link, $sql );
But nothing happens on my database, what am I doing wrong?

Related

Insert value of single form called multiple times using ajax call to mysql in php

I am trying to insert single form value called multiple times using ajax call to mysql in php with submit all button . I have store all the forms data to localStorage. But when I am trying to insert all the values to mysql one form value is inserting and other form values is taking null value.
**loadquestions1.php**
<form method="post">
<table>
<tr>
<td>
<?php echo "<h5>Question: ".$question_no ."</h5><h5> ".$question_title ."</h5>"; ?>
</td>
</tr>
</table>
<div class="center">
<textarea placeholder="Write your answer here..." class="outer persisted-text" name="pt<?php echo $question_no; ?>" id="persisted-text" onchange="changeBack();" rows="10" cols="100"></textarea>
<span><input type="hidden" name="question_no<?php echo $question_no; ?>" value="<?php echo $question_no; ?>" /></span>
<span><input type="hidden" name="question_title<?php echo $question_no; ?>" value="<?php echo $question_title; ?>" /></span>
</div>
<button class="btn btn-success" name="save">Save</button>
<?php } ?>
</form>
function load_questions1(questionno)
{
document.getElementById("current_que").innerHTML=questionno;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if(xmlhttp.responseText=="over")
{
window.location="result.php";
alert("hello");
}
else
{
document.getElementById("load_questions1").innerHTML=xmlhttp.responseText;
load_total_que();
var supported = '',
unsupported = 'Oh no! Your browser does not support localStorage.';
if (window.localStorage) {
$('.persisted-text').keyup(function () {
localStorage.setItem(this.name+questionno, this.value);
}).val(function () {
return localStorage.getItem(this.name+questionno) || supported
})
} else {
$('.persisted-text').val(unsupported);
}
}
}
};
xmlhttp.open("GET", "forajax/load_questions1.php?questionno="+ questionno, true);
xmlhttp.send(null);
}
**config.php**
if (isset($_POST['save'])) {
$size = sizeof($_POST);
$number = $size/3;
$query = "SELECT * FROM add_question where online_exam_title='$_SESSION[add_exam]'";
$data = mysqli_query($conn, $query);
$count=mysqli_num_rows($data);
for($i=1;$i<$count;$i++) {
$index1 = 'pt'.$i;
$pt[$i] = $_POST[$index1];
$index2 = 'question_no'.$i;
$question_no[$i] = $_POST[$index2];
$index3 = 'question_title'.$i;
$question_title[$i] = $_POST[$index3];
//$question_no = $_POST['question_no'];
$sql="INSERT INTO subjective_answer (placeholder, exam_type, username, question_no, question_title) VALUES ('$pt[$i]', '$_SESSION[add_exam]', '$_SESSION[username]', '$question_no[$i]', '$question_title[$i]')";
$result=mysqli_query($conn,$sql);
}
if($result)
{
echo "record inserted";
}
}

Display BLOB data from SQLITE database using PHP

Hope You all have a Great Day, I new with SQLITE DB and so I'm little confused about handling BLOB data.I tried lot of things ,but nothing get in to favor of me.
Here is My Code
INSERTING DATA
insert.php
<form method="POST" enctype="multipart/form-data">
model no:<input type="text" name="model_no"\><span style="color: red"><?php echo $messages["model_no"]; ?></span>
image:<input type="file" name="image" id="image"\><span style="color: red">
<input type="submit" value="save" id="save" name="save"/>
<input type="reset" value="Clear"/>
</form>
include.php
<?php
$flag = 0;
class MyDB extends SQLite3
{
function __construct()
{
$this->open('../database.db');
}
}
//checking save button is clicked
if(isset($_POST["save"])){
$model_no = $_POST['model_no'];
$image = $_FILES['image']['name'];
if($model_no != '' && $image != ''){
$flag = 1;
}
if($flag == '1'){
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
}
else{
$dbb = new MyDB();
$sql = 'SELECT COUNT(*) as count FROM fisfis WHERE model_no = "'.$model_no.'"';
//echo $sql;
$rows = $dbb->query($sql);
$row = $rows->fetchArray();
$numRows = $row['count'];
//echo $numRows;
if($numRows != 0){
$flag = 0;
echo "error:this model no is already taken";
}else{
$sqlp = "INSERT INTO fisfis(model_no, image) values('$model_no','$image')";
if($dbb->exec($sqlp)){
echo "data inserted successfully\n";
}
else{
echo"error:\n";
echo "data not inserted \n";
echo"contact admin for details\n";
}
}
}
}
else{
echo"error:\n";
echo "data not inserted : data fields cannot be empty\n";
}
}
?>
this is very successfully inserting data in to my table (table name:fisfis)
DISPLAYING DATA
display.php
<form method="POST" enctype="multipart/form-data">
<p>Enter Barcode : <input type="text" name="search_model" id="search_model" /></p>
<!--<p><img src='image.php?id=<?php //echo $row['model_no'];?>'/></p>-->
<p><input type="submit" value="search" name="search" id="search"/></p>
</form>
display_include.php
<?php
$flag2 = 0;
$flag3 = 0;
class MyDB extends SQLite3
{
function __construct()
{
$this->open('../database.db');
}
}
$db = new MyDB();
if(isset($_POST["search"])){
$model_no = '';
$model_no = $_POST['search_model'];
if($model_no != ''){
$flag2 = 1;
}
if($flag2 == '1'){
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
}
else{
$dbb = new MyDB();
$sql = 'SELECT COUNT(*) as count FROM fisfis WHERE model_no = "'.$model_no.'"';
$rows = $dbb->query($sql);
$row = $rows->fetchArray();
$numRows = $row['count'];
echo $numRows;
if($numRows == 0){
echo 'sorry this model no is not exists';
echo '<br/>';
echo 'create new';
$flag2 = 1;
}else{
echo "this is exisists";
$flag3 = 1;
}
if($flag3 == 1){
$sqla = 'SELECT * FROM fisfis WHERE model_no = "'.$model_no.'"';
$result = $dbb->query($sqla);
while($row = $result->fetchArray(SQLITE3_ASSOC) ) {
echo "MODEL NO = ". $row['model_no'] ."\n";
$img = '\'<img src="'. $row['image'] .'" width="100" height="100"/>\'';
echo $img;
}
}
}
}
}
?>
the display part displaying all data other than blob ,what i have tried
1.try to echo the image inside the php script
$img = '\'<img src="'. $row['image'] .'" width="100" height="100"/>\'';
try to display image inside html tag
but this is not working,please help me to fix this,thanks in advance
My explaining is not good, so here is a show-and-tell. I made a repro so I wouldn't forget any necessary bits.
The database table is defined:
CREATE TABLE `imgrepro` (
`id` INTEGER NOT NULL,
`photo` BLOB,
PRIMARY KEY(`id`)
);
It is seeded with one row, id = 1, photo is NULL.
The POST block will insert the image into the BLOB column in the db. The rest of the script will fetch the image and the html will display it.
<?php
$db = new SQLite3("***********\stacktest.db");
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// insert photo
$photo = file_get_contents($_FILES['fname']['tmp_name']);
$query = $db->prepare("UPDATE imgrepro set photo = :photo where id = 1");
$query->bindValue(':photo',$photo,SQLITE3_BLOB);
$result = $query->execute();
}
// get photo if there is one
$rows = $db->query("SELECT * from imgrepro")->fetchArray(SQLITE3_ASSOC);
$showphoto="";
if (count($rows) > 0) {
$showphoto=base64_encode($rows['photo']);
}
$db->close();
?>
<!DOCTYPE html>
<head>
<title>Say Cheese!</title>
</head>
<!-- show the photo -->
<img alt="no photo yet" src="data:image/jpeg;base64,<?= $showphoto ?>" >
<form action="imgrepro.php" method="post" enctype="multipart/form-data">
<input type="file" name="fname" accept=".jpg">
<input type="submit">
</form>

How to know what is the pangkat of branches i am selected?

<label>Branches</label>
<br>
<script type="text/javascript">
<!--
document.write('<textarea class="form-control" style="resize:none;" id="area" rows="3" readonly="readonly"></textarea>')
function updateArea (e) {
document.getElementById('area').value = '';
for (var i=0; i<e.form.elements.length; i++){if (e.form.elements[i].type == 'checkbox' && e.form.elements[i].checked) {document.getElementById('area').value += e.form.elements[i].nextSibling.data; document.getElementById('area').value += '\n';}};
}
// -->
</script>
<p>
<div class="form-control" style="float:left;
height: 100px;
overflow: auto;">
<?php
$select = "SELECT * FROM branches WHERE access = 'User'";
if($result = mysqli_query($conn, $select)){
while ($row = mysqli_fetch_array($result)) {
$brid = $row['brid'];
?>
<input type="checkbox" name="brid[]" value="<?php echo $brid; ?>" onclick="updateArea(this)"><?php echo $brid; ?>
<input type="hidden" name="pangkat" value="<?php echo $pangkat; ?>">
<br>
<?php
}
}
?>
</div>
here is the code i am selecting brid from branches table i already know how to insert multiple rows of selected branches to database i want to know how to insert the pangkat of branches am i selecting.
<?php
require '../db/db.php';
$smsid = $_POST['smsid'];
$brid = $_POST['brid'];
$pangkat = $_POST['pangkat'];
$smssubject = $_POST['smssubject'];
$smscontent = $_POST['smscontent'];
$smsfrom = $_POST['smsfrom'];
for ($i = 0; $i<sizeof($brid); $i++ ){
$insert = $conn->query("INSERT INTO messages(sms_id,brid,pangkat,subject,message,from_brid,datesent)
VALUES('$smsid', '".$brid[$i]."','$pangkat',
'$smssubject','$smscontent','$smsfrom',NOW())");
echo "<script>alert('The Message is successfully sent');</script>";
echo "<script>window.location.assign('../load/amessages.php')</script>";
}?>
here is my action page to insert brid but the pangkat is always blank any help?
<?php
require '../db/db.php';
$smsid = $_POST['smsid'];
$brid = $_POST['brid'];
// $pangkat = $_POST['pangkat'];
$smssubject = $_POST['smssubject'];
$smscontent = $_POST['smscontent'];
$smsfrom = $_POST['smsfrom'];
for ($i = 0; $i<sizeof($brid); $i++ ){
$select = $conn->query(" SELECT * FROM branches WHERE brid = '".$brid[$i]."' ");
while($rows = mysqli_fetch_array($select)){
$pangkat = $rows['pangkat'];
$insert = $conn->query("INSERT INTO messages(sms_id,brid,pangkat,subject,message,from_brid,datesent)
VALUES('$smsid', '".$brid[$i]."','$pangkat',
'$smssubject','$smscontent','$smsfrom',NOW())");
echo "<script>alert('The Message is successfully sent');</script>";
echo "<script>window.location.assign('../load/amessages.php')</script>";
}
}?>
problem solved thanks!

How to stop resubmission of a form using Php?

I am making a web-application for Quiz competition. For the purpose, I wrote a php script which is processed by the same page. Now when I am adding scores and question numbers, the score is incremented or remain unchanged depending upon the previous answer if someone is refreshing the page. Now I googled the problem and found something like PRG.But this method works if the page is processed by other page (What I think ). Again, a friend of mine told me to use Javascript. But what if someone has turned Js off? Can't we have a solution in php itself. I tried session method also, but I did not fix the issue .
Please help me .
PHP Quiz script is here:
<?php
// starting session
session_start();
if (!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
else {
echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. Log out.</p>');
}
// $query = ;
//this get is taking level from index.php
if ( isset($_GET['level']))
{
$level = $_GET['level'];
}
else
{
$level = 'E';
}
//connecting to Data Base
require_once('connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (isset($_POST['submit']))
{
$level = $_POST['level'];
// $_SESSION['flag']
$answer = $_POST['answer'];
if ( !empty($answer))
{
$qid = $_POST['qid'];
$select = $_POST['select'];
$user_id = $_SESSION['user_id'];
$result = mysqli_query($dbc,"select * from question where qid = '$qid'")
or die("Error in connection.");
$row = mysqli_fetch_array($result);
if ( $row['ANSWER'] == $answer)
{
echo 'Your answer is correct.';
mysqli_query($dbc,"insert into user_question ( qid,user_id,answer_key) values ( '$select','$user_id',1)")
or die ("Error in updating values in user_question");
}
else
{
echo 'Your answer is incorrect.';
mysqli_query($dbc,"insert into user_question ( qid,user_id,answer_key) values ( '$select','$user_id',0)")
or die ("Error in updating values in user_question");
}
$answer = "";
}
else
{
echo 'You did not answer the previous question';
}
}
$user_id = $_SESSION['user_id'];
// $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
//Taking a random value from the list of question
$id_list = array();
// echo $user_id;
// echo $level;
$result = mysqli_query($dbc,"select * from question where lvl = '$level' and user_id != '$user_id' and qid not in ( select qid from user_question where user_id = '$user_id' )");
while ( ($row = mysqli_fetch_array($result)) )
{
if ( $row['user_id'] != $user_id)
array_push($id_list,$row['qid']);
}
// print_r($id_list);
//Whether user viewed all the questions
if ( empty($id_list))
{
echo 'Great, You have visited all the question, wait for more update ';
echo '<br>';
echo '❤ View Your Score<br />';
exit();
}
// Taking a random value after shuffling it
shuffle($id_list);
$select = $id_list[array_rand($id_list)];
$result = mysqli_query($dbc,"select * from question where qid='$select'");
// Showing the question
while ( ($row = mysqli_fetch_array($result)) )
{
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h3> <?php echo $row['sawal']; ?></h3>
<form method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="radio" name=" answer" value="A" ><?php echo $row['a']; ?><br>
<input type="radio" name=" answer" value="B" ><?php echo $row['b']; ?><br>
<input type="radio" name=" answer" value="C" ><?php echo $row['c']; ?><br>
<input type="radio" name=" answer" value="D" ><?php echo $row['d']; ?><br>
<input type="hidden" name = "qid" value="<?php echo $row['qid'] ?>">
<!-- <input type="hidden" name = "range" value="<?php $range ?>"> -->
<input type="hidden" name = "level" value="<?php echo $level ?>">
<input type="hidden" name = "select" value="<?php echo $select ?>">
<input type="submit" name="submit" value="ANSWER"/>
</form>
</body>
</html>
<?php
require_once('view_score.php');
}
?>
Edit:
I changed my code as Mat is suggested. But it is not allowing me to have different question from the table?
The revised php code is here:
<?php
// starting session
session_start();
if (!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
else {
echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. Log out.</p>');
}
// $query = ;
//this get is taking level from index.php
if ( isset($_GET['level']))
{
$level = $_GET['level'];
}
else
{
$level = 'E';
}
//connecting to Data Base
require_once('connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (isset($_POST['submit']))
{
$is_new_post = true;
if (isset($_SESSION["myform_key"]) && isset($_POST["myform_key"]))
{
if($_POST["myform_key"] == $_SESSION["myform_key"] ){
$is_new_post = false;
}
}
if($is_new_post){
$_SESSION["myform_key"] = $_POST["myform_key"];
$level = $_POST['level'];
// $_SESSION['flag']
$answer = $_POST['answer'];
if ( !empty($answer))
{
$qid = $_POST['qid'];
$select = $_POST['select'];
$user_id = $_SESSION['user_id'];
$result = mysqli_query($dbc,"select * from question where qid = '$qid'")
or die("Error in connection.");
$row = mysqli_fetch_array($result);
if ( $row['ANSWER'] == $answer)
{
echo 'Your answer is correct.';
mysqli_query($dbc,"insert into user_question ( qid,user_id,answer_key) values ( '$select','$user_id',1)")
or die ("Error in updating values in user_question");
}
else
{
echo 'Your answer is incorrect.';
mysqli_query($dbc,"insert into user_question ( qid,user_id,answer_key) values ( '$select','$user_id',0)")
or die ("Error in updating values in user_question");
}
$answer = "";
}
else
{
echo 'You did not answer the previous question';
}
}
}
$user_id = $_SESSION['user_id'];
// $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
//Taking a random value from the list of question
$id_list = array();
// echo $user_id;
// echo $level;
$result = mysqli_query($dbc,"select * from question where lvl = '$level' and user_id != '$user_id' and qid not in ( select qid from user_question where user_id = '$user_id' )");
while ( ($row = mysqli_fetch_array($result)) )
{
if ( $row['user_id'] != $user_id)
array_push($id_list,$row['qid']);
}
// print_r($id_list);
//Whether user viewed all the questions
if ( empty($id_list))
{
echo 'Great, You have visited all the question, wait for more update ';
echo '<br>';
echo '❤ View Your Score<br />';
exit();
}
// Taking a random value after shuffling it
shuffle($id_list);
$select = $id_list[array_rand($id_list)];
$result = mysqli_query($dbc,"select * from question where qid='$select'");
// Showing the question
while ( ($row = mysqli_fetch_array($result)) )
{
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h3> <?php echo $row['sawal']; ?></h3>
<form method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="radio" name=" answer" value="A" ><?php echo $row['a']; ?><br>
<input type="radio" name=" answer" value="B" ><?php echo $row['b']; ?><br>
<input type="radio" name=" answer" value="C" ><?php echo $row['c']; ?><br>
<input type="radio" name=" answer" value="D" ><?php echo $row['d']; ?><br>
<input type="hidden" name = "qid" value="<?php echo $row['qid'] ?>">
<!-- <input type="hidden" name = "range" value="<?php $range ?>"> -->
<input type="hidden" name = "level" value="<?php echo $level ?>">
<input type="hidden" name = "select" value="<?php echo $select ?>">
<input type="hidden" name="myform_key" value="<?php echo md5("CrazyFrogBros"); ?>" />
<input type="submit" name="submit" value="ANSWER"/>
</form>
</body>
</html>
<?php
require_once('view_score.php');
}
?>
I tried session method also, but I did not fix the issue
I don't know how you code it but you can try this:
1. Set a session token with unique hash value e.g.
$_SESSION['formtoken'] = sha1(uniqid('', true));
include it in your form (input hidden) value = $_SESSION['formtoken']
everytime the user submit the form reset the $_SESSION['formtoken'] value

PHP, AJAX Auto fill input fields from HTML select?

I have been trying for a while to find out a correct method of pulling information from a database based on the initial text
selected on a html drop down menu.
Here is my code:
<html>
<head>
</head>
<script src="testjs.js"></script>
<?php
$host = "";
$username = "";
$password = "";
$database = "";
mysql_connect($host, $username, $password);
mysql_select_db($database);
?>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<?php
$Query = mysql_query("SELECT * FROM population");
while ($Rows = mysql_fetch_array($Query))
{
$ID = $Rows['ID'];
$Pop = $Rows['Pop'];
$UniqueID = $Rows['uid'];
echo "<option value=\"$UniqueID\">$Pop</option>";
}
?>
</select>
</form>
<br>
<p>DB ID <input type="text" id="ids" name="ID" ></p>
<p>Population <input type="text" id="content" name="contet" ></p>
<p>Unique ID <input type="text" id="uid" name="uid" ></p>
<div id="GetInformation"><b>Person info will be listed here.</b></div>
</body>
</html>
test.js contains:
function showUser(str)
{
if (str=="")
{
document.getElementById("GetInformation").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("GetInformation").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
Get user contains:
<?php
$q=$_GET["q"];
$con = mysql_connect('', '', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("DropDown", $con);
$sql="SELECT * FROM population WHERE uid = '".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$ID = $row['ID'];
$Pop = $row['Pop'];
$UID = $row['uid'];
?>
<script type="text/javascript">
var ids = '<?php echo json_encode($ID); ?>';
var content = '<?php echo json_encode($Pop); ?>';
var uid = '<?php echo json_encode($UID); ?>';
</script>
<?php }
mysql_close($con);
?>
try changing
while($row = mysql_fetch_array($result))
{
$ID = $row['ID'];
$Pop = $row['Pop'];
$UID = $row['uid'];
?>
<script type="text/javascript">
var ids = '<?php echo json_encode($ID); ?>';
var content = '<?php echo json_encode($Pop); ?>';
var uid = '<?php echo json_encode($UID); ?>';
</script>
<?php }
to
while($row = mysql_fetch_array($result))
{
$ID = $row['ID'];
$Pop = $row['Pop'];
$UID = $row['uid'];
echo $ID . ' - ' . $Pop . ' - ' . $UID;
}
this should work. but there are better ways as they give you more access later on in your client side. e.g. send a JSON object back, a quick example would be:
$info = array();
while($row = mysql_fetch_array($result))
{
$ID = $row['ID'];
$Pop = $row['Pop'];
$UID = $row['uid'];
$info[] = array( 'id' => $ID, 'pop' => $Pop, 'uid' => $UID );
}
echo json_encode($info);
and your JS would be something like :
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("GetInformation").innerHTML += data[i].id + ' - ' + data[i].pop + ' - ' + data[i].uid;
}
}
NOTE: if you are working with a browser that doesn't include the JSON library you need to load http://www.json.org/js.html . Also your AJAX/DOM changes can become much simpler if you want to use jQuery

Categories