Reputation: 371
I have html with ajax and php file. I use native php with mysqli for database. in connection, I have sricpt that named is config.php . this script :
<?php
$db = new mysqli('localhost', 'root', '', 'student');
?>
And then I have html with ajax like this :
$("form#form").submit(function(event) {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'student/action.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
if (data == 0) {
alert('all data updated');
} else {
alert('failed');
}
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id='form'>
<input type='hidden' name='type' value='new-data'>
<input name='name' type='text'>
<input name='class' type='text'>
<input name='hobbies' type='text'>
<button type='submit' name='submit'>Submit</button>
</form>
</body>
in student/action.php script like this,
<?
php require_once '../config/config.php';
switch ($_POST[ 'type']) {
case "new-data":
$qry1=$db->query("INSERT INTO tableA SET id=NULL, name='$_POST[name]' ");
$qry2=$db->query("INSERT INTO tableB SET id=NULL, name='$_POST[class]' ");
$qry3=$db->query("INSERT INTO tableC SET id=NULL, name='$_POST[hobbies]' ");
if($qry1 && $qry2 && $qry3) {
echo '1';
} else {
echo '2';
}
break;
}
?>
nah,this apps on hosting and at here the connection not stable. so when I submit by click submit
, it will post data to student/action.php. it must be insert all query ($qry1, $qry2, and $qry3), but if I had bad connection it only insert some query, not all. How to solve it. thanks
Upvotes: 0
Views: 620
Reputation: 1970
First, never use $_POST, $_GET, $_REQUEST directly in your query (because of SQL injection), alway use mysqli_real_escape_string :
$name=$db->mysqli_real_escape_string($_POST['name']);
$class=$db->mysqli_real_escape_string($_POST['class']);
$hobbies=$db->mysqli_real_escape_string($_POST['hobbies']);
And don't forget quotes
If you want to make sure all request are executed or all fail use transaction (you need innodb storage engine);
$db->begin_transaction();
//Your queries…
$db->commit();
If one request fail all previous requests are rolled back. you can use $db->rollback(); to cancel all queries before a commit. See php doc for more infos.
Upvotes: 1