update MySQL in PHP - php

I want to update MySQL database in PHP. My problem is that I have 3 tables. An employee, a company, and an employee_company (it has the another 2 table's id). And I want to update the employee table if I change the employee's name and the employee_company table if I add a company to the employee. I tried to solve this problem, but it didn't update the tables. How can I do this?
index.php
<form method="post" id="insert_form">
<label>Enter Employee Name</label>
<input type="text" name="name" id="name" class="form-control" />
<br />
<label>Enter Employee Address</label>
<textarea name="address" id="address" class="form-control"></textarea>
<br />
<label>Company:</label>
<select name="company" id="company" class="form-control">
<?php
$query2 = "SELECT * FROM company ORDER BY company_id";
$result2 = mysqli_query($connect, $query2);
while($row2= mysqli_fetch_array($result2)){
?>
<option value="<?php echo $row2['company_id'];?>"><?php echo $row2['company'];?></option>
<?php
}
?>
</select>
<br/>
<input type="hidden" name="employee_id" id="employee_id" />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success" />
</form>
<script>
$(document).on('click', '.edit_data', function(){
var employee_id = $(this).attr("id");
$.ajax({
url:"fetch.php",
method:"POST",
data:{employee_id:employee_id},
dataType:"json",
success:function(data){
$('#name').val(data.name);
$('#address').val(data.address);
$('#company').val(data.company);
$('#employee_id').val(data.id);
$('#insert').val("Update");
$('#add_data_Modal').modal('show');
}
});
});
$('#insert_form').on("submit", function(){
else
{
$.ajax({
url:"insert.php",
method:"POST",
data:$('#insert_form').serialize(),
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#employee_table').html(data);
}
});
}
});
</script>
insert.php
$name = mysqli_real_escape_string($connect, $_POST["name"]);
$company = mysqli_real_escape_string($connect, $_POST["company"]);
$id=$_POST["employee_id"];
if($_POST["employee_id"] != '')
{
$query = "
UPDATE employee, employee_company
SET employee_company.employee_id='$id',
employee_company.company_id='$company',
employee.name='$name',
WHERE employee.employee_id='".$_POST["employee_id"]."'";
$message = 'Data Updated';
}

You were missing mysqli_query() function which actually runs the query. Your$query variable is just a string variable until you don't put it into mysqli_query() function
Replace your code with this piece of code
if($_POST["employee_id"] != '')
{
$query = "
UPDATE employee, employee_company
SET employee_company.employee_id='$id',
employee_company.company_id='$company',
employee.name='$name'
WHERE employee.employee_id='".$_POST["employee_id"]."'";
if(mysqli_query($connect,$query))
$message = 'Data Updated';
else
echo mysqli_error($connect);
}
If there is any query then you can ask me freely!

There is some mistake in query, using additional comma(,) before where condition. So remove that. Check the updated code below:
if ($_POST["employee_id"] != '') {
$query = "UPDATE employee, employee_company SET employee_company.employee_id='$id', employee_company.company_id='$company', employee.name='$name' WHERE employee.employee_id='" . $_POST["employee_id"] . "'";
mysqli_query($connect,$query);
$message = 'Data Updated';
}
Note: Also I recommend you to sanitize all inputs before using in query.

Related

jQuery(AJAX) post to php issue when I try to insert data into DB

when I echo the php variable it work properly , but when I try to insert the data into database it doesn't work , what is the solution please I get stuck
I got this error on console
POST http://localhost/validate.php 500 (Internal Server Error)
send # jquery-3.1.1.min.js:4
ajax # jquery-3.1.1.min.js:4
(anonymous) # jquery.PHP:26
dispatch # jquery-3.1.1.min.js:3
q.handle # jquery-3.1.1.min.js:3
HTML/JQUERY
<form action="" id="myForm">
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
<script>
$(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var name = $('#name').val();
var age = $('#age').val();
$.ajax({
url: 'validate.php',
method: 'POST',
data: {postname:name, postage:age},
success: function(res) {
$("#result").append(res);
}
});
});
});
</script>
PHP
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
echo $result ;
?>
mysqldb.php
<?php
$conn = mysql_connect('localhost', 'root', 'password' , 'datab');
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
?>
Please add the details of the error message you get.
Make little changes to your code so that it can show the query error if any
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "INSERT INTO `uss` (`first`, `last`) VALUES('{$name}','{$age}')";
if($conn->query($sql))
{
echo "Record inserted";
}
else
{
echo $conn->error;
}
?>
Sugesstions: Your query have the chances of the SQL Injection. Make it secure.
if you are using ajax , try the following,
<form >
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit" id="submit">
</form>
<div id="result"></div>
$("#submit").click(function(){
var name = $('#name').val(); // getting name
var age = $('#age').val();
$.ajax({
url : "validate.php",
type: "POST",
data: {name:name, age:age},
success: function(data)
{
$("#result").html(data);
}
});
});
in your controller function,echo the result
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "insert into uss (first, last) values('$name','$age')";
$result = $conn->query($sql);
echo $result;
?>
jQuery Ajax
Form with id myFrom
<form action="" id="myForm">
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
jQuery Ajax section
$(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var name = $('#name').val(); // getting name
var age = $('#age').val(); // getting age
/* Ajax section */
$.ajax({
url: 'validate.php',
method: 'POST',
data: {postname:name, postage:age},
success: function(res) {
$("#result").append(res);
}
});
});
});
validate.php
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
//check ajax response by `echo $name` and `$age`
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
echo $result ;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<form >
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="button" value="Submit" onclick="postdata();">
</form>
<div id="result"></div>
<script type="text/javascript">
function postdata() {
alert("ashad");
var name = $('#name').val();
var age = $('#age').val();
$.post('validate.php',{postname:name,postage:age},
function(data){
$('#result').html(data);
});
}
</script>
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
//check ajax response by `echo $name` and `$age`
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else
{
$sql = "insert into uss(first, last) values('$name','$age')";
$result = $conn->query($sql);
}
echo $result ;
?>

Parse value of input field to query parameters

Can I parse the value of an input field to a query parameter to get the values of a select field within the same form?
The code is following:
<FORM ACTION="login.php" METHOD=get>
<label for="email">Email: </label>
<input id="email" name="email" type="text" ><br>
<label for="pin">Password: </label>
<input id="pin" name="pin" type="password" ><br>
<label for="company">Company</label>
<select name="Company" id="company">
<option>Select Company:</option>
<?php
$conn= new mysqli($servername,$username,$password,$db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connet_error);
}
$email = isset($_GET['email'])?$_GET['email']:"";
$sql="select company from accounts WHERE email = '$email';";
$results = mysqli_query($conn, $sql);
if ($results->num_rows > 0){
while ($row = mysqli_fetch_array($results)){
echo "<option value=\"company1\">" .$row['company'] . "</option>";
}
}
?>
</select>
<input class="submit_btn" type="submit" value="Login"></input><br>
<a id="cust-nopin" href="javascript:;"><p class="text_centered_pass">Click here if you don't have a password</p></a>
</FORM>
Is that not possible?
In this scenario your best bet would be Ajax.
Your Form Page:
<form action="login.php" method=get>
<label for="email">Email: </label>
<input id="email" name="email" type="text" ><br>
<label for="pin">Password: </label>
<input id="pin" name="pin" type="password" ><br>
<label for="company">Company</label>
<select name="Company" id="company">
<option value="">Select Company:</option>
</select>
<input class="submit_btn" type="submit" value="Login"></input><br>
<a id="cust-nopin" href="javascript:void(0);"><p class="text_centered_pass">Click here if you don't have a password</p></a>
</form>
Now the JQuery Part:
$(function () {
$(document).on("change, blur, keydown", "#email", function () {
$.ajax({
url: 'path/to/ajaxfile.php',
type: 'GET',
dataType: 'json',
data: {email: $(this).val()},
})
.done(function(response) {
if (response.status) {
var html = '<option value="">Select Company:</option>' + response.html;
$("#company").html(html);
} else {
console.log(status.message);
}
})
.fail(function(data) {
alert("Something went wrong please try again later.");
console.log(data.responseText);
});
});
});
And then the path/to/ajaxfile.php:
$conn = new mysqli($servername,$username,$password,$db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connet_error);
}
if (! empty($_GET['email'])) {
$email = mysqli_real_escape_string($conn, $_GET['email']);
$sql = "SELECT company FROM accounts WHERE email = '$email'";
$results = mysqli_query($conn, $sql);
if ($results->num_rows > 0){
$html = "";
while ($row = mysqli_fetch_array($results)){
$html .= '<option value="' . $row['company'] . '">' . $row['company'] . '</option>';
}
echo json_encode(array("status" => true, "html" => $html));
} else {
echo json_encode(array("status" => false, "message" => "There is no company with that email address."));
}
} else {
echo json_encode(array("status" => false, "message" => "No email is there to lookup."));
}
This should help you achieve what you are trying to do...
I hope it helps.
Yes of course you can use an input field's value as a parameter for your query. It is a very common scenario.
Your query does not work because you have included the $email variable inside single quotes. So this should work:
$sql="select company from accounts WHERE email = $email";
(the semicolon at the end is not needed).
BUT
This way of using user input to query the database is a bad practice as it makes your code vulnerable to SQL Injection.
To safeguard against SQL Injection it is recommended to use Prepared Statements
So you should query the database like this:
$sql="select company from accounts WHERE email = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();

Form is not submitting values to database in first attempt using jQuery

I am trying to make a simple incentive calculator.
PROBLEMS:
When I am submitting the form the values of the fields and field names are showing are showing up in the address bar.
eg: "http://localhost/incentive%20tracker/?jQueryDatePicker1=09%2F05%2F2015&pid=n&qty=1&memo=&remarks=&add=Add"
When I try to submit the values in the first attempt just after the first load of the page, the values are not getting inserted in the database. After the first attempt, the values do get inserted.
On success in insertion of data in the database, jQuery doesn't show me any message in spite of having the success function.
I am not being able to display an error message if the qty field is negative.
I am not sure what I am doing wrong.
HTML
<form id="saleDetail">
<input type="text" id="jQueryDatePicker1" name="jQueryDatePicker1" value="06/05/2015">
<input type="text" name="pid" id="pid" required placeholder="Enter a product code">
<datalist id="products">
<?php
$sql="SELECT * FROM products";
$result = mysqli_query($db, $sql);
while($fetch_options=mysqli_fetch_array($result)){
?>
<option value="<?php echo $fetch_options['pid']; ?>"><?php echo $fetch_options['pid']; ?></option>
<?php
}
?>
</datalist>
<input type="number" id="qty" name="qty" value="" autocomplete="off" required placeholder="Enter the Quantity">
<input type="text" id="memo" name="memo" value="" autocomplete="off" placeholder="Enter the Cash memo number">
<textarea name="remarks" id="remarks" rows="2" cols="27" placeholder="Any remarks"></textarea>
<input type="submit" id="add" name="add" value="Add">
<div id="message"></div>
</form>
JQuery
<script>
$(document).ready(function()
{
var jQueryDatePicker1Opts =
{
dateFormat: 'dd/mm/yy',
changeMonth: false,
changeYear: false,
showButtonPanel: false,
showAnim: 'slideDown'
};
$("#jQueryDatePicker1").datepicker(jQueryDatePicker1Opts);
$("#jQueryDatePicker1").datepicker("setDate", "new Date()");
$("#PanelMenu1").panel({animate: true, animationDuration: 200, animationEasing: 'swing', dismissible: true, display: 'push', position: 'right'});
$('#add').click(function()
{
var date=$('#jQueryDatePicker1').val();
var pid=$('#pid').val();
var qty=$('#qty').val();
var remarks=$('#remarks').val();
var memo=$('#memo').val();
if(pid==="" || qty==="" || qty<0){
$("#message").html("<span style='color:#cc0000'>Please fill in the required fields!");
}
else{
var dataString='date='+date+'&pid='+pid+'&qty='+qty+'&remarks='+remarks+'&memo='+memo;
$.ajax({
type:"POST",
data: dataString,
url: "add.php",
cache:false,
success: function(html){
$("#message").html("Data Added successfully! ");
}
});
}
});
return false;
});
</script>
PHP
<?php
include 'connect.php';
$error_message = "";
$mysql_table = "sales";
//if ($_SERVER['REQUEST_METHOD'] == 'POST')
if (isset($_POST['pid']) && isset($_POST['qty']))
{
$newdate =$_POST['date'];
$newpid = $_POST['pid'];
$newqty = $_POST['qty'];
$newremarks = $_POST['remarks'];
$newmemo = $_POST['memo'];
$newpid = mysqli_real_escape_string($db, $newpid);
$newqty = mysqli_real_escape_string($db, $newqty);
$newremarks = mysqli_real_escape_string($db, $newremarks);
$newmemo = mysqli_real_escape_string($db, $newmemo);
$sql = "SELECT incentive FROM products WHERE pid = '$newpid'";
$result = mysqli_query($db, $sql);
$rate=mysqli_fetch_array($result);
$amt = $rate['incentive'] * $newqty;
$sql = "INSERT `".$mysql_table."` (`date`, `pid`, `qty`, `amt`, `memo`, `remarks`) VALUES ('$newdate', '$newpid', '$newqty', '$amt', '$newmemo', '$newremarks')";
$results = mysqli_query($db, $sql);
echo "Success";
mysqli_close($db);
}
?>

$_POST array is empty and I got undefined variable errors

Sorry to ask it again, but I checked almost all the q&a's on the topic and still couldn't solve it. Here is my form.php and creditform.php
Edit1.Changed the .get to .post
Edit2.I'm getting errors of undefined variable "name" "email" "address" "income" etc (in short for all of them) in creditform.php
What I want to do is just insert all the inputs into the table in db.
HTML
<!-- End crumbs-->
<div class="container wrap wow fadeInUp">
<div class="row">
<div class="col-sm-5 col-md-6 left-app">
<form id="form" action="php/creditform.php" method="post">
<input type="text" placeholder="Name" name="name" required>
<input type="email" placeholder="Email" name="email" required>
<input type="text" placeholder="Address" name="address" required>
<input type="number" placeholder="Monthly income before taxes" name="income" required>
<input type="number" placeholder="Amount Needed" name="amount_needed" required>
<input type="number" placeholder="Phone" name="phone" required>
<div class="row">
<div class="container">
<input type="submit" name="submit" value="Submit" class="button"></div></div>
<div id="result"></div>
</form>
</div>
<script>
$(document).ready(function($) {
'use strict';
$('#form').submit(function(event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = $(this).serialize();
$.post(url, datos, function(resultado) {
$('#result').html(resultado);
});
});
</script>
FORM.PHP
<?php
include('db.config.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $email = $address = $income = $amount_needed = $phone = '';
if(isset($_POST['submit'])){
$name = addslashes($_POST['name']);
$email = addslashes($_POST['email']);
$address = addslashes($_POST['address']);
$income = addslashes($_POST['income']);
$amount_needed = addslashes($_POST['amount_needed']);
$phone = addslashes($_POST['phone']);
// check form fields
if(empty($name)){
$error .= 'Enter name <br />';
}
if(empty($email)){
$error .= 'Enter email <br />';
}
// check if errors exist
if(!empty($error)){
echo $error;
} else {
// process form as normal
$sql = "INSERT INTO `" . DBN . "`.`creditapp` (`name`, `email`, `address`, `income`, `amount_needed`, `phone`) VALUES ('$name', '$email', '$address', '$income', '$amount_needed', '$phone')";
$db->Query($sql);
}
}
}
print_r($_POST);
?>
CREDITFORM.PHP
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$address = $_POST['address'];
$income = $_POST['income'];
$amount_needed = $_POST['amount_needed'];
$phone = $_POST['phone'];
}
print_r($_POST);
?>
It's obvious that I'm missing something, please correct me...
Thanks for your time
You need to send a POST request for the $_POST array to have anything in it.
$.get(url, datos, function(resultado) {
$('#result').html(resultado);
});
This sends a GET request (check $_GET). You want to use $.post here instead.
$.post(url, datos, function(resultado) {
$('#result').html(resultado);
});
Here is a simple Ajax call to a Php File by an event : Click on a button.
In your example you must use POST method because you use :
$_POST['something'];
Javascript client side :
$("body").on("click", "#mybutton", function() {
var mydata = $("#form").serialize();
$.ajax({
type: "POST",
url: "/api/api.php",
data: {data : mydata},
timeout: 6e3,
error: function(a, b) {
if ("timeout" == b) $("#err-timedout").slideDown("slow"); else {
$("#err-state").slideDown("slow");
$("#err-state").html("An error occurred: " + b);
}
},
success: function(a) {
var e = $.parseJSON(a);
if (true == e["success"]) {
$("#result").html(e['message']);
// here is what you want, callback Php response content in Html DOM
}
}
});
return false;
});
Next in your Php code simply do after any success function :
if ($result) {
echo json_encode(array(
'success' => true,
'msg' => "Nice CallBack by Php sent to client Side by Ajax Call"
));
}
Okay, I practiced more on ajax - json - php and in the end this was my solution and my latest code.
Thanks for all answers and suggestions. Hope this also helps to someone.
Still open to any kind of advice to improve.
<?php
include('db.config.php');
if(isset($_POST['submit'])){
$name = addslashes($_POST['name']);
$email = addslashes($_POST['email']);
$address = addslashes($_POST['address']);
$income = addslashes($_POST['income']);
$amount_needed = addslashes($_POST['amount_needed']);
$phone = addslashes($_POST['phone']);
// process form as normal
$sql = "INSERT INTO `" . DBN . "`.`creditapp` (`name`, `email`, `address`, `income`, `amount_needed`, `phone`) VALUES ('$name', '$email', '$address', '$income', '$amount_needed', '$phone')";
$db->Query($sql);
die();
<div class="container wrap wow fadeInUp">
<div class="row">
<div class="col-sm-5 col-md-6 left-app">
<form id="form" action="creditapp.php" method="post">
<input type="text" placeholder="Name" name="name" id="name" required>
<input type="email" placeholder="Email" name="email" id="email" required>
<input type="text" placeholder="Address" name="address" id="address" required>
<input type="text" placeholder="Monthly income before taxes" id="income" name="income" required>
<input type="text" placeholder="Amount Needed" name="amount_needed" id="amount_needed" required>
<input type="text" placeholder="Phone" name="phone" id="phone" required>
<div class="row">
<div class="container">
<input type="submit" name="submit" value="Submit" class="button sub"></div>
</div>
</form>
</div>
<script>
$(document).ready(function() {
$('.sub').click(function(e){
e.preventDefault();
var name = $('#name').val(),
email = $('#email').val(),
address = $('#address').val(),
income = $('#income').val(),
amount_needed = $('#amount_needed').val(),
phone = $('#phone').val();
$.ajax({
url: "creditapp.php",
type: "POST",
data: {
name: name,
email: email,
address: address,
income: income,
amount_needed: amount_needed,
phone: phone,
submit: "submit"
}
}).done(function(msg){
$('.right-info').html('<pre>' + msg + '</pre>');
})
})
});
</script>
The problem you are having is with your javascript. You wait for the submit and than you do an ajax GET request, you need a POST.
<script>
$(document).ready(function($) {
'use strict';
$('#form').submit(function(event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = $(this).serialize();
$.post(url, datos, function(resultado) {
$('#result').html(resultado);
});
});
</script>

jquery not adding the values to database, readystate=0, and status=0

My script does not seem to be working. Every time i try to use the form i've get the error with readystate=0, and status=0. Any help will be appreciated.
I've got the following form:
<form action="" method="post" >
<input type="text" name="name" id="tekst"/><br/>
<input type="text" name="name" id="autor"/><br/>
<input type="submit" name="<?php echo $id; ?>" value="Send" id="submit"/>
</form>
<div class="response"></div>
the values from input fields are then processed by the following code:
$("input#submit").click(function(){
var id = $("input#submit").attr("name");
var autor = $('input#autor').val();
var tresc = $('input#tekst').val();
$.ajax({
type: "POST",
url: "add_comment.php",
data:
{id: id,
autor: autor,
tresc: tresc},
success: function(data){
$(".response").text(data);
},
error:function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
});
Here is my add_comment.php:
<?php
$id = $_POST['id'];
$autor= $_POST['autor'];
$tresc = $_POST['tresc'];
if(isset($id) && isset($autor) && isset($tresc)){
include("db/connection.php");
$zapytanie= "INSERT INTO komentarze(id_ref, autor, tresc) values ('$id', '$autor', '$tresc')";
$wynik = $db->query($zapytanie);
echo "Added";
}else{
echo "Problem";
}
?>
EDIT:
id_ref is not auto_increment field. The script is running on the localhost
First of all, your form isn't correct...name="name", class=".response"??
<form action="" method="post" >
<input type="text" name="tekst" id="tekst"/><br/>
<input type="text" name="autor" id="autor"/><br/>
<input type="submit" name="id" value="Send" id="submit"/>
</form>
<div class="response"></div>
Your PHP File should be"
<?php
$id = $_POST['id'];
$autor= $_POST['autor'];
$tresc = $_POST['tekst'];
if(isset($id) && isset($autor) && isset($tresc)){
include("db/connection.php");
$zapytanie= "INSERT INTO komentarze(id_ref, autor, tresc) values ('$id', '$autor', '$tresc')";
$wynik = $db->query($zapytanie);
echo "Added";
}else{
echo "Problem";
}
?>
<form action="add_comment.php" method="post" >
<input type="text" name="tekst" id="tekst"/><br/>
<input type="text" name="autor" id="autor"/><br/>
<input type="submit" name="button" value="Send" id="submit"/>
</form>
And in php it should be like this
$id = $_POST['button'];
$autor= $_POST['autor'];
$tresc = $_POST['tekst'];
It should work properly now. Previously you were making a mistake that in the submit button field you were passing a php variable which could contain anything and you dont know if it is dynamic. So you weren't be able to get it by using $_REQUEST['id'] because it could have been some thing like this
$id = 1; or $id = 'dynamic string' ;

Categories