Can anybody help me understand why this update query isn't updating the fields in db.
<?php
$id= $_GET['id'];
$query1 = mysql_query("SELECT * FROM invoice WHERE id=$id limit 1");
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="card">
<div class="card-header">
<strong>Create Tax</strong>
</div> <?php
while($query2=mysql_fetch_array($query1)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
?>
<div class="card-block">
<div class="col-sm-6">
<div class="form-group">
<label for="company">Coustomer Name</label>
<input type="text" class="form-control" id="company" name="cname" value="<?php echo $query2['CustomerName']?>" placeholder="Coustomer Name">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="company">Coustomer Mobile </label>
<input type="text" class="form-control" id="company" name="mobile" value="<?php echo $query2['CustomerMobile']?>" placeholder="Coustomer Mobile">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="company">Email</label>
<input type="text" class="form-control" id="company" name="email" value="<?php echo $query2['Email']?>" placeholder="Email">
</div>
</div> <div class="col-sm-6">
<div class="form-group">
<label for="company">Coustomer Streat </label>
<input type="text" class="form-control" id="company" name="streat" value="<?php echo $query2['CustomerStreat']?>" placeholder="Coustomer Streat">
</div>
</div> <div class="col-sm-6">
<div class="form-group">
<label for="company">Coustomer City</label>
<input type="text" class="form-control" id="company" name="city" value="<?php echo $query2['CustomerCity']?>" placeholder="Coustomer City">
</div>
</div> <div class="col-sm-6">
<div class="form-group">
<label for="company">Coustomer State</label>
<input type="text" class="form-control" id="company" name="state" value="<?php echo $query2['CustomerState']?>" placeholder="Coustomer State">
</div>
</div> <div class="col-sm-6">
<div class="form-group">
<label for="company">Coustomer Country</label>
<input type="text" class="form-control" id="company" name="country" value="<?php echo $query2['CustomerCountry']?>" placeholder="Coustomer Country">
</div>
</div> <div class="col-sm-6">
<div class="form-group">
<label for="company">Zip/Pin Code</label>
<input type="text" class="form-control" id="company" name="pin" value="<?php echo $query2['ZipCode']?>" placeholder="ZipCode">
</div>
</div>
<?php } ?>
<div class="col-sm-6">
<div class="form-group">
<label for="company">Tax Name </label><?php
$query1 = mysql_query("SELECT * FROM Tax");
?>
<select id="select" name="tax" class="form-control" size="1"><?php
while($query2=mysql_fetch_array($query1)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
?>
<option value="<?php echo $query2['NameOfTax']?> , <?php echo $query2['TaxPercentage']?>"><?php echo $query2['NameOfTax']?> , <?php echo $query2['TaxPercentage']?></option>
<?php $taxvalue = $query2['TaxPercentage']; ?> <?php } ?>
</select>
</div>
</div> <div class="col-sm-6">
<div class="form-group">
<label for="company">Iteam Name </label>
<input type="text" class="form-control" id="company" name="item" placeholder="Iteam Name" value="<?php echo $query2['ItemName']?>">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="company">Iteam Price </label>
<input type="text" class="form-control" id="company" name="itemprice" placeholder="Iteam price" value="<?php echo $query2['ItemPrice']?>">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="company">Paid Ammount </label>
<input type="text" class="form-control" id="company" name="pammount" placeholder="Paid Ammount" value="<?php echo $query2['PaidAmmount']?>">
</div>
</div> <div class="col-sm-6">
<div class="form-group">
<label for="company">Date</label>
<input type="text" class="form-control" id="company" name="date" placeholder="Date" value="<?php echo $query2['Date']?>">
</div>
</div>
<div class="col-sm-12">
<input type="submit" class="btn btn-outline-success" name="submit" value="Processe Invoice"/>
</div>
</div>
</div>
</div>
</div>
<!--/col-->
</form>
<?php
$cname = $_POST['cname'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$streat = $_POST['streat'];
$city = $_POST['city'];
$state = $_POST['state'];
$country = $_POST['country'];
$pin = $_POST['pin'];
$tax = $_POST['tax'];
$item = $_POST['item'];
$itemprice = $_POST['itemprice'];
$percent = ($taxvalue / 100) * $itemprice ;
$tammount = $percent + $itemprice;
$pammount = $_POST['pammount'];
$uammount = $tammount - $pammount;
$date = $_POST['date'];
$ip = $_SERVER['REMOTE_ADDR'];
$date1 = date('h,i,s');
if(isset($_POST['submit']))
{
$sql = "UPDATE `ero`.`invoice` SET `CustomerName` = '$cname', `CustomerMobile` = '$mobile', `Email` = '$email', `CustomerStreat` = '$streat', `CustomerCity` = '$city', `CustomerState` = '$state', `CustomerCountry` = '$country', `ZipCode` = '$pin', `TaxName` = '$tax', `ItemName` = '$item', `ItemPrice` = '$itemprice', `TotalAmmount` = '$tammount', `PaidAmmount` = '$pammount', `UnpaidAmmount` = '$uammount', `Date` = '$date', `IP` = '$ip', `DateTime` = '$date1' WHERE `invoice`.`id` = '$id'";
$result = mysql_query($sql);
if($result)
$url='customer.php';
echo '<script>window.location = "'.$url.'";</script>';
die;
}
?>
invoice.php
<?php
$query1 = mysql_query("SELECT * FROM invoice");
?>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Customer Name</th>
<th>Mobile</th>
<th>Email</th>
<th>City</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Tax</th>
<th>Total Ammount</th>
<th>Paid Ammount</th>
<th>Unpaid Ammount</th>
<th>Action</th>
</tr>
</thead>
<tbody><?php
while($query2=mysql_fetch_array($query1)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
?>
<tr>
<td><?php echo $query2['CustomerName']?></td>
<td><?php echo $query2['CustomerMobile']?></td>
<td><?php echo $query2['Email']?></td>
<td><?php echo $query2['CustomerCity']?></td>
<td><?php echo $query2['ItemName']?></td>
<td><?php echo $query2['ItemPrice']?></td>
<td><?php echo $query2['TaxName']?></td>
<td><?php echo $query2['TotalAmmount']?></td>
<td><?php echo $query2['PaidAmmount']?></td>
<td <?php if ($query2['UnpaidAmmount'] > 1) echo 'style="background-color:#FF0000"' ?>><?php if ($query2['UnpaidAmmount'] < 1) echo "Ammount Paid"; else echo $query2['UnpaidAmmount'];?></td>
<td>
<button type="button" class="btn btn-outline-danger btn-sm"><a href="DeleteInvoice.php?id='<?php echo $query2['id'] ?>'" >Delete</a>
<button type="button" class="btn btn-outline-success btn-sm"><a href="ViewInvoice.php?id='<?php echo $query2['id'] ?>'" >View</a></button>
<button type="button" class="btn btn-outline-success btn-sm"><a href="updatecheck.php?id='<?php echo $query2['id'] ?>'" >Update</a></button>
</div> </td> </tr> <?php } ?>
<tr>
this scripts redirects customer.php.if i place a manual id like id = 38. its wroking. but there is no update in MySql Table.i am new to programming please explain with some code examples.
Thanks
Replace single quote in the query with double quotes and since you are already using the double quotes for the query, escape the double quotes for the variables or use string concatenation.
<?php
$id = $_GET['id'];
$cname = $_POST['cname'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$streat = $_POST['streat'];
$city = $_POST['city'];
$state = $_POST['state'];
$country = $_POST['country'];
$pin = $_POST['pin'];
$tax = $_POST['tax'];
$item = $_POST['item'];
$itemprice = $_POST['itemprice'];
$percent = ($taxvalue / 100) * $itemprice;
$tammount = $percent + $itemprice;
$pammount = $_POST['pammount'];
$uammount = $tammount - $pammount;
$date = $_POST['date'];
$ip = $_SERVER['REMOTE_ADDR'];
$date1 = date('h,i,s');
if (isset($_POST['submit']))
{
$sql = "UPDATE `ero`.`invoice` SET `CustomerName` = \"$cname\", `CustomerMobile` = \"$mobile\", `Email` = \"$email\", `CustomerStreat` = \"$streat\", `CustomerCity` = \"$city\", `CustomerState` = \"$state\", `CustomerCountry` = \"$country\", `ZipCode` = \"$pin\", `TaxName` = \"$tax\", `ItemName` = \"$item\", `ItemPrice` = \"$itemprice\", `TotalAmmount` = \"$tammount\", `PaidAmmount` = \"$pammount\", `UnpaidAmmount` = \"$uammount\", `Date` = \"$date\", `IP` = \"$ip\", `DateTime` = \"$date1\" WHERE `invoice`.`id` = \"$id\"";
$result = mysql_query($sql);
if ($result) $url = 'customer.php';
echo '<script>window.location = "' . $url . '";</script>';
die;
?>
UPDATE table
SET col_name = 'new value'
WHERE condition
this is the syntax for updating in sql, try deleting the ``
Related
I am having two different database tables questions and choices where i am inserting questions in one table and multiple choices in another table where questions table id is foreign key in choices table.
Questions:
Questions_number Text
1 What is HTML?
2 What is PHP?
Choices:
id question_number is_correct text
1 1 1 markup
2 1 0 Hyext
3 1 0 Hyper text markup language
4 2 0 hsdfd
5 2 0 frfwer
6 2 1 Hypertext Preprocessor
If i am trying to edit question number 1 then i need to fetch all the details of questions,Choices and correct option as well.But when i am trying to edit the record for choices as well i am getting the same data which i am getting for question.
HTML:
<?php session_start();
include 'includes/db.php';
$id = (int)$_GET['id'];
$sql = "SELECT * FROM questions q WHERE q.question_number = $id ";
$oppointArr =array();
$result = mysqli_query($mysqli,$sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result))
{
$oppointArr = $row;
echo "Text: " . $row["text"]. "<br>";
}
} else {
echo "0 results";
}
?>
<form class="form-horizontal" action="updatequestions.php" method="post" role="form">
<?php if(isset($msg)) {?>
<div class="<?php echo $msgclass; ?>" id="mydiv" style="padding:5px;"><?php echo $msg; ?></div>
<?php } ?>
<input type='hidden' value='<?=$id;?>' name='question_number'>
<h2>Edit A Question</h1>
<div class="form-group">
<label for="questionno" class="col-sm-2 control-label">Question Number</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['question_number'];?>"
name="question_number" id="question_number" readonly>
</div>
</div>
<div class="form-group">
<label for="question" class="col-sm-2 control-label">Question</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['text'];?>" name="question_text" id="question_text">
</div>
</div>
<input type='hidden' value='<?=$id;?>' name='id'>
<h2>Edit A Choice</h1>
<div class="form-group">
<label for="choice #1" class="col-sm-2 control-label">Choice #1</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['choice1'];?>" name="choice1" id="choice1">
</div>
</div>
<div class="form-group">
<label for="choice #2" class="col-sm-2 control-label">Choice #2</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['choice2'];?>" name="choice2" id="choice2">
</div>
</div>
<div class="form-group">
<label for="choice #3" class="col-sm-2 control-label">Choice #3</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['choice3'];?>" name="choice3" id="choice3">
</div>
</div>
<div class="form-group">
<label for="Correct Choice Number:" class="col-sm-2 control-label">Correct Choice Number:</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['is_correct'];?>" name="is_correct" id="is_correct">
</div>
</div>
<div class="col-sm-offset-2">
<button type="submit" class="btn btn-default" name="submit_user" id="subject">Submit</button>
<button type="cancel" class="btn btn-raised">Cancel</button>
</div>
</form>
Updatequestions:
<?php
include 'includes/db.php';
if(isset($_POST['submit_user']))
{
$questiontext = $_POST['question_text'];
$id=$_POST['question_number'];
$correct_choice = $_POST['correct_choice'];
$choices = array();
$choices[1] = $_POST['choice1'];
$choices[2] = $_POST['choice2'];
$choices[3] = $_POST['choice3'];
$choices[4] = $_POST['choice4'];
$choices[5] = $_POST['choice5'];
$query = "UPDATE questions SET text='$questiontext' WHERE question_number = $id";
$insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($insert_row) {
foreach($choices as $choice => $value){
if($value != ''){
if($correct_choice == $choice){
$is_correct = 1;
} else {
$is_correct = 0;
}
$query = "UPDATE choices SET is_correct='$is_correct', text='$value' WHERE question_number=$id";
$insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($insert_row){
continue;
} else {
die('Error : ('.$mysqli->errno . ') '. $mysqli->error);
}
}
}
$msg = 'Question has been added';
}
}
?>
If i try to update the record all the fields are updating with the same data.
WARNING: Do not create SQL statements by concatenating the data with SQL. Use prepared statements.
As for your problem, you use the foreign key of the question to update choices. The key is not the primary key of choices and is not unique. Try using the unique primary key for your SQL.
Instead of this:
$query = "UPDATE choices SET is_correct='$is_correct', text='$value' WHERE question_number=$id";
try this:
$query = "UPDATE choices SET is_correct='$is_correct', text='$value' WHERE id=$choice ";
But of course you should really try to do it all over again using prepared statements instead!
<form class="form-horizontal" action="updatequestions.php" method="post" role="form">
<?php if(isset($msg)) {?>
<div class="<?php echo $msgclass; ?>" id="mydiv" style="padding:5px;"><?php echo $msg; ?></div>
<?php } ?>
<input type='hidden' value='<?=$id;?>' name='question_number'>
<h2>Edit A Question</h1>
<div class="form-group">
<label for="questionno" class="col-sm-2 control-label">Question Number</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['question_number'];?>"
name="question_number" id="question_number" readonly>
</div>
</div>
<div class="form-group">
<label for="question" class="col-sm-2 control-label">Question</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['text'];?>" name="question_text" id="question_text">
</div>
</div>
<input type='hidden' value='<?=$id;?>' name='id'>
<h2>Edit A Choice</h1>
<?php
$choicesql = "SELECT * FROM `choices` WHERE question_number = $id ";
$ChoicetArr =array();
$choiceresult = mysqli_query($mysqli,$choicesql);
$inc=1;
$correctAns ="";
if (mysqli_num_rows($choiceresult) > 0)
{
while($rows = mysqli_fetch_array($choiceresult))
{
$ChoicetArr[] = $rows;
?>
<div class="form-group">
<label for="choice #<?php echo $inc;?>" class="col-sm-2 control-label">Choice #<?php echo $inc;?></label>
<div class="col-sm-5">
<input type="hidden" name="choice_id<?php echo $inc;?>" value="<?php echo $rows['id'];?>">
<input type="text" class="form-control" value="<?php echo $rows['text'];?>" name="choice<?php echo $inc;?>" id="choice<?php echo $inc;?>">
</div>
</div>
<?php
//print_r($rows);
if($rows['is_correct']=="1"){
$correctAns = '<input type="hidden" name="choice_id'.$inc.'" value="'.$rows['id'].'"><div class="form-group">
<label for="Correct Choice Number:" class="col-sm-2 control-label">Correct Choice Number:</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="'.$inc.'" name="is_correct" id="is_correct">
</div>
</div>';
}
$inc++;
}
}
echo $correctAns;
?>
<div class="col-sm-offset-2">
<button type="submit" class="btn btn-default" name="submit_user" id="subject">Submit</button>
<button type="cancel" class="btn btn-raised">Cancel</button>
</div>
</form>
updatequestions.php
<?php
include 'includes/db.php';
if(isset($_POST['submit_user']))
{
$questiontext = $_POST['question_text'];
$id=$_POST['question_number'];
$correct_choice = $_POST['is_correct'];
$choices = array();
$choices[] = array("question"=>$_POST['choice1'], "answer"=>$_POST['choice_id1']);
$choices[] = array("question"=>$_POST['choice2'], "answer"=>$_POST['choice_id2']);
$choices[] = array("question"=>$_POST['choice3'], "answer"=>$_POST['choice_id3']);
$choices[] = array("question"=>$_POST['choice4'], "answer"=>$_POST['choice_id4']);
$choices[] = array("question"=>$_POST['choice5'], "answer"=>$_POST['choice_id5']);
$query = "UPDATE questions SET text='$questiontext' WHERE question_number = $id";
$insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($insert_row)
{
$inc= 0;
foreach($choices as $choice => $value){
if(count($value)>0){
$answerInc = $choice+1;
if($correct_choice == $answerInc){
$is_correct = 1;
} else {
$is_correct = 0;
}
$text= $value['question'];
$answer = $value['answer'];
//echo "<br>".$text;
//print_r($value);
echo $answerInc;
echo "<br>";
echo $query = "UPDATE choices SET is_correct='$is_correct', text='$text' WHERE id=$answer";
$insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($insert_row){
continue;
} else {
die('Error : ('.$mysqli->errno . ') '. $mysqli->error);
}
}
$inc++;
}
$msg = 'Question has been Updated Successfully';
header("location:searchquestions.php");
exit;
}
}
?>
This is my first time using multiple select options and add more field function in form. I have this form where I can enter multiple serialNumber and also add multiple accessories and quantity accordingly. But the only first selected serialNumber and accessories (and quantity) saved in my database.
So here is my HTML Form:
<form id="form1" name="form1" method="post" action="requisitionForm_process.php" onsubmit="return validateForm()" >
<div class="form-group">
<label for="DONO">DO. Number: </label>
<input class="form-control" id="DONO" name="DONO" placeholder="Place DO. Number Here" type="text"/>
</div>
<div class="form-group">
<label for="requestby">Request By: </label>
<select class="form-control" id="empCode" name="empCode">
<?php while ($row = mysqli_fetch_array($resultR)):;?>
<option value = <?php echo $row ['empCode']; ?>><?php echo $row ['empCode']; echo ":"; echo $row ['empName'];?></option>
<?php endwhile;
?>
</select>
</div>
<div class="form-group">
<label for="requestby">Customer: </label>
<select class="form-control" id="customerCode" name="customerCode">
<?php while ($row = mysqli_fetch_array($resultC)):;?>
<option value = <?php echo $row ['customerCode']; ?>><?php echo $row ['customerCode']; echo ":"; echo $row ['customerName'];?></option>
<?php endwhile;
?>
</select>
</div>
<div class="form-group"> <!-- Date input -->
<label class="control-label" for="dateOUT">Date:</label>
<input class="form-control" id="dateOUT" name="dateOUT" placeholder="DD/MM/YYY" type="text"/>
</div>
<div class="form-group">
<label for="categoryCode">Category: </label>
<select class="form-control" id="categoryCode" name="categoryCode">
<option value="new"> New Installation</option>
<option value="re">Re-installation</option>
</select>
</div>
<div class="form-group">
<label for="categoryCode">Product: </label>
<select class="form-control" id="productCode" name="productCode">
<?php while ($row = mysqli_fetch_array($result)):;?>
<option value = <?php echo $row ['productCode']; ?>><?php echo $row ['productCode']; echo ":"; echo $row ['productName'];?></option>
<?php endwhile;
?>
</select>
</div>
<div class="form-group">
<label for="serialNumber">Serial Number:</label><br>
<select id="serialNumber" name="serialNumber[]" multiple class="form-control" >
<?php while ($row = mysqli_fetch_array($resultSe)):;?>
<option value = <?php echo $row ['serialNumber']; ?>><?php echo $row ['serialNumber'];?></option>
<?php endwhile;?>
</select>
</div>
<table class="table table-bordered" id="item_table">
<tr>
<th>Select Accessories</th>
<th>Enter Quantity</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
<div class="form-group">
<input type="button" class="btn" id="checkBtn" name="return" value="Back" onClick="javascript: window.history.back(-1)";>
<input class="btn btn-primary" type="reset" value="Reset">
<input align="right" type="submit" class="btn btn-info" value="Submit Button">
</div>
</div>
</form>
And this is my PHP process:
<?php
if(isset($_POST["serialNumber"]))
{
$serialNumber = '';
foreach($_POST["serialNumber"] as $row)
{
$serialNumber .= $row . ', ';
}
$serialNumber = substr($serialNumber, 0, -2);
if(isset($_POST["categoryCode"]))
{
$connect = new PDO("mysql:host=localhost;dbname=ims", "root", "");
$DONO = $_POST["DONO"];
$empCode = $_POST["empCode"];
$customerCode = $_POST["customerCode"];
$categoryCode = $_POST["categoryCode"];
$productCode = $_POST["productCode"];
$dateOUT = date('Y-m-d', strtotime($_POST['dateOUT']));
for($count = 0; $count < count($_POST["accID"]); $count++)
{
$query = "INSERT INTO requisition (DONO, empCode, customerCode, dateOUT, categoryCode, productCode, serialNumber, quantityAcc, accID) VALUES (:DONO, :empCode, :customerCode, :dateOUT, :categoryCode, :productCode, :serialNumber, :quantityAcc, :accID) ";
$statement = $connect->prepare($query);
$statement->execute(
array(
':DONO' => $DONO,
':empCode' => $empCode,
':customerCode' => $customerCode,
':dateOUT' => $dateOUT,
':categoryCode' => $categoryCode,
':productCode' => $productCode,
':serialNumber' => $serialNumber,
':quantityAcc' => $_POST["quantityAcc"][$count],
':accID' => $_POST["accID"][$count]
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
echo 'ok';
}
}
}
?>
if(isset($_POST["test"]))
{
$serialNumber = '';
foreach($_POST["test"] as $row=>$value)
{
$serialNumber .= $value . ', ';
}
$serialNumber = substr($serialNumber, 0, -2);
}
Replace yor loop with this , before i was unable to html.
<?php
if(isset($_POST["submit"]))
if (!empty($_FILES["uploadImage"]["name"])) {
//Including dbconfig file.
require 'config.php';
$ImageSavefolder = "images/student/";
move_uploaded_file($_FILES["uploadImage"]["tmp_name"] ,
"$ImageSavefolder".$_FILES["uploadImage"]["name"]);
$name = mysqli_real_escape_string($conn, $_POST['name']);
$fathername = mysqli_real_escape_string($conn, $_POST['fathername']);
$htno = mysqli_real_escape_string($conn, $_POST['htno']);
$phoneno = mysqli_real_escape_string($conn, $_POST['phoneno']);
$department = mysqli_real_escape_string($conn, $_POST['department']);
$class = mysqli_real_escape_string($conn, $_POST['class']);
$address = mysqli_real_escape_string($conn, $_POST['address1']);
$address2 = mysqli_real_escape_string($conn, $_POST['address2']);
$city = mysqli_real_escape_string($conn, $_POST['city']);
$state = mysqli_real_escape_string($conn, $_POST['state']);
$zip = mysqli_real_escape_string($conn, $_POST['zip']);
$sql= "INSERT INTO student_detail(name,fathername,htno,phoneno,department,class,address1,address2,city,state,zip) VALUES ('$name','$fathername','$htno','$phoneno','$department','$class','$address','$address2','$city','$state','$zip','".$_FILES['uploadImage']['name']."')";
if(!mysqli_query($conn,$sql))
{
echo "Not Updated";
}
else
{
echo "<br><div class='alert alert-success' role='alert'>Added Sucessfully !</div>";
}
}
?>
This code is not working for adding the following data into database. Did I do anything wrong? Please help me sort the problem.
I already created database with config.php
Form Data
<form method="post" action="" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-md-6">
<label for="name">Name</label>
<input type="text" class="form-control" placeholder="Please Enter Name" name="name">
</div>
<div class="form-group col-md-6">
<label for="fathername">Father's Name</label>
<input type="text" class="form-control" placeholder="Please Enter Father's Name" name="fathername">
</div>
<div class="form-group col-md-6">
<label for="htno">Hall Ticket/ Roll No.</label>
<input type="text" class="form-control" placeholder="Please Enter Hall Ticket/ Roll No." name="htno">
</div>
<div class="form-group col-md-6">
<label for="phoneno">Phone Number</label>
<input type="text" class="form-control" placeholder="Please Enter Phone No." name="phoneno">
</div>
<div class="form-group col-md-6">
<label for="department">Department</label>
<select class="form-control" name="department">
<option selected="selected">Choose your Department</option>
<?php
require('config.php');
$result = mysqli_query($conn,"SELECT * FROM department");
while($test= mysqli_fetch_array($result))
{
echo "<option value='".$test['department_name']."'>".$test['department_name']."</option>";
}
?>
</select>
</div>
<div class="form-group col-md-6">
<label for="class">Class</label>
<select class="form-control" name="class">
<option selected="selected">Choose your Class</option>
<?php
require('config.php');
$result = mysqli_query($conn,"SELECT * FROM class");
while($test= mysqli_fetch_array($result))
{
echo "<option value='".$test['class_name']."'>".$test['class_name']."
</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="address">Address</label>
<input type="text" class="form-control" placeholder="House No./Flat No." name="address1">
</div>
<div class="form-group">
<label for="address2">Address 2 (Optional)</label>
<input type="text" class="form-control" placeholder="Locality/Area/Street" name="address2">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="city">City</label>
<input type="text" class="form-control" name="city">
</div>
<div class="form-group col-md-4">
<label for="state">State</label>
<select class="form-control" name="state">
<option selected="selected"name="bihar">bihar</option>
<option>...</option>
</select>
</div>
<div class="form-group col-md-2">
<label for="zip">Zip</label>
<input type="text" class="form-control" name="zip">
</div>
<div class="form-group col-md-6">
<label for="profile">Profile Pic</label><br>
<input type="file" accept="image/*" onchange="loadFile(event)" name="uploadImage" id="uploadImage">
<img id="output" style="width:20%;"/>
<script>
var loadFile = function(event) {
var reader = new FileReader();
reader.onload = function(){
var output = document.getElementById('output');
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
};
</script>
</div>
</div>
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
you are trying to insert extra value which is not exist in query see here.
your field
(name,fathername,htno,phoneno,department,class,address1,address2,city,state,zip)
and your values
('$name','$fathername','$htno','$phoneno','$department','$class','$address','$address2','$city','$state','$zip','".$_FILES['uploadImage']['name']."')
you need to do add image field also
your full query
$sql= "INSERT INTO student_detail(name,fathername,htno,phoneno,department,class,address1,address2,city,state,zip,imageFieldName) VALUES ('$name','$fathername','$htno','$phoneno','$department','$class','$address','$address2','$city','$state','$zip','".$_FILES['uploadImage']['name']."')";
<?php
/* dbconnection.php file
$conn = mysqli_connect("localhost","root","12345") or die (mysqli_error());
mysqli_select_db($conn,"student") or die (mysqli_error());
*/
//Including dbconnection file here
include('dbconnection.php');
if(isset($_POST["submit"]))
{
if (!empty($_FILES["uploadImage"]["name"]))
{
$ImageSavefolder = "images/student/";
$name = $_FILES["uploadImage"]["name"];
$tmp_name = $_FILES["uploadImage"]["tmp_name"];
move_uploaded_file(tmp_name, $ImageSavefolder.$name);
$sql = "INSERT INTO students (name,fathername,htno,phoneno,department,class,address1,address2,city,state,zip,image) VALUES ('".$_POST["name"]."','".$_POST["fathername"]."','".$_POST["htno"]."','".$_POST["phoneno"]."','".$_POST["department"]."','".$_POST["class"]."','".$_POST["address1"]."','".$_POST["address2"]."','".$_POST["city"]."','".$_POST["state"]."','".$_POST["zip"]."','".$name."')";
if ($conn->query($sql) === TRUE)
{
echo "<script type= 'text/javascript'>alert('Record Inserted Successfully');</script>";
}
else
{
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
}
}
?>
Data in 'lcAmount' in the database is '15' for 4 rows and I want to call it to multiple textbox per row.
Database:
HTML CODE:
<div class="form-group">
<label class="control-label col-lg-4">Sick leave unconsumed</label>
<div class="col-lg-3">
<input type="text" id="sickLeave" name="sickLeave" class="form-control" <?php echo $sickUnconsumed; ?> />
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-4">Vacation uncomsumed</label>
<div class="col-lg-3">
<input type="text" id="vacation" name="vacation" class="form-control" <? php echo $vacationUnconsumed ?>/>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-4">Maternity uncomsumed</label>
<div class="col-lg-3">
<input type="text" id="inpUN" name="inpUN" class="form-control" <? php echo $maternityUnconsumed ?>/>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-4">Emergency uncomsumed</label>
<div class="col-lg-3">
<input type="text" id="inpUN" name="inpUN" class="form-control" <? php echo $emergencyUnconsumed ?>/>
</div>
</div>
Controller PHP
$query = "SELECT lcAmount FROM leavecounts WHERE accountID = ?";
while($row = mysql_fetch_array($query)){
$sickUnconsumed = $row['lcAmount'];
$vacationUnconsumed = $row['lcAmount'];
$maternityUnconsumed = $row['lcAmount'];
$emergencyUnconsumed = $row['lcAmount'];
}
Answer
$query = "SELECT lcAmount FROM leavecounts WHERE accountID = ? and ltypeID =1";
$params1 = array($accID);
$stmt = sqlsrv_query($con, $query, $params1);
while($row1 = sqlsrv_fetch_array($stmt)){
$sickUnconsumed = $row1['lcAmount'];
}
$query1 = "SELECT lcAmount FROM leavecounts WHERE accountID = ? and ltypeID =2";
$params2 = array($accID);
$stmt1 = sqlsrv_query($con, $query1, $params2);
while($row2 = sqlsrv_fetch_array($stmt1)){
$vacationUnconsumed = $row2['lcAmount'];
}
$query2 = "SELECT lcAmount FROM leavecounts WHERE accountID = ? and ltypeID =3";
$params3 = array($accID);
$stmt2 = sqlsrv_query($con, $query2, $params3);
while($row3 = sqlsrv_fetch_array($stmt2)){
$maternityUnconsumed = $row3['lcAmount'];
}
$query3 = "SELECT lcAmount FROM leavecounts WHERE accountID = ? and ltypeID =4";
$params4 = array($accID);
$stmt3 = sqlsrv_query($con, $query3, $params4);
while($row4 = sqlsrv_fetch_array($stmt3)){
$emergencyUnconsumed = $row4['lcAmount'];
This will display multiple values for multiple textboxes you just have to take html in the loop or you can copy the values returned by result set and store them in array and separate the html.
<?php
$query = "SELECT lcAmount FROM leavecounts WHERE accountID = ?";
while($row = mysql_fetch_array($query))
{
$sickUnconsumed = $row['lcAmount'];
$vacationUnconsumed = $row['lcAmount'];
$maternityUnconsumed = $row['lcAmount'];
$emergencyUnconsumed = $row['lcAmount'];
?>
<div class="form-group">
<label class="control-label col-lg-4">Sick leave unconsumed</label>
<div class="col-lg-3">
<input type="text" id="sickLeave" name="sickLeave" class="form-control" value="<?php if(isset($sickUnconsumed)) echo $sickUnconsumed; ?>" >
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-4">Vacation uncomsumed</label>
<div class="col-lg-3">
<input type="text" id="vacation" name="vacation" class="form-control" value="<?php if(isset($vacationUnconsumed)) echo $vacationUnconsumed; ?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-4">Maternity uncomsumed</label>
<div class="col-lg-3">
<input type="text" id="inpUN" name="inpUN" class="form-control" value="<?php if(isset($maternityUnconsumed)) echo $maternityUnconsumed; ?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-4">Emergency uncomsumed</label>
<div class="col-lg-3">
<input type="text" id="inpUN" name="inpUN" class="form-control" value="<?php if(isset($emergencyUnconsumed)) echo $emergencyUnconsumed; ?>">
</div>
</div>
<?php
}//while
?>
I really hope you can help me.
I've done a form, where I can opt if a client I'm adding to the database is "Active or "Inactive", using a dropdown select box.
My code saves all the data correctly to the datbase, but when I want to edit the client, the option displays always as "Active", ignoring the value from the database.
I have 2 files:
edita_clientes.php - the form where I can edit the clients values
salvar_edicao.php - the file that saves the edition.
Here are the codes:
edita_clientes.php:
<?php
#ini_set('display_errors', '1');
error_reporting(E_ALL);
$id = $_GET["id_cliente"];
settype($id, "integer");
mysql_connect("localhost", "root", "");
mysql_select_db("sistema");
$resultado = mysql_query("select * from tabela where id_cliente = $id");
$dados = mysql_fetch_array($resultado);
mysql_close();
?>
<form id="edita_pj" name="edita_pj" method="post" action="salvar_edicao.php">
<input type="hidden" name="id_cliente" id="id_cliente" value="<?php echo $id;?>" />
<div class="box-body">
<div class="form-group">
<label>Razão Social</label>
<input type="text" name="razao" id="razao" class="form-control" value="<?php echo $dados["razao"];?>" />
</div>
<div class="form-group">
<label>Nome Fantasia</label>
<input type="text" name="fantasia" id="fantasia" class="form-control" value="<?php echo $dados["fantasia"];?>" />
</div>
</div>
<div class="box-body">
<div class="form-group">
<label>CNPJ</label>
<input type="text" name="cnpj" id="cnpj" class="form-control" data-inputmask='"mask": "999.999.999-99"' data-mask value="<?php echo $dados["cnpj"];?>">
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>Logradouro</label>
<input type="text" name="logradouro" id="logradouro" class="form-control" value="<?php echo $dados["logradouro"];?>">
</div>
<div class="col-xs-3">
<label>Número</label>
<input type="text" name="numero" id="numero" class="form-control" value="<?php echo $dados["numero"];?>">
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>Bairro</label>
<input type="text" name="bairro" id="bairro" class="form-control" value="<?php echo $dados["bairro"];?>">
</div>
<div class="col-xs-3">
<label>CEP</label>
<input type="text" name="cep" id="cep" class="form-control" data-inputmask='"mask": "99999-999"' data-mask value="<?php echo $dados["cep"];?>">
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-10">
<label>Cidade</label>
<input type="text" name="cidade" id="cidade" class="form-control" value="<?php echo $dados["cidade"];?>">
</div>
<div class="col-xs-2">
<label>UF</label>
<input type="text" name="uf" id="uf" class="form-control" value="<?php echo $dados["uf"];?>">
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>E-mail</label>
<input type="text" name="email" id="email" class="form-control" value="<?php echo $dados["email"];?>">
</div>
<div class="col-xs-3">
<label>Telefone</label>
<input type="text" name="telefone" id="telefone" class="form-control" data-inputmask='"mask": "(99) 9999.9999"' data-mask value="<?php echo $dados["telefone"];?>"/>
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>Contato</label>
<input type="text" name="contato" id="contato" class="form-control" value="<?php echo $dados["contato"];?>">
</div>
<div class="col-xs-3">
<label>Estado</label>
<select class="form-control" name="estado" id="estado" value=""><?php echo $dados["estado"];?>
<option>Ativo</option>
<option>Inativo</option>
</select>
</div>
</div>
<div class="form-group">
<label>Observações</label>
<textarea class="form-control" name="obs" id="obs" rows="6" ><?php echo $dados["obs"];?>
</textarea>
</div>
</div>
<div class="box-footer">
<button type="submit" name="Submit" class="btn btn-primary">Salvar</button>
</div>
</form>
salvar_edicao.php:
<?php
#ini_set('display_errors', '1');
error_reporting(E_ALL);
$razao = $_POST["razao"];
$fantasia = $_POST["fantasia"];
$cnpj = $_POST["cnpj"];
$logradouro = $_POST["logradouro"];
$numero = $_POST["numero"];
$bairro = $_POST["bairro"];
$cep = $_POST["cep"];
$cidade = $_POST["cidade"];
$uf = $_POST["uf"];
$email = $_POST["email"];
$telefone = $_POST["telefone"];
$contato = $_POST["contato"];
$estado = $_POST["estado"];
$obs = $_POST["obs"];
$id = $_POST["id_cliente"];
mysql_connect("localhost", "root", "");
mysql_select_db("sistema");
mysql_query("UPDATE tabela SET razao = '$razao', fantasia = '$fantasia', cnpj = '$cnpj', logradouro = '$logradouro', numero='$numero', bairro='$bairro', cep='$cep', cidade = '$cidade', uf='$uf', email = '$email', telefone = '$telefone', contato = '$contato', estado = '$estado', obs = '$obs' WHERE tabela.id_cliente = $id");
mysql_close();
header("Location: consulta.php");
?>
You need to add 'selected' to the option that you want to be selected, based on a value from the form/db. Here is an example using $value as the option value that you want selected.
<select class="form-control" name="estado" id="estado">
<option <?php echo $value == 'Ativo' ? selected : '' ?>>Ativo</option>
<option <?php echo $value == 'Inativo' ? selected : '' ?>>Inativo</option>
</select>
Also, your <select> tag does not require a 'value' element..
The HTML select element does not have a value attribute. For the select to do what you want you need to add the selected attribute to the option you want selected. It's always showing as 'Active' because that's the first option and it is the default.
The resulting post-php HTML will need to look something like this stripped back example for 'Inactive' to be selected.
<select>
<option>Active</option>
<option selected>Inactive</option>
</select>
Thank's for all the help!
The solution I've found was:
<?php
$resultado = mysql_query("select * from tabela where id_cliente = $id");
$dados = mysql_fetch_array($resultado);
$query = mysql_query("SELECT * FROM estado");
?>
And the html part:
<select class="form-control" name="estado" id="estado">
<option selected="selected"><?php echo $dados["estado"];?></option>
<option value="Ativo">Ativo</option>
<option value="Inativo">Inativo</option>
</select>