Updating two tables using prepared statements and PDO - javascript

Am trying to update data in two tables and according to my codes below, only the first table 'student_information' is getting updated
leaving out the 'training_information' table not updated. The two tables are linked by IndexNo. I need guidance with my code on how I can update both the tables at once using my sample prepared statements.
Please follow also that I try to get the id value using the URL as given. This helps me view and update data about one distinct column with IndexNo in one operation.
URL: http://localhost/sample/updateStudentInfo.php?id=14
updateStudentInfo.php code as below
<?php
// Connect to MySQL database
function connect(){
try{
$dbConn = new PDO('mysql:host=localhost; dbname=hpcz', 'root', 'root');
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConn;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
$dbh = connect();
//gets the value of the id from the URL
$id = htmlspecialchars($_GET["id"]);
$sql = "SELECT
student_information.IndexNo,
student_information.SurName,
student_information.FirstName,
student_information.MiddleName,
grade_obtained.Grade,
secondary_school.SchoolName
FROM student_information
LEFT JOIN training_information
ON student_information.IndexNo = training_information.IndexNo
WHERE student_information.IndexNo='$id'";
$result = $dbh->prepare($sql);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
//Initializing the id from URL with the IndexNo from the database
$id=$row["IndexNo"];
?>
<div><form method="post" >
<table width="500" border="1" >
<tr>
<td colspan="4">Update Student Information</td>
</tr>
<tr>
<td colspan="4"><div align="center"><strong>Applicant Information</strong></div></td>
</tr>
<tr>
<td><div align="right">Sur Name:</div></td>
<td><input type="text" name="surname" id="surname" value="<?php echo $row['SurName']; ?>"/></td>
<td><div align="right">First Name:</div></td>
<td><input type="text" text-input" name="fname" id="fname" value="<?php echo $row['FirstName']; ?>"/></td>
</tr>
<tr>
<td><div align="right">Middle Name:</div></td>
<td><input type="text" name="mname" id="mname" value="<?php echo $row['MiddleName']; ?>"/></td>
<td><div align="right">NRC/Passport No:</div></td>
<td><input type="text" name="nrc" id="nrc" value="<?php echo $row['NRCPassportNo']; ?>"/></td>
</tr>
<tr>
<td colspan="4"><div align="center"><strong>Training Information</strong></div></td>
</tr>
<tr>
<td><div align="right">Secondary School Attended:</div></td>
<td><select name="secondarysch" id="secondarysch" >
<option selected="selected"><?php echo $row['SchoolName']; ?></option>
</select></td>
<td><div align="right">Grade Obtained:</div></td>
<td><select name="grade" id="grade" >
<option selected="selected"><?php echo $row['Grade']; ?></option>
</select></td>
</tr>
<input type="hidden" name="id" id="id" value="<?php echo $row['IndexNo']; ?>"/>
<tr>
<td colspan="4"><div align="center"><button id="update">Update</div></td>
</tr>
</table>
<?php }?>
</form>
JavaScript code:
$(document).ready(function(){
$("#update").click(function(){
/*Applicant Information*/
var vid = $("#id").val();
var vsurname = $("#surname").val();
var vmname = $("#mname").val();
var vfname = $("#fname").val();
/*Training Information*/
var vsecondarysch = $("#secondarysch").val();
var vgrade = $("#grade").val();
/*Jquery post method */
$.post("http://localhost/sample/sendUpdateStudentInfo.php",
{
id : vid,
surname : vsurname,
mname : vmname,
fname : vfname,
secondarysch :vsecondarysch,
grade : vgrade
},
/*Handles response from server*/
function(response){
alert(response);
});
alert("You are here");
});
});
sendUpdateStudentInfo.php code:
<?php
$method = $_SERVER['REQUEST_METHOD'];
function connect(){
try{
$dbConn = new PDO('mysql:host=localhost; dbname=hpcz', 'root', 'root');
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConn;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
/*Checks if method is HTTP POST*/
if(strtolower($method) == 'post'){
/*Applicant Information*/
$id = addslashes($_POST['id']);
$surname = addslashes($_POST['surname']);
$mname = addslashes($_POST['mname']);
$fname = addslashes($_POST['fname']);
/*Training Information*/
$secondarysch = addslashes($_POST['secondarysch']);
$grade = addslashes($_POST['grade']);
try {
$dbHandler = connect();
$dbHandler->beginTransaction();
$setInfo = "UPDATE student_information
SET
SurName = :vSurname,
MiddleName = :vMName,
FirstName = :vFName
WHERE
IndexNo = '$id'";
$stmt = $dbHandler->prepare($setInfo);
$stmt->bindParam(':vSurname', $surname);
$stmt->bindParam(':vMName', $mname);
$stmt->bindParam(':vFName', $fname);
$stmt->execute();
$stmt->closeCursor();
$setTrainingInfo = "UPDATE training_information
SET
SecondarySchoolID = :Secondarysch,
GradeObtainedID = :Grade
WHERE
IndexNo = '$id'";
$stmt = $dbHandler->prepare($setTrainingInfo);
$stmt->bindParam(':Secondarysch', $secondarysch);
$stmt->bindParam(':Grade', $grade);
$stmt->execute();
$stmt->closeCursor();
$dbHandler->commit();
echo "The Operation was Successful!!!!!!";
} catch (PDOException $e) {
$dbHandler->rollback();
die($e->getMessage());
}
}else{
echo "Oops! Make sure Method is POST";
}
?>

Related

how to load a value from database in radio button?

I need to know if you can do this function ... I have a database that has a "boolean" field that accepts 0 or 1 values And I have an HTML page in which there is a radioButton with values Ok or No I must be able to load the boolean value in the radioButton so if in the database the boolean variable is 1 on the HTML page (after executing the SELECT) the radioButton will have OK value if in the database the boolean variable is 0 on the HTML page (after executing the SELECT) the radioButton will have NO value
this is the code of my attempts :
<?php
$servername = "localhost";
$username = "progettocantiere";
$password = "";
$dbname = "my_progettocantiere";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$idAffidataria = $_GET['idAffidataria'];
$sql1 = "SELECT * FROM Affidataria WHERE idAffidataria = '{$idAffidataria}'";
$result = $conn->query($sql1);
$details = $result->fetch_array();
$savedNomeCantiere = $details["nomeCantiere"];
$savedAddettoSicurezza = $details["addettoSicurezza"];
$savedMailAffidataria = $details["mailAffidataria"];
$savedContrattoDiAppalto = $details["contrattoDiAppalto"]; // <--- BOOLEAN <----
$result1 = $conn->query($sql1);
echo($nomeCantiere);
?>
<html>
<body>
<table>
<tr>
<td colspan="2" bgcolor="#CDECFD" style="font-weight: bold">Cantiere</td>
<td colspan="4" bgcolor="#CDECFD"><input type="text" class="form-control" style="width: 100%;" name="cantiereAffidataria" id="cantiereAffidataria" value="<?php echo $savedNomeCantiere; ?>"/> </td>
</tr>
<tr>
<td colspan="2" bgcolor="#CDECFD" style="font-weight: bold">ContrattoDiAppalto</td>
<td bgcolor="#B35556"><form action="">
OK <input type="radio" name="contrattoDiAppalto" id="contrattoDiAppalto" value="<?php echo $savedContrattoDiAppalto; ?>" onchange="color(this)" /> <BR>
NO <input type="radio" name="contrattoDiAppalto" id="contrattoDiAppalto" value="<?php echo $savedContrattoDiAppalto; ?>" onchange="color(this)" checked/>
</form></td>
</tr>
</table>
in other words I have to be able to change the radioButton according to the data provided by the SELECT on the database
I tried to give it the value through <?php echo $savedContrattoDiAppalto; ?>" but I doubt it's right .. I'm running out of ideas .. can someone help me?
Make an variable $checked = 'checked'
Then make an condition to check if it's 1 or 0
$checked = 'checked';
if($savedContrattoDiAppalto != 1){
$checked = ''; // Default is checked, if it isn't 1 then it's empty and will not check your radio.
}
And apply that variable to your input attributes.
<input type="radio" name="contrattoDiAppalto" id="contrattoDiAppalto"
value="<?php echo $savedContrattoDiAppalto; ?>" onchange="color(this)" $checked/>
Full code should be :
<?php
$servername = "localhost";
$username = "progettocantiere";
$password = "";
$dbname = "my_progettocantiere";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$idAffidataria = $_GET['idAffidataria'];
$sql1 = "SELECT * FROM Affidataria WHERE idAffidataria = '{$idAffidataria}'";
$result = $conn->query($sql1);
$details = $result->fetch_array();
$savedNomeCantiere = $details["nomeCantiere"];
$savedAddettoSicurezza = $details["addettoSicurezza"];
$savedMailAffidataria = $details["mailAffidataria"];
$savedContrattoDiAppalto = $details["contrattoDiAppalto"];
$checked = 'checked';
if($savedContrattoDiAppalto != true){
$checked = ''; // if not true then not checked
}
$result1 = $conn->query($sql1);
echo($nomeCantiere);
?>
<html>
<body>
<table>
<tr>
<td colspan="2" bgcolor="#CDECFD" style="font-weight: bold">Cantiere</td>
<td colspan="4" bgcolor="#CDECFD"><input type="text" class="form-control" style="width: 100%;" name="cantiereAffidataria" id="cantiereAffidataria" value="<?php echo $savedNomeCantiere; ?>"/> </td>
</tr>
<tr>
<td colspan="2" bgcolor="#CDECFD" style="font-weight: bold">ContrattoDiAppalto</td>
<td bgcolor="#B35556"><form action="">
OK <input type="radio" name="contrattoDiAppalto" id="contrattoDiAppalto" value="<?php echo $savedContrattoDiAppalto; ?>" onchange="color(this)" $checked/> <BR>
NO <input type="radio" name="contrattoDiAppalto" id="contrattoDiAppalto" value="<?php echo $savedContrattoDiAppalto; ?>" onchange="color(this)" $checked/>
</form></td>
</tr>
</table>

Edit/Update data in php through AJAX

In my index.php I am fetching data from the database. I put an edit button on that and I have used a datatable to view data information in this form. I have four field: Name, Age, Email, Update through mysqli_fetch_array I have fetched the data.
This is the index.php file:
<?php
//including the database connection file
include_once("config.php");
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
// using mysqli_query instead
?>
<html>
<head>
<title>Homepage</title>
<link rel="stylesheet" href="DataTables/datatables.css" type="text/css">
<link rel="stylesheet" href="DataTables/DataTables/css/dataTables.bootstrap.css" type="text/css">
<link rel="stylesheet" href="DataTables/DataTables/css/jquery.dataTables.css" type="text/css">
<script src="DataTables/datatables.js"></script>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/datatable.js"></script>
<script src="DataTables/DataTables/js/dataTables.bootstrap.js"></script>
<script src="DataTables/DataTables/js/jquery.dataTables.js"></script>
</head>
<body>
Add New Data<br/><br/>
<table id="datatable" class="display" width='100%' border=0>
<thead>
<tr bgcolor='#CCCCCC'>
<td>Name</td>
<td>Age</td>
<td>Email</td>
<td>Update</td>
</tr>
</thead>
<?php
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
//$action=$_POST["action"];
//if($action=='showroom')
{
$result = mysqli_query($mysqli, "SELECT * FROM users ORDER BY id DESC");
while ($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $res['name'] . "</td>";
echo "<td>" . $res['age'] . "</td>";
echo "<td>" . $res['email'] . "</td>";
echo "<td>Edit | Delete</td>";
}
}
?>
</table>
</body>
</html>
This is my edit.php file. First I check empty fields, after that I run updating the table query redirecting to the display page. In our case, it is index.php then getting id from url, selecting data associated with this particular id, fetching data through mysqli_fetch_array .
<?php
// including the database connection file
include_once("config.php");
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
// checking empty fields
if (empty($name) || empty($age) || empty($email)) {
if (empty($name)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if (empty($age)) {
echo "<font color='red'>Age field is empty.</font><br/>";
}
if (empty($email)) {
echo "<font color='red'>Email field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE users SET name='$name',age='$age',email='$email' WHERE id=$id");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE id=$id");
while ($res = mysqli_fetch_array($result)) {
$name = $res['name'];
$age = $res['age'];
$email = $res['email'];
}
?>
<html>
<head>
<title>Edit Data</title>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/insert.js"></script>
<script src="style/view.js"></script>
<script src="style/edit.js"></script>
</head>
<body>
Home
<br/><br/>
<p id="message"></p>
<form name="form1" method="POST" action="edit.php">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo $name; ?>"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="<?php echo $age; ?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email; ?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id']; ?>></td>
<td><input type="submit" name="update" id="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
Finally, this is my edit.js file. In this file I try to do edit the form through AJAX, but I can't find where I doing mistakes.
<script>
$(document).ready(function (e) {
$('#update').click(function (event)
{
event.preventDefault();
$.ajax({
data: $('form').serialize(),
url: "edit.php", //php page URL where we post this data to save in database
type: 'POST',
success: function (strMessage) {
$('#message').text("strMessage");
}
})
});
});
</script>
You are doing edit and update on same file so you have to add condition on file. change your code as below:
edit.php
<?php
// including the database connection file
include_once("config.php");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
// checking empty fields
if(empty($name) || empty($age) || empty($email)) {
if(empty($name)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if(empty($age)) {
echo "<font color='red'>Age field is empty.</font><br/>";
}
if(empty($email)) {
echo "<font color='red'>Email field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE users SET name='$name',age='$age',email='$email' WHERE id=$id");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE id=$id");
while($res = mysqli_fetch_array($result))
{
$name = $res['name'];
$age = $res['age'];
$email = $res['email'];
}
?>
<html>
<head>
<title>Edit Data</title>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/insert.js"></script>
<script src="style/view.js"></script>
<script src="style/edit.js"></script>
</head>
<body>
Home
<br/><br/>
<p id="message"></p>
<form name="form1" method="POST" action="edit.php">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo $name;?>"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="<?php echo $age;?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" id="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>

Updating quantity in cart table

I want that update button should be in that field which I choose.But it appears only in first row and is updating for first row quantity field.
<form action="cart.php?action=update" method="post">
<table>
<tr>
<th colspan="2">ITEM</th>
<th>QUANTITY</th>
<th>PRICE</th>
<th>SUBTOTAL</th>
<th>REMOVE</th>
</tr>
<?php
$query = "select * from cart where customer_id='$user' ";
$result = mysqli_query($con,$query);$b = 0;$c = 0;
while($row = mysqli_fetch_array($result))
{
$productid = $row['product_id'];
$query2 = "select * from product where product_id='$productid'";
$result2 = mysqli_query($con,$query2);
while($row2=mysqli_fetch_array($result2))
{
?>
<tr>
<td rowspan="3"><img src="upload/<?php echo $row2['pimage']; ?>" height="50px" width="50px"></td>
<td rowspan="3"><?php echo $row2['pname']; ?></td>
<td rowspan="3">
<input tpe="text" name="newqty" value="<?php echo $qty = $row['quantity']; ?>" onkeypress="showsubmit()">
<input style="visibility:hidden;width:80px;border-radius:10px;background-color:green;border:none;padding:5px;color:white;" type="submit" name="sub1" id="sub1" value="UPDATE">
<input type="hidden" name="hidcartid" value="<?php echo $row['cart_id'] ?>"/>
<input type="hidden" name="hidproductid" value="<?php echo $row['product_id']; ?>"/>
<script>
function showsubmit()
{
document.getElementById("sub1").style.visibility = "visible";
}
</script>
</td>
<td>Price:<?php echo $sp = $row2['psellingprice']; ?></td>
<?php
$total = $sp * $qty;
?>
<td rowspan="3">
<?php
echo $t = $total;
$b = $b + $t;
?></td>
<td rowspan="3">REMOVE</td>
</tr>
<?php
$action = ( array_key_exists( 'action', $_REQUEST) ? $_REQUEST['action'] : "" );
if($action =="delete")
{
deletecart($_REQUEST['cid']);
}
if($action=="update")
{
echo "update function called";
updatecart();
echo "update function executed";
}
?>
<tr>
<td>Selling Price:<?php echo $p = $row2['pprice']; ?></td>
</tr>
<tr>
<td>You Saved:
<?php
$d = $row2['pdiscount'];
$s = ($p*$d)/100;
echo $q = $s * $qty;
$c = $c + $q;
?> rs.</td>
</tr>
<?php
}
}
?>
</table>
and cart2.php
<?php
function deletecart($cartid)
{
include 'connection.php';
$sql1="delete from cart where cart_id=$cartid";
$executequery = mysqli_query($con,$sql1);
header('location:cart.php');
}
function updatecart()
{
include 'connection.php';
$cartId = $_POST['hidcartid'];
$productId = $_POST['hidproductid'];
$newqty = $_POST['newqty'];
echo("inside update function");
// update product quantity
$sql = "UPDATE cart
SET quantity = $newqty
WHERE cart_id = $cartId";
mysqli_query($con,$sql);
header('location:cart.php');
}?>
For row onw everything is fine.But for row2 update button appears in row1 and not updating at all.
<input tpe="text" name="newqty" value="<?php echo $qty = $row['quantity']; ?>" onkeypress="showsubmit(<?php echo $row['cart_id'] ?>)">
<input style="visibility:hidden;width:80px;border-radius:10px;background-color:green;border:none;padding:5px;color:white;"
type="submit"
name="sub_<?php echo $row['cart_id'] ?>"
id="sub_<?php echo $row['cart_id'] ?>"
value="UPDATE">
<script>
function showsubmit(id)
{
document.getElementById("sub_"+id).style.visibility ="visible";
}
</script>

Auto submit php form

I want to submit a form after some interval periodically.
I have tried as follows.
<script language="JavaScript">
function fncAutoSubmitForm()
{
//alert('test alert');
alert("B : "+document.getElementById('myform').id);
document.getElementById('myform').submit();
alert("A : "+document.getElementById('myform').id);
setTimeout("fncAutoSubmitForm();",5000);}
</script>
displayPage.php code as follows
<body onload="fncAutoSubmitForm();">
<form id="myform" name="myform" action="code.php" method="post">
some controls
</form>
</body>
here, "displayPage.php" submits the page to "code.php"
"code.php" performs required action and redirects to "displayPage.php"
It works fine when I dont use autosubmit. i.e. fncAutoSubmitForm() function
but when I use fncAutoSubmitForm() "displayPage.php" disappears
here is the actual code
<form action="code.php" method="post" id="myform" name="myform" onload='setGenLeadId();'>
<tr><td colspan="2"><?php if($row1['lead_call_type']=="C"){echo"<font color=red>CALLBACK Lead</font>";}?></td>
<td align = "right"><strong>Lead Id :</strong> </td>
<!--<td><b><font color="red"></font>Reference Number</b></td>-->
<td align="left"><?php echo "" . $row1['lead_id'] ."";?></td>
</tr>
<tr>
<td align="right" ><b>Name :</b></td>
<td align="left"><input name="custname" id="custname" class="textbox" style="width: 100%;height: 25%;" maxlength="140" type="text" value="<?php echo htmlspecialchars($row1['lead_fname'])?>"></td>
<td align="right"><b>Phone :</b></td>
<td align="left"><input name="phone" id="phone" style="width: 100%;height: 25%;" maxlength="10" type="text" value = "<?php echo "" . $row1['lead_phone1'] ."";?>" ></td>
</tr>
<tr>
<td align="right"><b>City :</b></td>
<td align="left">
<input name="city" id="city" class="textbox" style="width: 100%;height: 25%;" maxlength="140" type="text" value="<?php echo "" . $row1['lead_city'] ."";?>">
</td>
<td align="right"><b>State :</b></td>
<td align="left" >
<input name="state" id="state" class="textbox" style="width: 100%;height: 25%;" maxlength="140" type="text" value="<?php echo "" . $row1['lead_state'] ."";?>">
</td>
</tr>
<tr>
<td align="right"><b>Email-ID :</b></td>
<td align="left" ><input name="email" id="email" style="width: 100%;height: 25%;" class="textbox" type="text" value = "<?php echo "" . $row1['lead_email'] ."";?>"></td>
<td align="right"><b>Source </b></td>
<td ><input type="text" name="source" id = "source" style ="width:100%;resize: none;" maxlength="900" value="<?php echo "". $row1['lead_source'] ."";?>"></td>
</tr>
<tr>
<td align="right"><b>Address : </b></td>
<td>
<textarea type="text" name="address" id = "address" style ="width:100%;resize: none;" maxlength="900" ><?php echo "". $row1['lead_address1'] ."";?></textarea>
</td>
<td align="right"><b>Zip Code :</b></td>
<td align="left"><input name="zip" id="zip" class="textbox" style="width: 100%;height: 25%;" maxlength="140" type="text" value="<?php echo htmlspecialchars($row1['lead_zip'])?>"></td>
<!--<td align="right"><b>Phone :</b></td>
<td align="left"><input name="phone" id="phone" style="width: 100%;height: 25%;" maxlength="10" type="text" value = "<?php //echo "" . $row1['lead_phone1'] ."";?>" ></td>-->
</tr>
<tr>
<td align="right"><b>Rounds :</b></td>
<td>
<?php
$query = mysql_query("SELECT param_field_value,param_field_itemdata FROM cti_service_parameters where param_service_id=$service_id and param_field_name='rounds'");
$k=0;
echo "<select style='width: 100%;' id='rounds' name ='rounds'>";
echo "<option value=".$row1['lead_rounds']." selected>".$row1['lead_rounds']."</option>";
while($row = mysql_fetch_array($query))
{
$value[$k] = $row['param_field_value'];
$item[$k] = $row['param_field_itemdata'];
if($field_val == $item[$k])
echo "<option value='$value[$k]' selected>$value[$k]</option>";
else
echo "<option value='$value[$k]'>$value[$k]</option>";
$k = $k + 1;
}
echo "</select>";
?>
</td>
<td align="right"><b>Preparing For IIT-JEE :</b></td>
<td align="left">
<?php
$query = mysql_query("SELECT param_field_value,param_field_itemdata FROM cti_service_parameters where param_service_id=$service_id and param_field_name='IIT-JEE'");
$k=0;
echo "<select style='width: 100%;' id='PrepIIT' name ='PrepIIT'>";
echo "<option value=".$row1['lead_prep_iit']." selected>".$row1['lead_prep_iit']."</option>";
while($row = mysql_fetch_array($query))
{
$value[$k] = $row['param_field_value'];
$item[$k] = $row['param_field_itemdata'];
if($field_val == $item[$k])
echo "<option value='$value[$k]' selected>$value[$k]</option>";
else
echo "<option value='$value[$k]'>$value[$k]</option>";
$k = $k + 1;
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td align="right"><b>Which Standard :</b></td>
<td align="left" >
<?php
$query = mysql_query("SELECT param_field_value,param_field_itemdata FROM cti_service_parameters where param_service_id=$service_id and param_field_name='standered'");
$k=0;
echo "<select style='width: 100%;' id='standared' name ='standared'>";
echo "<option value=".$row1['lead_standared']." selected>".$row1['lead_standared']."</option>";
while($row = mysql_fetch_array($query))
{
$value[$k] = $row['param_field_value'];
$item[$k] = $row['param_field_itemdata'];
if($field_val == $item[$k])
echo "<option value='$value[$k]' selected>$value[$k]</option>";
else
echo "<option value='$value[$k]'>$value[$k]</option>";
$k = $k + 1;
}
echo "</select>";
?>
</td>
<td align="right"><b>Promo DVD :</b></td>
<td align="left">
<?php
$query = mysql_query("SELECT param_field_value,param_field_itemdata FROM cti_service_parameters where param_service_id=$service_id and param_field_name='PromoDVD'");
$k=0;
echo "<select style='width: 100%;' id='dvd' name ='dvd'>";
echo "<option value=".$row1['lead_dvd']." selected>".$row1['lead_dvd']."</option>";
while($row = mysql_fetch_array($query))
{
$value[$k] = $row['param_field_value'];
$item[$k] = $row['param_field_itemdata'];
if($field_val == $item[$k])
echo "<option value='$value[$k]' selected>$value[$k]</option>";
else
echo "<option value='$value[$k]'>$value[$k]</option>";
$k = $k + 1;
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td align="right"><b>Percentage in 10th :</b></td>
<td align="left" ><input name="tenth" id="tenth" maxlength="5" style="width: 100%;height: 25%;" class="textbox" type="text" value = "<?php echo "" . $row1['lead_tenth'] ."";?>"></td>
<td align="right"><b>Percentage in 12th :</b></td>
<td align="left" ><input name="twelth" id="twelth" maxlength="5" style="width: 100%;height: 25%;" class="textbox" type="text" value = "<?php echo "" . $row1['lead_twelth'] ."";?>"> </td>
<!--<td align="right"><b>Time of Call</b></td>
<td align="left" ><input name="calltime" id="calltime" style="width: 100%;height: 25%;" class="textbox" type="text" value = "<?php// echo "" . $row1['lead_import_batch_start_date'] ."";?>" readonly> </td> -->
</tr>
<tr>
<td align="right"><b>JEE appearing year :</b></td>
<td align="left" >
<?php
$query = mysql_query("SELECT param_field_value,param_field_itemdata FROM cti_service_parameters where param_service_id=$service_id and param_field_name='JeeYear'");
$k=0;
echo "<select style='width: 100%;' id='jeeyear' name ='jeeyear'>";
echo "<option value=".$row1['lead_jee_year']." selected>".$row1['lead_jee_year']."</option>";
while($row = mysql_fetch_array($query))
{
$value[$k] = $row['param_field_value'];
$item[$k] = $row['param_field_itemdata'];
if($field_val == $item[$k])
echo "<option value='$value[$k]' selected>$value[$k]</option>";
else
echo "<option value='$value[$k]'>$value[$k]</option>";
$k = $k + 1;
}
echo "</select>";
?>
</td>
<td align="right"><b>Joined any classes :</b></td>
<td align="left">
<?php
$query = mysql_query("SELECT param_field_value,param_field_itemdata FROM cti_service_parameters where param_service_id=$service_id and param_field_name='JoinedClasses'");
$k=0;
echo "<select style='width: 100%;' id='classes' name ='classes'>";
echo "<option value=".$row1['lead_classes']." selected>".$row1['lead_classes']."</option>";
while($row = mysql_fetch_array($query))
{
$value[$k] = $row['param_field_value'];
$item[$k] = $row['param_field_itemdata'];
if($field_val == $item[$k])
echo "<option value='$value[$k]' selected>$value[$k]</option>";
else
echo "<option value='$value[$k]'>$value[$k]</option>";
$k = $k + 1;
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td align="right"><b>Remarks :</b></td>
<td colspan="3"><textarea type="text" name="remarks" id = "remarks" style ="width:100%;resize: none;" maxlength="900" ><?php echo "". $row1['lead_remarks'] ."";?></textarea> </td>
</tr>
<tr>
<td colspan=4 class="tableHeading">
<!--<b><font color="red">Note : Fields with * are Mandatory</font></b>-->
</td>
</tr>
<!--<input type="hidden" id="clinicFlag" name="clinicFlag" value="<?php// echo $_GET["clinicFlag"]?>">-->
<tr>
<tr>
<td colspan=4 style="padding:0px">
<div align="center">
<input title="Save [Alt+S]" accessKey="S" class="crmbutton small save" type="button" name="save" value=" Save " style="width:100px;height:30px" >
</td>
</div>
</tr>
</table>
</div>
and Code.php code is as follows
<?php
//session_start();
//echo $_SESSION['user'];
include("connection.php");
$lead = $_POST['lead'];
$callnumber = $_POST['callnumber'];
$service = $_POST['service'];
$lead_fname = $_POST['custname'];
$lead_phone1 = $_POST['phone'];
$lead_city = $_POST['city'];
$lead_email = $_POST['email'];
$lead_state = $_POST['state'];
$lead_address1 = $_POST['address'];
$lead_zip = $_POST['zip'];
$lead_rounds = $_POST['rounds'];
$lead_IIT = $_POST['PrepIIT'];
$lead_standared = $_POST['standared'];
$lead_dvd = $_POST['dvd'];
$lead_tenth = $_POST['tenth'];
$lead_twelth = $_POST['twelth'];
$lead_jee_year = $_POST['jeeyear'];
$lead_classes = $_POST['classes'];
$lead_remarks = $_POST['remarks'];
$lead_source = $_POST['source'];
if($GLOBALS['database_type'] == "MySql")
{
$con=mysql_connect($GLOBALS['database_ip'],$GLOBALS['database_username'],$GLOBALS['database_password']);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($GLOBALS['database_name'],$con);
$sql1 = mysql_query("SELECT service_outbound_lead_dsn_string,
service_outbound_lead_db_user,
service_outbound_lead_db_password,
service_leadstructure_master_tablename,
service_outbound_lead_db_name
FROM cti_services WHERE service_id = $service");
while($row = mysql_fetch_array($sql1))
{
$lead_dsn = $row['service_outbound_lead_dsn_string'];
$lead_user = $row['service_outbound_lead_db_user'];
$lead_pwd = $row['service_outbound_lead_db_password'];
$lead_table = $row['service_leadstructure_master_tablename'];
$lead_db = $row['service_outbound_lead_db_name'];
}
if($_POST['save'])
{
//input_app_datetime = '$lead_appointment',
//input_app_reschedule = '$lead_reschedule',
mysql_select_db($GLOBALS['database_name'],$con);
$sqlquery = ("UPDATE $lead_db.$lead_table set lead_fname = '$lead_fname', lead_phone1 = '$lead_phone1', lead_email = '$lead_email', lead_remarks = '$lead_remarks', lead_address1 = '$lead_address1', lead_state = '$lead_state', lead_city = '$lead_city', lead_zip = '$lead_zip', lead_rounds ='$lead_rounds', lead_prep_iit ='$lead_IIT', lead_standared ='$lead_standared', lead_dvd ='$lead_dvd', lead_tenth ='$lead_tenth', lead_twelth ='$lead_twelth', lead_jee_year ='$lead_jee_year', lead_classes ='$lead_classes', lead_source ='$lead_source' WHERE lead_id=$lead");
$dbSql = mysql_query($sqlquery) or die("Error : " . mysql_error());
$sql="update cti_call_master set crm_remarks='$lead_remarks' where call_number=$callnumber";
$dbSql1 = mysql_query($sql);
//$flag = "saved";
$message = "Lead Id-".$lead." Data Saved .....";
//$message = $sqlquery;
//header("location:vision.php?LEADID=$lead&SERVICEID=$service&CALLNUMBER=$callnumber&MESSAGE=$message&FLAG=$flag&CLI=$lead_phone1&clinicFlag=$clinicFlag&alterno=$alter_no");
header("location:displayPage.php?LEADID=$lead&SERVICEID=$service&CALLNUMBER=$callnumber&MESSAGE=$message&FLAG=$flag&CLI=$lead_phone1");
}
}
?>
You can call the following function at 'onload' event. It will submit the form after 5 second to your code.php
function fncAutoSubmitForm() {
setTimeout(function(){
document.getElementById('myform').submit();
}, 5000);
}
Then your code.php will process the form action and redirect it back to displayPage.php.
Can you check if your form is not submitted at all to code.php or it is being submitted to code.php and due to some error it fails to redirect back to displayPage.php. In the later case you can turn ON the display error settings if it is not already ON. Use following in code.php to enable:
error_reporting(E_ALL);
ini_set('display_errors',1);
It it doesn't help then pls provide the code to get the actual scenario here.
As you call fncAutoSubmitForm() onload of displayPage.php, it immediately triggers document.getElementById('myform').submit();
So you are redirected to code.php, the action of your form.
If you want a delay you should not apply fncAutoSubmitForm() onload of the page.
but more something like:
setTimeout("fncAutoSubmitForm();",5000);}
function fncAutoSubmitForm(){
document.getElementById('myform').submit();
}
But you won't stay on displayPage.php it will redirect you to code.php. If you want to always display the same page you needs to change the action target in your form.
Use jQuery :)
$(document).ready(function(){
setInterval(function(){
submit();
}, 1000);
});
function submit(){
var data;
// extract data from your form and save it to data variable
$.ajax({
type: "POST",
url: "some.php",
data: data
});
}

I'm trying to pull data from database into selectboxes

I'm trying to pull data from database into selectboxes, but when the data is pulled it goes into one 'td' and not into separate td's. I'm trying to achieve result as shown below
but I keep getting this result
here is my code
<?php
$data_array = array();
$result2 = mysql_query("SELECT * FROM `firefightersonscene`
JOIN `firefighterinfo` ON `firefightersonscene`.`FireFighterInfo_fighterID` = `firefighterinfo`.`fighterID`
JOIN `stationlocation` ON `firefighterinfo`.`StationLocation_locationID`=`stationlocation`.`locationID`
WHERE `IncidenceOfFire_incidentID`='$getIncID' ORDER BY `firstName`");
if(mysql_num_rows($result2) > 0)
{
while($rows2 = mysql_fetch_object($result2))
{
$data_array[] = $rows2;
}
}
?>
<form action="core_viewfireoccurrence.php?incidentID=<?php echo $rows->incidentID; ?>" method="post" class="view_occurrence_form">
<table id="myTable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<tr>
<td class="count">1</td>
<td>
<?php
foreach($data_array as $rows2):
$fighterID = $rows2->FireFighterInfo_fighterID;
$results = mysql_query("SELECT `fighterID`, `firstName`, `middleName`, `lastName`, `stationlocation`.`exactlocation`
FROM `firefighterinfo`
JOIN `stationlocation` ON `firefighterinfo`.`StationLocation_locationID`=`stationlocation`.`locationID` ORDER BY `firstName`");
echo '<select name="fireman[]" required><option value=""></option>';
while($row = mysql_fetch_array($results))
{
if($row['fighterID'] == $fighterID)
echo '<option selected>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
else
echo '<option>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
}// end while
echo '</select><br>';
endforeach;
?>
</td>
<td>
<input type="button" value="X" class="removeVar"/>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input type="button" id="addVar" value="Add Item"/>
</tr>
</tfoot>
</table>
</form>
JS CODE
<script type="text/javascript">
$('form').on('click', '.removeVar', function(){
$(this).closest('tr').remove();
$('.count').each(function(i){
$(this).text(i + 1);
});
});
//add a new node
$('#addVar').on('click', function(){
var varCount = $('#myTable tr').length - 1;
$node = ['<tr>',
'<td class="count">'+varCount+'</td>',
'<td><select name="fireman[]" class="ctlGroup" required>',
'<option value=""></option>',
'<?php require("php/fireman_list.php"); ?>',
'</select></td>',
'<td><input type="button" value="X" class="removeVar"/>',
'</td></tr>'].join('\n');
$('#myTable > tbody:last').append($node);
});
</script>
You need to put your whole table row in the loop. You will also need to add a variable to count the row number for you.
<?php
$row =1;
foreach($data_array as $rows2):
?>
<tr>
<td class="count"><?php echo $row; ?></td>
<td>
<?php
$fighterID = $rows2->FireFighterInfo_fighterID;
$results = mysql_query("SELECT `fighterID`, `firstName`, `middleName`, `lastName`, `stationlocation`.`exactlocation`
FROM `firefighterinfo`
JOIN `stationlocation` ON `firefighterinfo`.`StationLocation_locationID`=`stationlocation`.`locationID` ORDER BY `firstName`");
echo '<select name="fireman[]" required><option value=""></option>';
while($row = mysql_fetch_array($results))
{
if($row['fighterID'] == $fighterID)
echo '<option selected>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
else
echo '<option>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
}// end while
echo '</select><br>';
?>
</td>
<td>
<input type="button" value="X" class="removeVar"/>
</td>
</tr>
<?php
$row++;
endforeach;
?>

Categories