I want to save data from input fields to mysql database so first I create a modal window and input fields:
<!-- Button trigger modal -->
<button class="btn btn-success" data-toggle="modal" data-target="#myModal">
Add new</button>
<div id="output"></div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add new row</h4>
</div>
<div class="modal-body">
......
<div class="input-group">
<span class="input-group-addon">Ime</span>
<input type="text" id="Ime" class="form-control" placeholder="Upisi ime">
</div>
</br>
<div class="input-group">
<span class="input-group-addon">Pol</span>
<input type="text" id="pol" class="form-control" placeholder="Pol (male/female)">
</div>
</br>
<div class="input-group">
<span class="input-group-addon">Godine</span>
<input type="text" id="godine" class="form-control" placeholder="Godine starosti">
</div>
</br>
<div class="input-group">
<span class="input-group-addon">Broj pojedenih krofni</span>
<input type="text" id="krofne" class="form-control" placeholder="Pojedene krofne">
</div>
</br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="newData" class="btn btn-primary">Add new data</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
Now I write jQuery AJAX code to add data to database:
<script>
//add data to database using jquery ajax
$("#newData").click(function() {
//in here we can do the ajax after validating the field isn't empty.
if($("#ime").val()!="") {
$.ajax({
url: "add.php",
type: "POST",
async: true,
data: { Name:$("#ime").val(), Gender:$("#pol").val(), Age:$("#godine").val(), Donuts_eaten:$("#krofne").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
} else {
//notify the user they need to enter data
}
});
</script>
and finally I create a php file (add.php)
<?php
$con = mysql_connect('localhost', 'gmaestro_agro', 'pass') or die('Error connecting to server');
mysql_select_db('gmaestro_agro', $con);
mysql_select_db('gmaestro_agro', $con);
$query = "INSERT INTO `stat` (`Name`, `Gender`, `Age`, `Donuts eaten`) VALUES (";
$query .= mysql_real_escape_string($_POST['Name']) . ", ";
$query .= mysql_real_escape_string($_POST['Gender']) . ", ";
$query .= mysql_real_escape_string($_POST['Age']) . ", ";
$query .= mysql_real_escape_string($_POST['Donuts_eaten']);
$query .= ")";
$result = mysql_query($query);
if($result != false) {
echo "success!";
} else {
echo "an error occured saving your data!";
}
?>
Now, when I try to add data I just get this error: an error occurred saving your data!.
What is the problem here exactly? I try to find the error whole day...
You are not quoting your strings:
$query .= mysql_real_escape_string($_POST['Name']) . ", ";
should be:
$query .= "'" . mysql_real_escape_string($_POST['Name']) . "', ";
(for all string values)
By the way, it would probably make your life easier if you switched to PDO or mysqli and prepared statements. Then you would not have to escape and quote your variables and the mysql_* functions are deprecated anyway.
$query = "INSERT INTO `stat` (`Name`, `Gender`, `Age`, `Donuts eaten`) VALUES (";
$query .= "'".mysql_real_escape_string($_POST['Name']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Gender']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Age']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Donuts_eaten']);
$query .= "')";
Put all the values in single quotes.
Related
I have a search bar for users to enter a query. Upon clicking 'Search', a modal should appear with the query results.
My output from index.php is still not showing in the modal. When I click 'Search', the modal pops up with an empty body. How do I get my output from index.php to show in the modal's body?
Is there something wrong with my script? Do I need to add something to modal-body?
index.php
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<form method="POST" action="#">
<input type="text" name="q" placeholder="Enter query"/>
<input type="button" name="search" value="Search" data-toggle="modal" data-target="#mymodal">
</form>
</body>
<script>
$.ajax({ type: "GET",
url: 'search.php',
success: function(data){ debugger $('#mymodal').modal('show');
$('#mymodal:visible .modal-content .modal-body').html(e); } });
</script>
<!-- The Modal -->
<div class="modal" id="mymodal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
search.php
<?php
include_once('db.php'); //Connect to database
if(isset($_REQUEST['q'])){
$q = $_REQUEST['q'];
//get required columns
$query = mysqli_query($conn, "SELECT * FROM `words` WHERE `englishWord` LIKE '%".$q."%' OR `yupikWord` LIKE '%".$q."%') or die(mysqli_error($conn)); //check for query error
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<h2>No result found</h2>';
}else{
while($row = mysqli_fetch_assoc($query)){
$output .= '<h2>'.$row['yupikWord'].'</h2><br>';
$output .= '<h2>'.$row['englishWord'].'</h2><br>';
$output .= '<h2>'.$row['audio'].'</h2><br>';
$audio_name = $row['audio'];
$output .= '<td><audio src="audio/'.$audio_name.'" controls="control">'.$audio_name.'</audio></td>';
}
}
echo $output;
}else{
"Please add search parameter";
}
mysqli_close($conn);
?>
use these code of search.php
<?php
include_once('db.php'); //Connect to database
if(isset($_REQUEST['q']))
{
$q = $_REQUEST['q'];
$query = mysqli_query($conn, "SELECT * FROM `words` WHERE `englishWord` LIKE '%".$q."%' OR `yupikWord` LIKE '%".$q."%'") or die(mysqli_error($conn));
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<h2>No result found</h2>';
}else{
while($row = mysqli_fetch_assoc($query)){
$output .= '<h2>'.$row['yupikWord'].'</h2><br>';
$output .= '<h2>'.$row['englishWord'].'</h2><br>';
$output .= '<h2>'.$row['audio'].'</h2><br>';
$audio_name = $row['audio'];
$output .= '<td><audio src="audio/'.$audio_name.'" controls="control">'.$audio_name.'</audio></td>';
}
}
echo $output;
}else{
"Please add search parameter";
}
mysqli_close($conn);
?>
I have a form in a bootstrap modal window and what is happening, is when I click the 'send' button, the modal closes and a white page displays the result of my action call to contact-form.php and shows the error message for blank field but thid should be showing in the message div in the form in the the modal window.
I am obviously doing something fundementally wrong and would appreciate any help you can offer. I wouls have done a snippet but couldn't see how to include php code.
Many thanks
Bootstrap V3.3.7
UPDATE: The form works fine if i use as normal form outside of the modal
window.
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal__title"><div style="color: white; margin-top: -14px; margin-left: 36px;">Contact Us</div></h2>
<div style="color: white; margin-left: 36px; margin-bottom: 20px;">If you need to contact us, please use this form and we shall respond as soon as possible. Thanks</div>
</div>
<div class="modal-body">
<div class="content-block contact-3">
<div class="container">
<div class="row">
<div class="col-md-9">
<div id="contact" class="form-container">
<div id="message"></div> <-ERROR SHOULD BE DISPLAYED HERE
<form method="post" action="js/contact-form.php" name="contactform" id="contactform">
<div class="form-group">
<input name="name" id="name" type="text" value="" placeholder="Name" class="form-control" />
</div>
<div class="form-group">
<input name="email" id="email" type="text" value="" placeholder="Email" class="form-control" />
</div>
<div class="form-group">
<input name="phone" id="phone" type="text" value="" placeholder="Phone" class="form-control" />
</div>
<div class="form-group">
<textarea name="comments" id="comments" class="form-control" rows="3" placeholder="Message" id="textArea"></textarea>
<div class="editContent">
<p class="small text-muted"><span class="guardsman">* All fields are required.</span> Once we receive your message we will respond as soon as possible.</p>
</div>
</div>
<div class="form-group">
<button class="btn btn-default" type="button" class="modal" data-dismiss="modal">Close</button>
<button class="btn btn-primary" type="submit" id="cf-submit" name="submit">Send</button>
</div>
</form>
</div>
<!-- /.form-container -->
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
<!--// END Contact 3-1 -->
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
contact-form.php
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="error_message">Please enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Please enter a valid phone number.</div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message">Phone number can only contain digits and no spaces.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">You have entered an invalid e-mail address, try again.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Please enter your message.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "yourname#yourdomain.com";
$address = "yourname#yourdomain.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name from your website, their message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name by email, $email or by phone $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h2>Email Sent Successfully.</h2>";
echo "<p>Thank you <strong>$name</strong>, your message has been sent to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>
sendmail.js
jQuery(document).ready(function () {
$('#contactform').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
$("#message").fadeOut(500, function () {
$('#message').hide();
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
comments: $('#comments').val(),
},
function (data) {
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#submit').removeAttr('disabled');
if (data.match('success') != null) {
$('#contactform').fadeOut('slow');
$("#message").delay(3000).fadeOut();
$("#contactform").delay(4000).fadeIn();
$("#contactform").css("margin-top", "40px !important");
$("#contactform").trigger("reset");
}
}
);
});
return false;
});
});
I can't test you code but in my opinion i would not do the submit action with $(form).submit().... also if you are doing a event.preventDefault(), i explain better, you are doing an ajax call and with different errors you have differents answers, so in your place i would delete the action in the html at on click of the send button i would do an ajax call and manage the answer.Try in this way, because i think that if you use the submit in that way the browser interpret the submit form also because you are using the action url to send the call.
$('#cf-submit').click(function(){
name = $('#name').val();
email = $('#email').val();
phone = $('#phone').val();
comments = $('#comments').val();
$.ajax({
url : 'js/contact-form.php',
type : 'POST',
data : {
name : name,
email : email,
phone : phone,
comments : comments,
},
dataType : 'html',
success : function(response){
$('#message').html(response);
}
});
});
I think you forget to put exit(); at the end of file contact-form.php
I am loading record details into a modal allowing the user to edit. What I am trying to achieve is to have the user update the record in the modal and then submit to the MySQL table via AJAX / jQuery, however, afte pressing the "Save Changes" button nothing happens. I checked the JS Query and can confirm that the button is linked correctly and also managed to update the database when directly addressing the PHP update script. Not sure why the script refuses to start
Modal:
<div id="output"></div>
<!-- Modal MYMODAL -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Edit Record</h4>
</div>
<div class="modal-body">
<!-- ID No. -->
<div class="form-group">
<label>ID No.:</label>
<input type="number" class="form-control" id="dataPID" name="dataPID" size="5" disabled />
</div>
<!-- /.id number -->
<!-- Category -->
<div class="form-group">
<label>Category:</label>
<input type="text" class="form-control" id="dataCat" name="dataCat" />
</div>
<!-- /.category -->
<!-- Issue -->
<div class="form-group">
<label>Issue:</label>
<input type="text" class="form-control" id="dataIssue" name="dataIssue" />
</div>
<!-- /.issue -->
<!-- Department Responsible -->
<div class="form-group">
<label>Department Responsible:</label>
<input type="text" class="form-control" id="dataDeptResp" name="dataDeptResp" />
</div>
<!-- /.department responsible -->
<!-- Experience -->
<div class="form-group">
<label>Experience:</label>
<input type="text" class="form-control" id="dataExp" name="dataExp" />
</div>
<!-- /.experience -->
<!-- textarea -->
<div class="form-group">
<label>Description:</label>
<textarea class="form-control" id="dataDesc" name="dataDesc" rows="3" ></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" id="SaveChanges" name="SaveChanges" class="btn btn-primary">Save Changes</button>
<button type="button" id="DeleteRecord" name="DeleteRecord" class="btn btn-danger">Delete Record</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- /.Modal MYMODAL -->
Javascript:
$("#SaveChanges").click(function() {
$.ajax({
type: "POST",
url: "plugins/MySQL/ajax_action.php",
data: { action:"update_mysqli",PID:$("#dataPID").val(), Category:$("#dataCat").val(), Issue:$("#dataIssue").val(), Department_Responsible:$("#dataDeptResp").val(), Experience:$("#dataExp").val(), Description:$("#dataDesc").val()}, //your form data to post goes here as a json object
dataType: "json",
contentType:"text",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
});
ajax_action.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['action']) && ($_POST['action']=='update_mysqli')) {
// include connection details
include 'connect_db.php';
//Open a new connection to the MySQL server
$db = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
//Output any connection error
if ($db->connect_error) {
die('Error : ('. $db->connect_errno .') '. $db->connect_error);
}
// get variables and sanitize
$pid = mysqli_real_escape_string($db,$_POST['PID']);
$cat = mysqli_real_escape_string($db,$_POST['Category']);
$issue = mysqli_real_escape_string($db,$_POST['Issue']);
$dept_resp = mysqli_real_escape_string($db,$_POST['Department_Responsible']);
$exp = mysqli_real_escape_string($db,$_POST['Experience']);
$desc = mysqli_real_escape_string($db,$_POST['Description']);
// check if record exists based on ID number
$result = $db->query("SELECT * FROM qci_problems_index_new WHERE PID='".$pid."'");
// if record is found, update accordingly
if ($result->num_rows > 0){
$sql = "UPDATE qci_problems_index_new SET Category = '$cat', Issue = '$issue', Department_Responsible = '$dept_resp', Experience = '$exp', Description = '$desc' WHERE PID = '$pid'";
if (!$db->query($sql)) {
echo "Error - Update of record PID " . $pid . " failed: (" . $db->errno . ") " . $db->error;
}
} else {
// if no record with relevant PID is found, create new record
$sql = "INSERT INTO `qci_problems_index_new`(`PID`, `Category`, `Issue`, `Department_Responsible`, `Experience`, `Description`) VALUES ('".$pid."', '".$cat."', '".$issue."', '".$dept_resp."', '".$exp."', '".$desc."')";
if (!$db->query($sql)) {
echo "Error - could not insert new record: (" . $db->errno . ") " . $db->error;
}
}
echo "Success, record updated successfully";
//close connection
$db->close();
}
EDIT 1:
Chrome Console says the following:
EDIT 2:
updated code
Change you data type to json and content type to text,add your get variable to the post request
$("#SaveChanges").click(function() {
$.ajax({
type: "POST",
url: "plugins/MySQL/ajax_action.php",
data: { action:"update_mysqli",PID:$("#dataPID").val(), Category:$("#dataCat").val(), Issue:$("#dataIssue").val(), Department_Responsible:$("#dataDeptResp").val(), Experience:$("#dataExp").val(), Description:$("#dataDesc").val()}, //your form data to post goes here as a json object
dataType: "json",
contentType:"text",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
});
php
if(isset($_POST['action']) && ($_POST['action']=='update_mysqli')) {
You are passing the value "update_mysql" in "action" parameter in the ajax URL(plugins/MySQL/ajax_action.php?action=update_mysql). On the other hand your condition in ajax_action.php will only be executed the code if the value of "action" parameter is "update_mysqli"
Change the following line
if(isset($_GET['action']) && ($_GET['action']=='update_mysqli'))
to
if(isset($_GET['action']) && ($_GET['action']=='update_mysql'))
in your ajax_action.php file.
OR
Alternatively, you can pass value update_mysqli instead of update_mysql for your action parameter in ajax call.
Since you are using mysqli, you will prefer this for the sake of best practice as you are using mysqli functions inside code.
I want to display a "thank you" modal when the page is reloaded after successful form submission.
Here's my PHP at the bottom of the <head>:
<?php
if (isset($_POST["email"]) && !empty($_POST["email"]))
{
$response_text = "Thanks, we'll be in touch soon!";
include('connect.php');
mysqli_query($con, "INSERT INTO sh_betalist (email, ip_address, signup_loc) VALUES ('" . $_POST['email'] . "', '" . $_SERVER['REMOTE_ADDR'] . "', '" . "homepage')");
?>
<script type="text/javascript"> $('#thankyouModal').modal('show'); </script>
<?php
}
?>
That all works fine except for showing the modal, which doesn't happen. I don't get any errors in the JS console.
Here's my modal at the bottom of the <body>:
<div class="modal fade" id="thankyouModal" tabindex="-1" role="dialog" aria-labelledby="thankyouLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Thank you for pre-registering!</h4>
</div>
<div class="modal-body">
<p>You'll be the first to know when Shopaholic launches.</p>
<p>In the meantime, any feedback would be much appreciated.</p>
</div>
</div>
</div>
</div>
Try wrapping a $(document).ready around the javascript.
<?php
if (isset($_POST["email"]) && !empty($_POST["email"]))
{
$response_text = "Thanks, we'll be in touch soon!";
include('connect.php');
mysqli_query($con, "INSERT INTO sh_betalist
(email, ip_address, signup_loc) VALUES ('" . $_POST['email'] . "', '" .
$_SERVER['REMOTE_ADDR'] . "', '" . "homepage')");
?>
<script type="text/javascript">
$(document).ready(function(){
$('#thankyouModal').modal('show');
});
</script>
<?php
}
?>
Here I create a table http://jsbin.com/OJAnaji/13/edit and DEMO: http://jsbin.com/OJAnaji/13
So when users click on some row on table automaticly populate input fields with values from table into modal window. Modal window user open when click on button "Edit row". Now I need to know how I can update mysql table with columns: Name,Gender,Age,Donuts eaten.
I create js ajax:
$("#edit").click(function() {
//in here we can do the ajax after validating the field isn't empty.
if($("#name").val()!="") {
$.ajax({
url: "update.php",
type: "POST",
async: true,
data: { Name:$("#name").val(), Gender:$("#gender").val(), Age:$("#age").val(), Donuts_eaten:$("#donuts_eaten").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
} else {
//notify the user they need to enter data
}
});
HTML - modal window and button:
<!-- Button trigger modal -->
<button id="edit" class="btn btn-success disabled" type="button" data-toggle="modal" data-target="#myModal">
Edit selected row</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add new row</h4>
</div>
<div class="modal-body">
<div class="input-group">
<span class="input-group-addon">Name</span>
<input type="text" value="" id="name" class="form-control" placeholder="Type name">
</div></br>
<div class="input-group">
<span class="input-group-addon">Gender</span>
<input type="text" id="gender" class="form-control" placeholder="Gender?">
</div></br>
<div class="input-group">
<span class="input-group-addon">Age</span>
<input type="text" id="age" class="form-control" placeholder="Number of age">
</div></br>
<div class="input-group">
<span class="input-group-addon">Donuts eaten</span>
<input type="text" id="donuts_eaten" class="form-control" placeholder="Number of donuts eaten">
</div></br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
So how I can now update MySql database with php:
so file update.php how must looks like:
<?php
$con = mysql_connect('localhost', 'gmaestro_agro', 'pass') or die('Error connecting to server');
mysql_select_db('gmaestro_agro', $con);
//HOW I CAN UPDATE MYSQL DATABASE, WHAT I NEED TO ADD HERE?
?>
You should have a column in the table which is an auto-increment column, such as "id" or like the example below uses "index_id". This should be used when creating your form, and sent along with the $_POST array to reference the row you are updating. This is a simple example, which you can use to get you started.
$_POST = stripslashes_deep($_POST); # you will want to better filtering for security.
if(isset($_POST['Name']) && $_POST('Name') !=''){
$query = "UPDATE stat
SET Name ='". $_POST['Name'] . "',
Gender ='". $_POST['Gender'] . "',
Age ='". $_POST['Age'] . "',
Donuts_eaten ='" .$_POST['Donuts_eaten'] . "'
WHERE
index_id = '". $_POST['index_id'] . "'";
$result = mysql_query($query) or die(mysql_error());
exit(json_encode($_POST));
}
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
For your MYSQL table you can run this in your MYSQL PhpMyAdmin:
ALTER TABLE `stats` ADD `index_id` INT( 3 ) NOT NULL AUTO_INCREMENT FIRST ,
ADD PRIMARY KEY ( `index_id` )
In your update.php, do like this,
$name = $_POST['Name'];
$gender = $_POST['Gender'];
$age = $_POST['Age'];
$donuts = $_POST['Donuts_eaten'];
$query = "UPDATE `your_table_name` SET name ='".$name."', gender ='".$gender."',
age='".$age."', donuts_eaten ='".$donuts."' ";
mysql_query($query, $con);
Just a basic to basic structure on what you need to do in update.php its up to you to kick it a notch and you've used POST in your ajax that why its $_POST.
note: Dont use reserved word as your field name in the database.