I am doing Add, Update and Delete in Php.
Everything is working fine but My Update query is not working.
Can I know, where i am going wrong in Update query?
Here is my update.php file code..
<?php
include('connection.php');
$ID = $_REQUEST['Student_Id'];
$result = mysql_query("select* from tblstudent where Student_Id='".$ID."'");
while($oldvalue= mysql_fetch_array($result))
{
$oldname=$oldvalue['Student_Name'];
$oldgender=$oldvalue['Gender'];
$olddob=$oldvalue['DOB'];
$oldaddress=$oldvalue['Address'];
$oldmobileno=$oldvalue['Phone'];
$olddivision=$oldvalue['Division'];
$oldclass=$oldvalue['Class'];
$oldemail=$oldvalue['Email_Id'];
}
if(isset ($_POST['submit']))
{
$update = $_POST['submit'];
if($update)
{
$newname=$_POST['Student_Name'];
$newgender=$_POST['Gender'];
$newdob=$_POST['DOB'];
$newaddress=$_POST['Address'];
$newmobileno=$_POST['Phone'];
$newdivision=$_POST['Division'];
$newclass=$_POST['Class'];
$newemail=$_POST['Email_Id'];
/* UPDATE QUERY */
mysql_query("UPDATE tblstuent SET Student_Name='$newname', Gender='$newgender', DOB='$newdob', Address='$newaddress', Phone='$newmobileno', Division='$newdivision', Class='$newclass', Email_Id='$newemail'
WHERE id='$ID'");
header('location:index.php');
}
}
?>
<body>
<form action="update.php" method="post">
<fieldset>
<legend>Personal Information</legend><br/>
<div class="studentname"><label>Student Name :</label><input type="text" name="newstudentname" id="studentnameId" value="<?php echo $oldname ?>" placeholder="Enter Name" size="30px" /></div><br/>
<div class="gender">
<label>Gender :</label>
<input type="radio" name="type" value="Male" <?php echo ($oldgender == 'Male') ? 'checked' : ''; ?> /> Male
<input type="radio" name="type" value="Female" <?php echo ($oldgender == 'Female') ? 'checked' : ''; ?>/> Female<br />
</div> <br/>
<div class="dob"><label>Date of Birth :</label><input type="text" name="dob" id="dobId" value="<?php echo $olddob ?>" placeholder="Enter DOB format Year-Month-DaY" size="30px" /></div><br/>
<div class="address"><label class="addresschild">Address : </label><textarea rows="4" cols="21" name="address" id="addressId" value="" placeholder="Enter Your Address"><?php echo $oldaddress ?></textarea></div><br/>
<div class="mobileno"><label>Parent's Mobile No : </label><input type="text" name="mobileno" id="mobilenoId" value="<?php echo $oldmobileno ?>" placeholder="Enter Parent's Mobile No" size="30px" /></div><br/>
<div class="selectdivision">
<label>Divison :</label>
<select id="divisiondropdownId" name="divisiondropdown">
<option value="0">Select Division</option>
<option value="A"<?php if($olddivision=="A") echo 'selected="selected"'; ?> >A</option>
<option value="B"<?php if($olddivision=="B") echo 'selected="selected"'; ?> >B</option>
<option value="C"<?php if($olddivision=="C") echo 'selected="selected"'; ?> >C</option>
</select>
</div><br/>
<div class="selectclass">
<label>Class :</label>
<select id="classdropdownId" name="classdropdown">
<option value="0">Select Class</option>
<option value="First"<?php if($oldclass=="First") echo 'selected="selected"'; ?>>First</option>
<option value="Second"<?php if($oldclass=="Second") echo 'selected="selected"'; ?>>Second</option>
<option value="Third"<?php if($oldclass=="Third") echo 'selected="selected"'; ?>>Third</option>
<option value="Fourth"<?php if($oldclass=="Fourth") echo 'selected="selected"'; ?>>Fourth</option>
<option value="Fifth"<?php if($oldclass=="Fifth") echo 'selected="selected"'; ?>>Fifth</option>
<option value="Sixth"<?php if($oldclass=="Sixth") echo 'selected="selected"'; ?>>Sixth</option>
<option value="Seventh"<?php if($oldclass=="Seventh") echo 'selected="selected"'; ?>>Seventh</option>
<option value="Eighth"<?php if($oldclass=="Eighth") echo 'selected="selected"'; ?>>Eighth</option>
<option value="Nineth"<?php if($oldclass=="Nineth") echo 'selected="selected"'; ?>>Nineth</option>
<option value="Tenth"<?php if($oldclass=="Tenth") echo 'selected="selected"'; ?>>Tenth</option>
</select>
</div><br/>
<div class="emailid"><label>Email-Id : </label><input type="text" name="emailid" id="emailId" value="<?php echo $oldemail ?>" placeholder="Enter your Email-id" size="30px" /></div><br/>
<div id="submit1">
<input class="btnsubmit" type="submit" name="submit" id="submit" value="Submit" />
<input class="btnreset" type="reset" name="reset" id="submit" value="Reset" />
</div><br/>
</fieldset>
</form>
</body>
Thank you
Rahul Barge
I have an example with PDO and prepared statements for you. Also if I was you I would start learning PDO with prepared statements. MySQL is deprecated and can get you into trouble.
This example is using Student_Id as auto increment and primary
SelectStudentPage.php
<!DOCTYPE>
<html>
<head>
<title>Students</title>
</head>
<body>
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "Studentsdb";
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
//prepared statement with PDO to query the database
$stmt = $db->prepare("SELECT * FROM tblstudent ");
$stmt->execute();
?>
<?php //start of the while loop ?>
<?php while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { ?>
<table border="1" style="table-layout: fixed; width: 1080px;">
<br>
<tr>
<th style="width:125px">STUDENT ID</th>
<th style="width:125px">STUDENT NAME</th>
<th style="width:100px">GENDER</th>
<th style="width:100px">DOB</th>
<th style="width:250px">ADDRESS</th>
<th style="width:100px">PHONE</th>
<th style="width:100px">DIVISION</th>
<th style="width:100px">CLASS</th>
<th style="width:250px">EMAIL ID</th>
</tr>
<tr style="width:25px">
<?php $id = $row['Student_Id'];?>
<?php echo "<td> <a href='StudentUpdateForm.php?Student_Id=$id'>$id</a></td>"?>
<td><?php echo $row['Student_Name']; ?></td>
<td><?php echo $row['Gender']; ?></td>
<td><?php echo $row['DOB']; ?></td>
<td><?php echo $row['Address']; ?></td>
<td><?php echo $row['Phone']; ?></td>
<td><?php echo $row['Division']; ?></td>
<td><?php echo $row['Class']; ?></td>
<td><?php echo $row['Email_Id']; ?></td>
</tr>
</table>
<?php } //end of the while loop?>
</body>
</html>
StudentUpdateForm.php
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "Studentsdb";
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$id=$_GET['Student_Id'];
$result = $db->prepare("SELECT * FROM tblstudent Where Student_Id=:Student_Id");
$result->bindParam(':Student_Id', $id);
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<!DOCTYPE>
<html>
<head>
<title>Example Update Form</title>
</head>
<body>
<form action="UpdateProcess.php" method="post">
<legend>Personal Information</legend><br>
<div>
<label>Student Id :<label><input name="Student_Id" type="text" value=
"<?php print($row['Student_Id']) ?>">
</div><br>
<div>
<label>Student Name :</label><input name="Student_Name" type="text" value=
"<?php print($row['Student_Name']) ?>">
</div><br>
<div>
<label>Gender :</label>
<select name ="Gender" style="width: 149px" >
<option value <?php if ($row['Gender']==1){ print('selected');} ?> ="Male">Male</option>
<option value <?php if ($row['Gender']==2){ print('selected');} ?> ="Female">Female</option>
</select>
</div><br>
<div>
<label>Date of Birth :</label><input name="DOB" type="text" value=
"<?php print($row['DOB']) ?>">
</div><br>
<div>
<label>Address :</label><textarea name="Address"><?php echo $row['Address']; ?></textarea><br>
</div><br>
<div>
<label>parents mobile no:</label><input name="Phone" type="text"value=
"<?php print($row['Phone']) ?>">
</div><br>
<div>
<label>Divison :</label><br>
<select name ="Division" style="width: 149px" >
<option value <?php if ($row['Division']==1){ print('selected');} ?> ="A">A</option>
<option value <?php if ($row['Division']==2){ print('selected');} ?> ="B">B</option>
<option value <?php if ($row['Division']==3){ print('selected');} ?> ="C">C</option>
</select>
</div><br>
<div>
<label>Class :</label><br>
<select name ="Class" style="width: 149px" >
<option value <?php if ($row['Class']==1){ print('selected');} ?> ="First">First</option>
<option value <?php if ($row['Class']==2){ print('selected');} ?> ="Second">Second</option>
<option value <?php if ($row['Class']==3){ print('selected');} ?> ="Third">Third</option>
</select>
</div><br>
<div>
<label>Email id :</label><input name="Email_Id" type="text" value=
"<?php print($row['Email_Id']) ?>">
</div><br>
<div id="submit1">
<input class="btnsubmit" id="submit" name="submit" type="submit"
value="Update"> <input class="btnreset" id="submit" name="reset"
type="reset" value="Reset">
</div><br>
</form>
</body>
</html>
<?php } ?>
UpdateProcess.php
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "Studentsdb";
try{
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$sql = 'UPDATE tblstudent SET Student_Id=:Student_Id, Student_Name=:Student_Name, Gender=:Gender, DOB=:DOB, Address=:Address, Phone=:Phone, Division=:Division, Class=:Class, Email_Id=:Email_Id WHERE Student_Id=:Student_Id';
$stmt = $db->prepare($sql);
$stmt->bindParam(':Student_Id', $_POST['Student_Id'], PDO::PARAM_STR);
$stmt->bindParam(':Student_Name', $_POST['Student_Name'], PDO::PARAM_STR);
$stmt->bindParam(':Gender', $_POST['Gender'], PDO::PARAM_STR);
$stmt->bindParam(':DOB', $_POST['DOB'], PDO::PARAM_STR);
$stmt->bindParam(':Address', $_POST['Address'], PDO::PARAM_STR);
$stmt->bindParam(':Phone', $_POST['Phone'], PDO::PARAM_STR);
$stmt->bindParam(':Division', $_POST['Division'], PDO::PARAM_STR);
$stmt->bindParam(':Class', $_POST['Class'], PDO::PARAM_STR);
$stmt->bindParam(':Email_Id', $_POST['Email_Id'], PDO::PARAM_STR);
$stmt->execute();
echo $stmt->rowCount() . " record Updated successfully.";
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
echo "<a href=http://localhost/students/SelectStudentPage.php>Go to Grid view Results page</a>";
?>
along with having typo,you used
$ID = $_REQUEST['Student_Id'];
in your code i dont found any element with id 'Student_Id' in your form, so there will be no value in $ID, and no update will be done.
Sorry for not commenting. I don't have 50 points yet.
I saw few errors in your query.
table name. in select query it's tblstudent and in update query its tblstuent
'$newname' is better to concatinate like this. '".$newname."'. and this should do for all variables.
No STUDENT_ID in your code. So add it as a hidden field.
Make sure column names spelled in the same way as it is in the table. simple/capital and spellings.
if you are updating same table than you should pass Student_Id instead of id in below query,
mysql_query("UPDATE tblstuent SET Student_Name='$newname', Gender='$newgender', DOB='$newdob', Address='$newaddress', Phone='$newmobileno', Division='$newdivision', Class='$newclass', Email_Id='$newemail'
WHERE id='$ID'");
or You had set wrong table name tblstuent , it should be tblstudent if you are updating same table.
Try This:
Student_Name='$newname',
put $newname in double quotes like this.
Student_Name="$newname",
In your query check data type of all column then as data type you need to set column value with quotes if datatype like string,date. otherwise not need to set quotes for good practice. and in your update query you write table name wrong so first update this. after check
$sql = "SELECT * FROM table WHERE id = '$id' " ;
while($oldvalue= mysql_fetch_array($result))
{
$oldname=$oldvalue['Student_Name'];
$oldgender=$oldvalue['Gender'];
$olddob=$oldvalue['DOB'];
$oldaddress=$oldvalue['Address'];
$oldmobileno=$oldvalue['Phone'];
$olddivision=$oldvalue['Division'];
$oldclass=$oldvalue['Class'];
$oldemail=$oldvalue['Email_Id'];
}
if(mysql_query("DESCRIBE `table`")) {
$sql = "UPDATE table SET ";
$sql.= " Student_Name = '$oldname', Gender = '$oldgender',.... ";
$sql.= " WHERE id = '$id' ";
if(mysql_query($sql)){
echo 'Good';
}
else
{
echo 'Bad';
}
}
Try something like this ;)
Hello Friends thank you,
All your answers helped me to solve problem.
I learn alot from you all.
Finally i solved above problem doing some changes in update.php file code..
Here is my new code
<?php
include('connection.php');
if(isset ($_REQUEST['Student_Id']))
{
$id = $_REQUEST['Student_Id'];
$result = mysql_query("select* from tblstudent where Student_Id ='".$id."'");
while($oldvalue= mysql_fetch_array($result))
{
$oldid = $oldvalue['Student_Id'];
$oldname=$oldvalue['Student_Name'];
$oldgender=$oldvalue['Gender'];
$olddob=$oldvalue['DOB'];
$oldaddress=$oldvalue['Address'];
$oldmobileno=$oldvalue['Phone'];
$olddivision=$oldvalue['Division'];
$oldclass=$oldvalue['Class'];
$oldemail=$oldvalue['Email_Id'];
}
}
if(isset ($_POST['newname']))
{
$newname =$_POST['newname'];
$newid =$_POST['newid'];
$newgender =$_POST['newgender'];
$newdob = $_POST['newdob'];
$newaddress = $_POST['newaddress'];
$newphone = $_POST['newphone'];
$newdivision = $_POST['newdivision'];
$newclass = $_POST['newclass'];
$newemailid = $_POST['newemailid'];
$sql= "UPDATE tblstudent SET Student_Name='$newname', Gender='$newgender', DOB='$newdob', Address='$newaddress', Phone='$newphone', Division='$newdivision', Class='$newclass', Email_Id='$newemailid' WHERE Student_Id='$newid'";
$result= mysql_query($sql);
header('location:index.php');
}
?>
<body>
<form action="update.php" method="post">
<fieldset>
<legend>Personal Information</legend><br/>
<div class="studentname"><label>Student Name :</label><input type="text" name="newname" id="studentnameId" value="<?php echo $oldname ?>" placeholder="Enter First & Last Name" size="30px" /></div><br/>
<input type="hidden" name="newid" value="<?php echo $oldid ?>"/>
<div class="gender">
<label>Gender :</label>
<input type="radio" name="newgender" value="Male" <?php echo ($oldgender == 'Male') ? 'checked' : ''; ?> /> Male
<input type="radio" name="newgender" value="Female" <?php echo ($oldgender == 'Female') ? 'checked' : ''; ?>/> Female<br />
</div> <br/>
<div class="dob"><label>Date of Birth :</label><input type="text" name="newdob" id="dobId" value="<?php echo $olddob ?>" placeholder="Enter DOB format Year-Month-DaY" size="30px" /></div><br/>
<div class="address"><label class="addresschild">Address : </label><textarea rows="4" cols="21" name="newaddress" id="addressId" value="" placeholder="Enter Your Address"><?php echo $oldaddress ?></textarea></div><br/>
<div class="mobileno"><label>Parent's Mobile No : </label><input type="text" name="newphone" id="mobilenoId" value="<?php echo $oldmobileno ?>" placeholder="Enter Parent's Mobile No" size="30px" /></div><br/>
<div class="selectdivision">
<label>Divison :</label>
<select id="divisiondropdownId" name="newdivision">
<option value="0">Select Division</option>
<option value="A"<?php if($olddivision=="A") echo 'selected="selected"'; ?> >A</option>
<option value="B"<?php if($olddivision=="B") echo 'selected="selected"'; ?> >B</option>
<option value="C"<?php if($olddivision=="C") echo 'selected="selected"'; ?> >C</option>
</select>
</div><br/>
<div class="selectclass">
<label>Class :</label>
<select id="classdropdownId" name="newclass">
<option value="0">Select Class</option>
<option value="First"<?php if($oldclass=="First") echo 'selected="selected"'; ?>>First</option>
<option value="Second"<?php if($oldclass=="Second") echo 'selected="selected"'; ?>>Second</option>
<option value="Third"<?php if($oldclass=="Third") echo 'selected="selected"'; ?>>Third</option>
<option value="Fourth"<?php if($oldclass=="Fourth") echo 'selected="selected"'; ?>>Fourth</option>
<option value="Fifth"<?php if($oldclass=="Fifth") echo 'selected="selected"'; ?>>Fifth</option>
<option value="Sixth"<?php if($oldclass=="Sixth") echo 'selected="selected"'; ?>>Sixth</option>
<option value="Seventh"<?php if($oldclass=="Seventh") echo 'selected="selected"'; ?>>Seventh</option>
<option value="Eighth"<?php if($oldclass=="Eighth") echo 'selected="selected"'; ?>>Eighth</option>
<option value="Nineth"<?php if($oldclass=="Nineth") echo 'selected="selected"'; ?>>Nineth</option>
<option value="Tenth"<?php if($oldclass=="Tenth") echo 'selected="selected"'; ?>>Tenth</option>
</select>
</div><br/>
<div class="emailid"><label>Email-Id : </label><input type="text" name="newemailid" id="emailId" value="<?php echo $oldemail ?>" placeholder="Enter your Email-id" size="30px" /></div><br/>
<div id="submit1">
<input class="btnsubmit" type="submit" name="submit" id="submit" value="Submit" />
<input class="btnreset" type="reset" name="reset" id="submit" value="Reset" />
</div><br/>
</fieldset>
</form>
</body>
Thank you :-)
Related
I have a form contain looping input tag that is used for adding data. the looping form is work, and the problem is i didn't know how to retrieve that looping data in controller code igniter. please help!
this is my view (form)
<form action="#" id="ap_data">
<div class="table-responsive">
<table class="table table-striped table-hover" id="mkt">
<thead>
<tr>
<th>KR</th>
<th>NP</th>
<th>KP</th>
</tr>
</thead>
<tbody>
<?php $number =0;
$id = "id";
$idkr = "idkr";
$np = "np";
$idkp = "idkp";?>
<?php foreach ($perb as $value) {
$number++; ?>
<tr>
<input type="hidden" name="<?php echo $id.$number; ?>" value="<?php echo $value->idp ?>"/>
<td>
<input type="text" placeholder="" name="<?php echo $idkr.$number; ?>" value="<?php echo $value->idkp ?>" class="form-control">
</td>
<td>
<select name="<?php echo $np.$number; ?>" class="form-control">
<option value="1">1 (AS)</option>
<option value="2">2 (Bold)</option>
<option value="3">3 (Seed)</option>
</select>
</td>
<td>
<input type="text" placeholder="" name="<?php echo $idkp.$number; ?>" value="<?php echo $value->idkp ?>" id="class="form-control">
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="form-group">
<button type="button" onclick="test_kond()" class="btn btn-success col-lg-12">Test Kond</button>
</div>
</form>
here' is my view (Ajax function)
<script type="text/javascript">
var test_kond;
$( document ).ready(function() {
test_kond = function () {
var data_ap;
data_ap = $("#ap_data").serialize();
$.ajax({
type: "POST",
url: "<?php echo site_url('HoldBotCtrl/kond_ajax')?>",
data: data_app,
success: function() {
alert(data_ap);
}
});
};
});
and here's my controller
function kond_ajax(){
$k_t = $this->Hb_model->select_kr();
$j_kr = count($kr_total);
$idkr = "idkr";
$np = "np";
$idkp ="idkp";
for ($i=1; $i <= $jj_kr ; $i++) {
$idkrr = $idkr.$i;
$npp = $np.$i;
$idkpp = $idkp.$i;
$data_ap = array(
$idkrr => $this->input->post($idkrr),
$npp => $this->input->post($npp),
$idkpp => $this->input->post($idkpp)
);
print_r($data_ap);
}
and this is result of print_r
idkr1Array ( [idkr1] => [np1] => [idkp1] => ) idkr2Array ( [idkr2] => [np2] => [idkp2] => )
the value still null, i need to get the data from $this->input->post();.
how to fix this??
I think serilize() method creates a URL encoded string where as you want to send data via POST method in ajax. You could try this way.
var test_kond;
$( document ).ready(function() {
test_kond = function () {
var data_ap;
data_ap = new FormData($("#ap_data"));
$.ajax({
type: "POST",
url: "<?php echo site_url('HoldBotCtrl/kond_ajax')?>",
data: data_app,
success: function() {
alert(data_ap);
}
});
};
});
Just try by changing field names like below:
<form action="#" id="ap_data">
<div class="table-responsive">
<table class="table table-striped table-hover" id="mkt">
<thead>
<tr>
<th>KR</th>
<th>NP</th>
<th>KP</th>
</tr>
</thead>
<tbody>
<?php $number =0;
$id = "id";
$idkr = "idkr";
$np = "np";
$idkp = "idkp";?>
<?php foreach ($perb as $value) {
$number++; ?>
<tr>
<input type="hidden" name="data[<?= $number ?>]['id']" value="<?php echo $value->idp ?>"/>
<td>
<input type="text" placeholder="" name="data[<?= $number ?>]['idkr']" value="<?php echo $value->idkp ?>" class="form-control">
</td>
<td>
<select name="data[<?= $number ?>]['np']" class="form-control">
<option value="1">1 (AS)</option>
<option value="2">2 (Bold)</option>
<option value="3">3 (Seed)</option>
</select>
</td>
<td>
<input type="text" placeholder="" name="data[<?= $number ?>]['idkp']" value="<?php echo $value->idkp ?>" id="" class="form-control">
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="form-group">
<button type="button" onclick="test_kond()" class="btn btn-success col-lg-12">Test Kond</button>
</div>
</form>
and in your controller :
function kond_ajax(){
print_r($this->input->post());
}
I hope this will help :)
im working with a dynamic form that the end user can enter as much material as he wants by clicking on an add button, this button calls a JavaScript function that inserts a drop-down list into my form. if i removed the select section it works and it calls the input field but if i add the select section it doesn't call the function.
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
function add_row()
{
$rowno=$("#recipe_details tr").length;
$rowno=$rowno+1;
$("#recipe_details tr:last").after("<tr id='row"+$rowno+"'> <td><select name="Material1[]">
<?php
$sql2 = mysqli_query($conn, "SELECT * FROM Material");
while ($r = $sql2->fetch_assoc()){
?>
<option value= <?php echo $r["Material_ID"] ?>><?php echo $r["Material"]; ?></option>
<?php
// close while loop
}
?></select></td><td><input type='text' name='quantity[]' placeholder='Enter Quantity'></td><td><input type='button' value='DELETE' onclick=delete_row('row"+$rowno+"')></td></tr>");
}
function delete_row(rowno)
{
$('#'+rowno).remove();
}
</script>
<div id="wrapper">
<div id="form_div">
<form method="post" action="">
<table id="recipe_details" align=center>
<tr id="row1">
<td><select name="Material1[]">
<?php
$sql2 = mysqli_query($conn, "SELECT * FROM Material");
while ($r = $sql2->fetch_assoc()){
?>
<option value= <?php echo $r["Material_ID"] ?>><?php echo $r["Material"]; ?></option>
<?php
// close while loop
}
?></select></td>
<td><input type="text" name="quantity[]" placeholder="Enter Quantity"></td>
</tr>
</table>
<input type="button" onclick="add_row();" value="ADD ROW">
<input type="submit" name="submit_row" value="SUBMIT">
</form>
</div>
</div>
Updated code :-
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
function add_row()
{
$rowno = $("#recipe_details tr").length;
$rowno = $rowno+1;
$("#recipe_details tr:last").after(
`<tr id='row` + $rowno + `'><td><select name='Material1[]'>
<?php
$sql2 = mysqli_query($conn, "SELECT * FROM Material");
while ($r = $sql2->fetch_assoc()){
?>
<option value = <?php echo $r["Material_ID"] ?>><?php echo $r["Material"]; ?></option>
<?php
// close while loop
}
?>
<option value = 'Option 1'>Option 1</option>
</select ></td >
<td><input type='text' name='quantity[]' placeholder='Enter Quantity'></td>
<td><input type='button' value='DELETE' onclick=delete_row('row`+ $rowno + `')></td></tr>"`);
}
function delete_row(rowno)
{
$('#'+rowno).remove();
}
</script>
<div id="wrapper">
<div id="form_div">
<form method="post" action="">
<table id="recipe_details" align="center">
<tr id="row1">
<td><select name="Material1[]">
<?php
$sql2 = mysqli_query($conn, "SELECT * FROM Material");
while ($r = $sql2->fetch_assoc()){
?>
<option value ='<?php echo $r["Material_ID"] ?>><?php echo $r["Material"];?>'></option>
<?php
// close while loop
}
?></select></td>
<td><input type="text" name="quantity[]" placeholder="Enter Quantity"></td>
</tr>
</table>
<input type="button" onclick="add_row();" value="ADD ROW">
<input type="submit" name="submit_row" value="SUBMIT">
</form>
</div>
</div>
I have checked this snippet on my machine for employee list. Its working fine.
Let me know if you are still facing some issues.
It should work on your machine also.
This is my controller:
function update_agenda() {
$id = $this->input->post['did'];
$this->load->model('agenda_model');
$data = array(
'nama' => $this->input->post('did'),
'keterangan' => $this->input->post('dketer')
);
($this->agenda_model->update($id, $data))
}
When I click button Save, it won't change anything. How can I fix this problem?
<td>
<input type ="checkbox" id="haha" class=checkbox1 name="checklist" value=<?php echo $agenda->id; ?>> <?php echo $agenda->id; ?>
</td>
<td>
<input type="text" id="hide" name="did" value="<?php echo $agenda->id; ?>">
</td>
<td>
<input type="text" name="dnama" id="nama_" value="<?php echo $agenda->nama; ?>" disabled />
</td>
<td>
<input type="text" name="dketer" id="ket_" value="<?php echo $agenda->keterangan; ?>" disabled>
</td>
<?php }?>
</td>
</tr>
</table>
<button onclick="saveUpdate()"> Save </button>
This is my model:
function update ($id,$data){
$this->db->where('id', $id);
$this->db->update('agenda', $data);
}
Here is my saveUpdate function
i hope this helpyou
view.php
<td>
<input type ="checkbox" id="haha" class=checkbox1 name="checklist" value=<?php echo $agenda->id; ?>> <?php echo $agenda->id; ?>
</td>
<td>
<input type="text" id="hide" name="did" value="<?php echo $agenda->id; ?>">
</td>
<td>
<input type="text" name="dnama" id="nama_" value="<?php echo $agenda->nama; ?>" disabled />
</td>
<td>
<input type="text" name="dketer" id="ket_" value="<?php echo $agenda->keterangan; ?>" disabled>
</td>
<?php }?>
</td>
</tr>
</table>
<button onclick="saveUpdate()"> Save </button>
controller.php
function update_agenda() {
$this->load->model('agenda_model');
$this->form_validation->set_rules('did', 'Did', 'trim|required|xss_clean');
$this->form_validation->set_rules('dketer', 'Dketer', 'trim|required|xss_clean');
if ($this->form_validation->run() === FALSE){
echo 'ERROR';
}
else{
$id = $this->input->post['did'];
$data = array(
'nama' => $this->input->post('did'),
'keterangan' => $this->input->post('dketer')
);
$this->agenda_model->update($id, $data);
$data['agenda'] = $this->agenda_model->get_data($id);
$this->load->view('formsuccess', $data);
}
}
model.php
function update($id, $data){
$this->db->where('id', $id);
$this->db->update('table', $data);
}
function get_data($id){
$this->db->where('id', $id);
return $this->db->get('table')->row();
}
I am trying to pass my JavaScript variable using Ajax into my PHP script but that doesn't work it given me error that it is undefined index. both codes are in different files but both of them are accessible on the main page.
Here's my script.php
<script>
function get_child_options(){
var parentID = jQuery('#parent').val();
jQuery.ajax({
url: '/**/**/**/child_categories.php',
type: 'POST',
data: {parentID : parentID},
success: function(data){
jQuery('#child').html(data);
},
error: function(){alert("Something Went Wrong with child options. ")},
});
}
jQuery('select[name="parent"]').change(get_child_options);
</script>
And this is my php file
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/ **/core/init.php'; //Including database path stored in init.php
$parentID = (int)$_POST['parentID'];
$childQuery = "SELECT * FROM categories WHERE parent = '$parentID' ORDER BY category";
ob_start();
?>
<option value="">Select <strong>Child</strong> Category</option>
<?php while ($child = mysqli_fetch_assoc($childQuery)): ?>
<option value="<?= $child['id']; ?>"><?= $child['category']; ?></option>
<?php endwhile; ?>
<?php
echo ob_get_clean();
?>
in script the #parent is a form id i am passing to javascript using jQuery.
because of variable is not accessible PHP is not running query.
This is my products.php the main where page where this is happening
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/Online Store/core/init.php'; //Including database path stored in init.php
include 'includes/head.php'; //Including header
include 'includes/navigation.php'; //Including Navigation bar
include 'includes/script.php';
if (isset($_GET['add'])) {
$brandQuery = $db->query("SELECT * FROM brand ORDER BY brand");
$parentQuery = $db->query("SELECT * FROM categories WHERE parent = 0 ORDER BY category");
?>
<h2 class="text-center">Add A New Product</h2><hr />
<form action="products.php?add=1" method="post" enctype="multipart/form-data">
<div class="form-group col-md-3">
<label for="title">Title*:</label>
<input type="text" class="form-control" id="title" name="title" value="<?= ((isset($_POST['title']))?sanitize($_POST['title']):''); ?>" placeholder="Add a title" />
</div>
<div class="form-group col-md-3">
<label for="brand">Brand*: </label>
<select class="form-control ">
<option value="" <?= ((isset($_POST['brand']) && $_POST['brand'] == '')?' selected':''); ?> >Select Brand</option>
<?php while($brand = mysqli_fetch_assoc($brandQuery)): ?>
<option value="<?= $brand['id']; ?>" <?= ((isset($_POST['brand']) && $_POST['brand'] == $brand['id'])?' selected':''); ?> ><?= $brand['brand'] ?></option>
<?php endwhile; ?>
</select>
</div>
<div class="form-group col-md-3">
<label for="parent">Parent Category*: </label>
<select class="form-control" id="parent" name="parent">
<option value="" <?= ((isset($_POST['parent']) && $_POST['parent'] == '')?' select':''); ?> >Select <strong>Parent</strong> Category</option>
<?php while($parent = mysqli_fetch_assoc($parentQuery)): ?>
<option value="<?= $parent['id']; ?>" <?= ((isset($_POST['parent']) && $_POST['parent'] == $parent['id'])?' select':''); ?> ><?= $parent['category']; ?></option>
<?php endwhile; ?>
</select>
</div>
<div class="form-group col-md-3">
<label for="child">Child Category*: </label>
<select id="child" name="child" class="form-control"></select>
<?php include $_SERVER['DOCUMENT_ROOT'].'/Online Store/admin/parsers/child_categories.php'; ?>
</div>
<div class="form-group col-md-3">
<label for="price">Price*: </label>
<input type="text" id="price" name="price" class="form-control" value="<?= ((isset($_POST['price']))?sanitize($_POST['price']):''); ?>" />
</div>
<div class="form-group col-md-3">
<label for="list_price">List Price*: </label>
<input type="text" id="list_price" name="list_price" class="form-control" value="<?= ((isset($_POST['list_price']))?sanitize($_POST['list_price']):''); ?>" />
</div>
<div class="form-group col-md-3">
<label>Quantity & Sizes</label>
<button class="btn btn-default btn-info form-control" onclick="jQuery('#sizesModal').modal('toggle'); return false;">Quantity & Sizes</button>
</div>
<div class="form-group col-md-3">
<label for="sizes">Sizes & Quantity preview*: </label>
<input type="text" name="sizes" id="sizes" class="form-control" value="<?= ((isset($_POST['sizes']))?$_POST['sizes']:''); ?>" readonly/>
</div>
<div class="form-group col-md-6">
<label for="photo">Photo*: </label>
<input type="file" name="photo" id="photo" class="form-control" />
</div>
<div class="form-group col-md-6">
<label for="description">Description</label>
<textarea name="description" id="description" class="form-control" rows="6" placeholder="Description" ><?= ((isset($_POST['description']))?sanitize($_POST['description']):''); ?></textarea>
</div>
<div class="form-group pull-right">
<input type="submit" class="form-control btn btn-success" value="Add Product" />
</div>
<div class="clearfix"></div>
</form>
<?php
}else{
$sql = "SELECT * FROM products WHERE deleted = 0";
$presults = $db->query($sql);
$product = mysqli_fetch_assoc($presults);
// Featured product
if (isset($_GET['featured'])) {
$id = (int)$_GET['id'];
$featured = (int)$_GET['featured'];
$featuredSql = "UPDATE `products` SET `featured` = '$featured' WHERE `products`.`id` = '$product[id]' ";
$db->query($featuredSql);
// header('Location: products.php');
}
?>
<h2 class="text-center">Products</h2>
Add Product<div class="clearfix"></div>
<hr />
<table class="table table-bordered table-condensed table-striped">
<thead>
<th></th>
<th>Product</th>
<th>Price</th>
<th>Category</th>
<th>Featured</th>
<th>Sold</th>
</thead>
<tbody>
<?php
while($product = mysqli_fetch_assoc($presults)):
$childID = $product['categories'];
$catSql = "SELECT * FROM categories WHERE id = '$childID'";
$result = $db->query($catSql);
$child = mysqli_fetch_assoc($result);
$parentID = $child['parent'];
$pSql = "SELECT * FROM categories WHERE id = '$parentID'";
$presult = $db->query($pSql);
$parent = mysqli_fetch_assoc($presult);
$category = $parent['category'].'~'.$child['category'];
?>
<tr>
<td>
<span class= " glyphicon glyphicon-pencil"></span>
<span class= " glyphicon glyphicon-remove-sign"></span>
</td>
<td><?= $product['title']; ?></td>
<td><?= money($product['price']) ?></td>
<td><?= $category; ?></td>
<td><a href="products.php?featured=<?= (($product['featured'] == 0)?'1':'0'); ?>&id =<?= $product['id']; ?>" class=" btn btn-sx btn-default">
<span class=" glyphicon glyphicon-<?= (($product['featured'] == 1)?'minus':'plus'); ?>"></span>
</a>  <?= (($product['featured'] == 1)?'Featured':''); ?></td>
<td>0</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<?php
}
include 'includes/footer.php'; //Including footer
?>
Is there any other way to do it? What I am trying to do is when user selects parent category I want child category to arrange as per parent category.
Try this:
<script>
function get_child_options(){
var parentID = $(this).val();
jQuery.ajax({
url: '/**/**/**/child_categories.php',
type: 'POST',
data: {'parentID' : parentID},
success: function(data){
jQuery('#child').html(data);
},
error: function(){alert("Something Went Wrong with child options. ")},
});
}
jQuery('select[name="parent"]').change(get_child_options);
</script>
Getting the Value by $(this) and putting single quotes around parentID data: {'parentID' : parentID},
All columns are in TEXT format apart from the BDid column which is in int. Ive had the code running smoothly with un-preared statements but thought I would update it, with the same data in and the same table.
No errors are returned, but no rows are affected.
The code is not getting any error but the MySQL is not updating
<?php
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: index.php");
}
if ( !empty($_POST)) {
// keep track validation errors with form fields
$first_nameError = null;
$sur_nameError = null;
$companyError = null;
$locationError = null;
$supervisorError = null;
$departmentError = null;
$job_descriptionError = null;
$hire_dateError =null;
$emailError = null;
$messageError = null;
// keep track post values
$first_name = $_POST['first_name'];
$sur_name = $_POST['sur_name'];
$company = $_POST['company'];
$location = $_POST['location'];
$supervisor = $_POST['supervisor'];
$department = $_POST['department'];
$job_description = $_POST['job_description'];
$hire_date = $_POST['hire_date'];
$email = $_POST['email'];
$message = $_POST['message'];
// validate input for the field
$valid = true;
if (empty($first_name)) {
$first_nameError = 'Please enter Name';
$valid = false;
}
if (empty($sur_name)) {
$sur_nameError = 'Please enter Name';
$valid = false;
}
if (empty($company)) {
$companyError = 'Please selest Company';
$valid = false;
}
if (empty($location)) {
$locationError = 'Please enter Location';
$valid = false;
}
if (empty($department)) {
$departmentError = 'Please enter Department';
$valid = false;
}
if (empty($job_description)) {
$job_descriptionError = 'Please enter Job Description';
$valid = false;
}
if (empty($hire_date)) {
$hire_dateError = 'Please enter Hire Date';
$valid = false;
}
if (empty($email)) {
$emailError = 'Please enter Email Address';
$valid = false;
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$emailError = 'Please enter a valid Email Address';
$valid = false;
}
if (empty($message)) {
$messageError = 'Please enter Message';
$valid = false;
}
// update data the field in the database
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE employee SET first_name = ?,sur_name = ?, company = ?, location = ?, supervisor = ?,
department= ?, job_description = ?, hire_date = ?, email = ?, message = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id, $first_name, $sur_name, $company, $location, $supervisor, $department,$job_description, $hire_date, $email, $message));
Database::disconnect();
header("Location: index.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM employee where id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$first_name = $data['first_name'];
$sur_name = $data['sur_name'];
$company = $data['company'];
$location = $data['location'];
$location = $data['supervisor'];
$department = $data['department'];
$job_description = $data['job_description'];
$hire_date = $data['hire_date'];
$email = $data['email'];
$message = $data['message'];
Database::disconnect();
}
?>
This my Html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update a Customer</h3>
</div>
This is my form
<form class="form-horizontal" action="update.php?id=<?php echo $id?>" method="post">
<div class="control-group <?php echo !empty($first_nameError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<input name="first_name" required placeholder="First Name"
title="First Name" value="<?php echo !empty($first_name)?$first_name:'';?>">
<?php if (!empty($first_nameError)): ?>
<span class="help-inline"><?php echo $first_nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($sur_nameError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<input name="sur_name" required placeholder="Sur Name" title="Sur Name"
value="<?php echo !empty($sur_name)?$sur_name:'';?>">
<?php if (!empty($sur_nameError)): ?>
<span class="help-inline"><?php echo $sur_nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($companyError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<select name="company" class="company" id="company" style="company"
title="Company" required placeholder="Company" value="<?php echo !empty($company)?$company:'';?>">
<option value="Select.." selected>Select....</option>
<option>HM</option>
<option>HRA</option>
<option>HSG</option>
<option>HAL</option>
<option>HBN</option>
<option>HFR</option>
<option>HPL</option>
<option>HRD</option>
<option>HERS</option>
<option>HPS</option>
<option>HEA</option>
</select>
<?php if (!empty($companyError)): ?>
<span class="help-inline"><?php echo $companyeError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($locationError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<input name="location" required placeholder="Location" title="Location"
value="<?php echo !empty($location)?$location:'';?>">
<?php if (!empty($locationError)): ?>
<span class="help-inline"><?php echo $location;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($supervisorError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<input name="supervisor" required placeholder="Supervisor"
title="Supervisor" value="<?php echo !empty($supervisor)?$supervisor:'';?>">
<?php if (!empty($supervisorError)): ?>
<span class="help-inline"><?php echo $supervisor;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($departmentError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<select name="department" size="1" class="department" id="department" style="department"
title="Department " required placeholder="Department" value="<?php echo !empty($department)?$department:'';?>">
<option value="Select" selected>Select</option>
<option value="FI">Finace</option>
<option value="CO">Controlling</option>
<option value="PP">Production Planning</option>
<option value="SD">Sale & Distribution &Customer Relationship manager</option>
<option value="WM">Warehouse Managerment</option>
<option value="MM">Material Managerment</option>
<option value="HR">Human Resources</option>
<option value="QM">Quality Management</option>
<option value="PM">Plant Maintenance</option>
<option value="IT">Information Technology</option>
<option value="BO">Back Office</option>
<option value="SAP">Administrative Group SAP User</option>
<option value="SAPKEY">Administrative Group SAP Key User</option>
<option value="ADMIN">Administrative Group Administrators</option>
<option value="MGMT">Management</option>
</select>
<?php if (!empty($departmentError)): ?>
<span class="help-inline"><?php echo $department;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($job_descriptionError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<input name="job_description" required placeholder="Job Description"
title="Job Description" value="<?php echo !empty($job_description)?$job_description:'';?>">
<?php if (!empty($job_descriptionError)): ?>
<span class="help-inline"><?php echo $job_description;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($hire_dateError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<input name= "hire_date" type="date" required placeholder="Hire Date"
title="Hire Date" value="<?php echo !empty($hire_date)?$hire_date:'';?>">
<?php if (!empty($hire_dateError)): ?>
<span class="help-inline"><?php echo $hire_date;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($emailError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<input name="email" type="email" required placeholder="Email"
title="Email ID" value="<?php echo !empty($email)?$email:'';?>">
<?php if (!empty($emailError)): ?>
<span class="help-inline"><?php echo $email;?></span>
<?php endif; ?>
</div>
</div><div class="control-group <?php echo !empty($messageError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<textarea name="message" cols="20" rows="5" required placeholder="Message"
title="Comments"value="<?php echo !empty($message)?$message:'';?>"></textarea>
<?php if (!empty($messageError)): ?>
<span class="help-inline"><?php echo $messager;?></span>
<?php endif; ?>
</div>
this is the action
</div> <div class="form-actions">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
it looks like you need to change the execute line to this:
$q->execute(array($first_name, $sur_name, $company, $location, $supervisor, $department,$job_description, $hire_date, $email, $message, $id));