updating sql table for selected check box values - php

I dynamically create table rows with checkboxes. Check a few of them and then perform and update query on the selected ones. But the problem I face is that only the first selected record gets updated even though I have used foreach loop.
Following is the code.
<?php
$checkbox = $_POST['pr'];
$year = $_POST['promoteyearselect1'];
$semester = $_POST['promotesemselect1'];
# $db = mysql_connect("abc", "abc", "");
mysql_select_db("abc");
foreach($checkbox as $value){
if(isset($checkbox)){
if(($semester%2)==0) {
$strSQL = "UPDATE student SET year='".++$year."', semester='".++$semester."' WHERE enrollment='".$value."'";
$rs = mysql_query($strSQL);
if($rs){
echo 'Promotion Successful';
header("location:page1.php");
echo '<script> alert("Promotion Successful");</script>';
}
else echo "Sorry, but that did not work. ";
}
else{
$strSQL = "UPDATE student SET semester=".++$semester."' WHERE enrollment='".$value."'";
$rs = mysql_query($strSQL);
if($rs){
echo 'Promotion Successful';
header("location:page1.php");
echo '<script> alert("Promotion Successful");</script>';
}
else echo "Sorry, but that did not work. ";
}
}
}
mysql_close($db);
?>
Even though I use the foreach loop to get through the array of checkboxes, still only the first checked record gets updated.
This is the html part
<div class="dropdown dropdown-dark">
<select name="promoteyearselect1" id="promoteyearselect1" class="dropdown-select" onfocus="showhidephdmenu()" form="promotionform" required>
<option value="">Select an option</option>
<div id="yearselect1">
<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
<option value="4">4th</option>
<option value="5">5th</option>
</div>
</option>
</select>
</div>
<div class="dropdown dropdown-dark">
<select name="promotesemselect1" id="promotesemselect1" class="dropdown-select" form="promotionform" required>
<option value="">Select an option</option>
<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
<option value="4">4th</option>
<option value="5">5th</option>
<option value="6">6th</option>
<option value="7">7th</option>
<option value="8">8th</option>
<option value="9">9th</option>
<option value="10">10th</option>
</select>
</div>
<button id="promotego" class="login-button" style=" position:relative; padding: 0 0 0; " onclick="getpromotestudents()"></button>
</div>
<form id="promotionform" action="promotestudents.php" method="POST">
<div id="promoteresults">
The results will show up here..!!
</div>
<div style=" position:relative; margin-top:10px; padding-left:44%;">
<input type="submit" value="Promoted" class="button black"></input>
Passed Out
</div>
</form>
This is the PHP that gets the records and generates checkboxes.
$i=1;
while($r = mysql_fetch_array($rs)){
echo "<tr>";
echo "<td class='promotetabledata'>".$r[7]."</td>";
echo "<td class='promotetabledata'>".$r[6]."</td>";
echo "<td class='promotetabledata'><input type='checkbox' name='pr[]' value='".$r[7]."'/></td>";
echo "</tr>";
$i++;
}

Here is the modified code that finally worked for me, I added spaces in the if($semester % 2 != 0)
<?php
$checkbox = $_POST['pr'];
$year = $_POST['promoteyearselect1'] + 1 ;
$semester = $_POST['promotesemselect1'] + 1;
$con = mysqli_connect("localhost","root","","university") or die("Error " . mysqli_error($con));
foreach($checkbox as $value){
if(isset($checkbox)){
// echo $value;
if( $semester % 2 != 0) {
// echo $value;
$strSQL = "UPDATE student SET year='".$year."', semester='".$semester."' WHERE enrollment='".$value."'";
$rs = mysqli_query($con, $strSQL);
if($rs){
echo 'Promotion Successful';
header("location:page1.php");
echo '<script> alert("Promotion Successful");</script>';
}
else echo "Sorry, but that did not work. ";
}
else{
$strSQL = "UPDATE student SET semester='".$semester."' WHERE enrollment='".$value."'";
$rs = mysqli_query($con, $strSQL);
if($rs){
echo 'Promotion Successful';
header("location:page1.php");
echo '<script> alert("Promotion Successful");</script>';
}
else echo "Sorry, but that did not work. ";
}
}
}
mysqli_close($con);
?>

I didn't found any checkbox with name 'pr' in your code..If there is any ..please make it an array and try
like <input type="checkbox" name="pr[]">

Related

Undefined index in php inside selected drop down

this is the undefined error that i got
the update is working. but after i clicked the submit button, the selected dropdown gave me this error.
$row=array();
if (isset($_GET['typeid'])) {
$sql = "SELECT * FROM vehicletype WHERE id_vehicleType=" . $_GET['typeid'];
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
}
// update record
if(isset($_POST['submit'])){
$id = mysqli_real_escape_string($link,$_POST['idtype']);
$type = mysqli_real_escape_string($link, $_POST['type']);
$status = mysqli_real_escape_string($link, $_POST['status']);
$update = mysqli_real_escape_string($link, $_SESSION['idinfostaf']);
$result = mysqli_query($link, "UPDATE vehicletype SET vehicle_Type='$type', status_vehicleType='$status', updateby_vehicleType='$update' WHERE id_vehicleType=".$id);
if ($result) {
$success = "Record updated successfully!";
}
else {
$error = "Error updating record...";
}
}
i put the php code and html on the same page..below is the html
<div class="form-group">
<label>Choose Vehicle Type Status</label>
<select class="form-control" name="status" required class="form-control" value="<?php if(isset($row['status_vehicleType'])){ echo $row['status_vehicleType'];} ?>">
<option value="">Select Vehicle Type</option>
<option
value="1" <?php if ($row['status_vehicleType']==$_GET["typeid"]) { echo 'selected="selected"' ;} ?> >Enabled</option>
<option
value="0" <?php if ($row['status_vehicleType']== $_GET["typeid"]) { echo 'selected="selected"' ;} ?> >Disabled</option>
</select>
<hr>
<button type="submit" name="submit" class="btn btn-info">Submit </button>
<span class="text-success"><?php if (isset($success)) { echo $success; } ?></span>
<span class="text-danger"><?php if (isset($error)) { echo $error; } ?></span>
i used the typeid to carry the values.
Try this:
<select value="<?php if(isset($row['status_vehicleType'])){ echo $row['status_vehicleType'];} ?>">
<option value="">Select Vehicle Type</option>
<option value="1" <?php
if(isset($row['status_vehicleBrand'])) {
if ($row['status_vehicleBrand']==$_GET["typeid"]) {
echo 'Selected' ;
}
} ?> >Enabled</option>
<option value="0" <?php
if(isset($row['status_vehicleBrand'])) {
if ($row['status_vehicleBrand']==$_GET["typeid"]) {
echo 'Selected' ;
}
} ?> >Disabled</option>
</select>

How to keep form items selected after post request.Using onchange

I have a problem when submit form value from the second select don't show. Can someone explain me what I'm doing wrong because in new in this (maybe is because i use onchange event). Thanks in advance.
index.php
<?php
include("includes/conn.php");
$sql = "SELECT * FROM opstina";
$result = $conn->query($sql);
if($result->num_rows > 0){
$opstineArr = array();
while($row = $result->fetch_assoc()){
$opstineArr[] = $row;
}
}
if(isset($_POST["addNesto"])){
$opstine = $_POST["opstine"];
$ime = $_POST["ime"];
if(isset($opstine)){
if(empty($opstine)){
$error["opstine"] = "izaberite opstinu";
}
}
$naselja = $_POST["naselja"];
if(isset($naselja)){
if(empty($naselja)){
$error["naselja"] = "izaberite naselje";
}
}
if(isset($ime)){
if(empty($ime)){
$error["ime"] = "izaberite ime";
}
}
if(count($error) == 0){
echo 2222;
}
}
include("includes/header.php");
?>
<form action="" method="POST">
<select name="opstine" class="form-control" id="select_id" onchange="getNaselja(this.value)">
<option>..Izaberite Opstinu..</option>
<?php foreach($opstineArr as $key => $opstina): ?>
<option value="<?php echo $opstina['OpstinaID']; ?>" <?php if(isset($opstine) && $opstine==$opstina['OpstinaID']) echo "selected"; ?> ><?php echo $opstina['NazivOpstine']; ?></option>
<?php endforeach; ?>
</select>
<?php if(isset($error["opstine"])) echo $error["opstine"]; ?>
<p>
<select name='naselja' id='naseljeLista' class='form-control' style='margin-top:10px;'>
</select>
<span><?php if(isset($error["naselja"])) echo $error["naselja"]; ?></span>
</p><br>
<input type="text" name="ime" value="<?php if(isset($ime)) echo $ime; ?>" class="form-control col-md-7 col-xs-12"><?php if(isset($error["ime"])) echo $error["ime"]; ?><br><br>
<input type="submit" name="addNesto" class="btn btn-sm btn-success">
</form>
<?php include("includes/footer.php"); ?>
getNaselja.php
global $conn;
include("includes/conn.php");
if(!empty($_POST["opstina_id"])){
$opstinaID = $_POST["opstina_id"];
$sql1 = "SELECT * FROM naselje WHERE OpstinaID=".$opstinaID;
$result1 = $conn->query($sql1);
if($result1->num_rows > 0){
$naseljaArr = array();
while ($one = $result1->fetch_assoc()) {
$naseljaArr[] = $one;
}
}
echo "<option value=''>---Izaberite naselje---</option>";
foreach ($naseljaArr as $key => $value) {
if(isset($_POST["naselja"]) && $value["NaseljeID"]==$_POST["naselja"]){
echo "<option value='".$value['NaseljeID']."' selected='selected' style='display:block;'>".$value['NazivNaselja']."</option>";
}else{
echo "<option value='".$value['NaseljeID']."'>".$value['NazivNaselja']."</option>";
}
}
}
footer.php
<script>
function getNaselja(val){
$.ajax({
type: 'POST',
url: 'getNaselja.php',
data: 'opstina_id='+val,
success: function(data){
$('#naseljeLista').html(data);
console.log(data);
}
});
}
</script>
example of form after submit on index.php
When I choose from first select my data on the console looks like:
<option value=''>---Izaberite naselje---</option>
<option value='4610'>Beška</option>
<option value='4611'>Inđija</option>
<option value='4612'>Jarkovci</option>
<option value='4613'>Krčedin</option>
<option value='4614'>Ljukovo</option>
<option value='4615'>Maradik</option>
<option value='4616'>Novi Karlovci</option>
<option value='4617'>Novi Slankamen</option>
<option value='4618'>Slankamenački Vinogradi</option>
<option value='4619'>Stari Slankamen</option>
<option value='4620'>Čortanovci</option>

Database driven select box being empty on submit

I am trying to submit a form value in a database with php. In form a select box value comes from database.
<?php include_once 'header.php';
$sql="SELECT uid,name FROM emitra_basic where block='$user'";
$result = $conn->query($sql);
//form validion
if(isset($_POST['submit']))
{
$eid =$_POST["eid"];
if($eid=="blank")
{
$flag=1;
$idErr="please Select E-MITRA";
}
$miatm =trim($_POST["miatm"]);
if(empty($miatm) || !preg_match("/^[a-zA-Z0-9 ]*$/",$miatm)) {
$flag=1;
$miErr="Please Enter Valid Id";
}
.............like this
if($flag==0)
{
$sqll="insert into **********";
}
//my form is
<form id="basic" method="post" name="basic">
<select class="select-style gender" name="eid">
<option value="blank">Please Select E-MITRA ID</option>
<?php
while($row=mysqli_fetch_array($result))
{
?>
<option value="<?php echo $row['uid']; ?>"><?php echo $row['uid']." (" . $row['name'] .")"; ?></option>
<?php
}
?>
</select>
<p class="contact"><label for="bid">Micro-ATM Serial No</label></p>
<input type="text" name="miatm" value ="<?php if (isset($miatm)) echo $miatm; ?>" /> <?php echo $miErr; ?>
<p class="contact"><label for="bid">Micro-ATM TID No</label></p>
<input type="text" name="tid" value ="<?php if (isset($tid)) echo $tid; ?>" /> <?php echo $tiErr; ?>
<input class="buttom" name="submit" id="submit" value="Add Me" type="submit">
Its seems Ok.but when i tried to submit the form if some of one field remain empty then its show blank value in select box.
how can i remain the same selected value in select box even if textbox remain empty.
You need to retain the value of drop down after form submit.
User selected attribute of select option.
<?php
if (isset($_POST['submit'])) {
$eid =$_POST["eid"];
if ($eid=="blank") {
$flag=1;
$idErr="please Select E-MITRA";
}
}
$sql="SELECT uid,name FROM emitra_basic where block='$user'";
$result = $conn->query($sql);
?>
<select class="select-style gender" name="eid">
<option value="blank">Please Select E-MITRA ID</option>
<?php
while($row=mysqli_fetch_array($result)) {
$selected = (isset($_POST["eid"]) && $_POST["eid"] == $row['uid']) ? 'selected="selected"' : '';
?>
<option value="<?php echo $row['uid']; ?>" <?php echo $selected;?>><?php echo $row['uid']." (" . $row['name'] .")"; ?></option>
<?php
}
?>
</select>
You need to use selected="" or selected="selected" after submission in your select tag as a attribute as:
<?
$sql="SELECT uid,name FROM emitra_basic where block='$user'";
$result = $conn->query($sql);
?>
<select class="select-style gender" name="eid">
<option value="blank">Please Select E-MITRA ID</option>
<?php
while($row=mysqli_fetch_array($result))
{
$selected = ((isset($_POST["eid"]) && $_POST["eid"] == $row['uid']) ? 'selected=""' : '');
?>
<option <?=$selected?> value="<?php echo $row['uid']; ?>"><?php echo $row['uid']." (" . $row['name'] .")"; ?></option>
<?php
}
if(isset($_POST['submit']))
{
$eid = $_POST["eid"];
if($eid=="blank")
{
$flag=1;
$idErr="please Select E-MITRA";
}
?>
</select>
Side Note:
In your question ist two lines are not inside the php, i hope this is type error.

phpmyadmin shows 8 rows but only the 1st is displayed on the page

<h5>Student-sem</h5>
<p>
<select required>";
<option value="">Please select</option>
<?php
$query = "SELECT distinct `sem_no` FROM `course`,`student_info` WHERE course.c_id=student_info.c_id and `s_id` = '$s_id' ORDER BY `sem_no`";
if($query_run = mysql_query($query)) {
while ($arow = mysql_fetch_array($query_run)){
$asem = $arow['sem_no'];
echo "<option >" .$asem. "</option>" ;
}
}
else{
echo mysql_error();
}
?>
</select>
</p>
the query returns 8 values in phpmyadmin bt only the 1st value is displayed with this code

Refine Results with dropdown box

I would like to refine the results of mysql query using dropdown boxes... live site is here:
http://www.halfwayenterprises.com/search/tyrell.php
<form name="doublecombo" action="" method="POST">
<label for="status">Status:</label>
<label for="current">
<input class="radio_style" id="current" checked="checked" name="status" type="radio" value="current">
Current
</label>
<label for="obsolete">
<input class="radio_style" id="obsolete" name="status" type="radio" value="obsolete">
Obsolete
</label>
<label for="both">
<input class="radio_style" id="both" name="status" type="radio" value="both">
ALL
</label>
<br /><br />
<select name="category" size="1" onChange="redirect(this.options.selectedIndex)">
<option value="null">Category</option>
<option value="asset management">Asset Management</option>
<option value="budget">Budget/Finance</option>
<option value="central office">Central Office</option>
<option value="disposal">Disposal</option>
</select>
<select name="subcategory">
<option value="null">Sub-Category</option>
<option value="Portfolio">Portfolio</option>
<option value="Pricing">Pricing</option>
<option value="Valuation">Valuation</option>
<option value="Disposal">Disposal</option>
</select>
<input name="submitted" type="submit" value="GO">
<br />
Seach for: <input type="text" name="find" /> in
<Select NAME="field">
<Option id="title" VALUE="title">Title</option>
<Option id="poc" VALUE="poc">POC</option>
<Option id="purpose" VALUE="purpose">Purpose</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input name="submitted" type="submit" value="GO">
</form>
<select name="filter1">
<option value="az">Sort by A-Z</option>
<option value="date">Sort by Date</option>
</select>
<select name="filter2">
<option value="office">Sort by Office</option>
<option value="p">P</option>
<option value="pt">PT</option>
<option value="pf">PF</option>
</select>
<select name="filter3">
<option value="mandatory">Mandatory</option>
<option value="nonmandatory">Non-Mandatory</option>
<option value="combined">Combined</option>
</select>
</form>
</p>
<script>
<!--
/*
Double Combo Script Credit
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free JavaScripts here!
*/
var groups=document.doublecombo.category.options.length
var group=new Array(groups)
for (i=0; i<groups; i++)
group[i]=new Array()
group[0][0]=new Option("Sub Category")
group[1][0]=new Option("Portfolio")
group[1][1]=new Option("Pricing")
group[1][2]=new Option("Valuation")
group[3][0]=new Option("Central Office")
group[4][0]=new Option("Disposal")
var temp=document.doublecombo.subcategory
function redirect(x){
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null
for (i=0;i<group[x].length;i++){
temp.options[i]=new Option(group[x][i].text,group[x][i].value)
}
temp.options[0].selected=true
}
function go(){
location=temp.options[temp.selectedIndex].value
}
//-->
</script>
<?
mysql_connect("localhost", "name", "pasword") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
if(isset($_POST["submitted"])){
$status = $_POST['status'];
$category = $_POST['category'];
$subcategory = $_POST['subcategory'];
echo '<div class="status_div">';
if($status=='current')
{
echo "<h2>Results</h2><p>";
$res = mysql_query("SELECT * FROM material WHERE status='$status' AND category='$category' AND subcategory='$subcategory' ORDER BY `documentid` ASC");
while ($row = mysql_fetch_assoc($res)) {
echo '<div class="current">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
} if ($status=='obsolete')
{
echo "<h2>Results</h2><p>";
$res = mysql_query("SELECT * FROM material WHERE status='$status' AND category='$category' ORDER BY `documentid` ASC ");
while ($row = mysql_fetch_assoc($res)) {
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '<br>';
}
} if ($status=='both')
{
echo "<h2>Results</h2><p>";
$res = mysql_query("SELECT * FROM material WHERE status1='both' AND category='$category' ORDER BY `documentid` ASC");
while ($row = mysql_fetch_assoc($res)) {
echo '<div class="">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
}
echo '</div>';
}
$field = #$_POST['field'] ;
$find = #$_POST['find'] ;
$searching = #$_POST['searching'] ;
$status = $_POST['status'];
//This is only displayed if they have submitted the form
if ($searching =="yes")
{
echo "<h2></h2><p>";
//If they did not enter a search term we give them an error
if ($find == "")
{
echo "<a href='tyrell.htm'>Return</a>";
exit;
}
// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
if($status=='current'){
$data = mysql_query("SELECT * FROM material WHERE status='$status' AND lower($field) LIKE'%$find%' LIMIT 0,30");
while ($row = mysql_fetch_assoc($data)) {
echo '<div class="current">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
}
if ($status=='obsolete'){
$data = mysql_query("SELECT * FROM material WHERE status='$status' AND lower($field) LIKE'%$find%' LIMIT 0,30");
while ($row = mysql_fetch_assoc($data)) {
echo '<div class="obsolete">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
} if ($status=='both'){
$data = mysql_query("SELECT * FROM material WHERE status1='both' AND lower($field) LIKE'%$find%' LIMIT 0,30");
while ($row = mysql_fetch_assoc($data)) {
echo '<div class="">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>
<p align="center"><font face="arial" size="-2">This free script provided by</font><br>
<font face="arial, helvetica" size="-2"><a href="http://javascriptkit.com">JavaScript
Kit</a></font></p>'
</body>
</html>
I have can't think of how to use the drop downs without having a submit button
I think I know what you need...
Use jquery to submit form on you page.
Something like this...
$("submitted").click(function() {
var url = "file.php";
$.ajax({
type: "POST",
url: url,
data: $("doublecombo").serialize(), // serializes the form's elements.
success: function(data)
{
// populate box or div with your result
}
});
return false; // avoid reload.
});
//PHP part
if($_POST['someField']){
$result = //Do query and staff and return any type of resposne you will handle in ajax success
echo $result;
exit;
}
You can use JavaScript to manipulate the content of the dropdown list. All you need is to do is bind the click even on the radio button and when one of them gets clicked, use an Ajax call to retrieve the information from your SQL database and modify the content of your selectbox.
EDIT
Here's some code you can add to your page:
$('form[name=doublecombo] input').change(function() {
$('form[name=doublecombo]').submit();
});
Note that change might not work. If it doesn't, try using click instead.

Categories