Delete rows of local database as each is transfered to hosted database - php

EDIT - got the transfer to happen
.. now I need to figure out how to get the successful transfers to delete each row after it is stored on the host. The function that grabs the data from the browsers SQL database is :
function grabLocal(){
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM entries', [], function(tx, results){
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
var qID = (results.rows.item(i).ID);
var qEmail = (results.rows.item(i).email);
var qPhone = (results.rows.item(i).phone);
var qMonth = (results.rows.item(i).birth_month);
var qDay = (results.rows.item(i).birth_day);
var qYear = (results.rows.item(i).birth_year);
var qMonth = (results.rows.item(i).birth_month);
var qGender = (results.rows.item(i).gender);
var qContest = (results.rows.item(i).contest);
var qStore = (results.rows.item(i).storeNo);
var qDate = (results.rows.item(i).added_on);
var localData = new Array((qEmail),(qPhone),(qMonth),(qDay),(qYear),(qGender),(qContest),(qStore),(qDate));
$.ajax({
type: "POST",
url: "sendIt.php",
data: "email=" + qEmail + "&phone=" + qPhone + "&month=" + qMonth + "&day=" + qDay + "&year=" + qYear + "&gender=" + qGender + "&contest=" + qContest + "&store=" + qStore + "&date=" + qDate,
success: function(){
// delete each row as passed to host
db.transaction(function(tx)
{
tx.executeSql('DELETE FROM entries WHERE ID = ?', [qID]);
});
// alert ("Success");
}
});
}
});
});
}
the php is simple like :
<?php
$link = mysql_connect('host', 'user', 'password');
if (!$link) {
die('Could not connect: ' .mysql_error());
}
echo 'Connected successfully';
$email = htmlspecialchars(trim($_POST['email']));
$phone = htmlspecialchars(trim($_POST['phone']));
$month = htmlspecialchars(trim($_POST['month']));
$day = htmlspecialchars(trim($_POST['day']));
$year = htmlspecialchars(trim($_POST['year']));
$gender = htmlspecialchars(trim($_POST['gender']));
$contest = htmlspecialchars(trim($_POST['contest']));
$store = htmlspecialchars(trim($_POST['store']));
$datestamp = htmlspecialchars(trim($_POST['date']));
mysql_select_db("sandbox_info") or die (mysql_error());
mysql_query("INSERT INTO `infoData` (email, phone, birth_month, birth_day, birth_year, gender, storeNo, contest, added_on) VALUES ('$email','$phone','$month','$day','$year','$gender','$store','$contest','$datestamp')");
echo 'Data uploaded';
mysql_close($link);
?>
Can someone please help explain what is wrong with the delete transaction? It does delete one row each time I run the process but I would like it to delete all of them. I guess I could drop the whole table but I would rather it runs a check after each transfer to the remote host and then deletes the local data. I would also appreciate any tips on how this code could just be improved in general. Thanks in advance for any advice!
REVELATION
OK i echoed back the qID in the success and found out since it is deleting out each row it is then giving a new id to the next available row and keeps echoing out the same id over and over. So... I know the problem but still need some help to find the fix.

You seem to have described it well enough: if you already have HTTP POST support in your app (using java.net.URL or HttpClient) and a PHP script that works on the server, you'll need to:
Detect when someone is online (look at their IP address or try and connect to your server).
Generate a list of all unsaved transactions: you've got the basic code for that above, maybe you need some flag.
For each row, generate a POST to the server: if the POST succeeds (returns a 200 success code) then delete the row from the local database (or mark it as synchronized in some other way).
That should do it?

I'm not 100% clear on what you are trying to do but...
You could have one side generate a list of INSERT statements from the data that would be executed on the other side.

Related

Jquery ajax not call not working

I have 2 files in my directory: one is js/form-validation-reg.js and one is HTML/registeruser.php. The javascript file validates a form from another html file which I have already checked; all values are passed all the way till the ajax but the values does not seem to be send to registeruser.php to be send in my database.
form-validation-reg.js:
//data string creation
var dataString = 'name='+ name
+ '&pass=' + pass
+ '&nationality=' + nationality
+ '&contactno=' + contactno
+ '&dateofbirth=' + dateofbirth
+ '&eaddress=' + eaddress
+ '&address=' + address
+ '&gender=' + gender
+ '&monthlysub=' + monthlysub;
//ajax
$.ajax({
type:"POST",
url: "HTML/registeruser.php",
data: dataString,
success: success(),
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});
});
no errors is displayed and i have also tried setting the url as "../HTML/registeruser.php" but it still doesn't work.
PHP file(NOTE:i have also made sure my database details are correct.):
$name = stripslashes(strip_tags($_POST['name']));
$pass = stripslashes(strip_tags($_POST['pass']));
$nationality = stripslashes(strip_tags($_POST['nationality']));
$contactno = stripslashes(strip_tags($_POST['contactno']));
$dateofbirth = stripslashes(strip_tags($_POST['dateofbirth']));
$eaddress = stripslashes(strip_tags($_POST['eaddress']));
$address = stripslashes(strip_tags($_POST['address']));
$gender = stripslashes(strip_tags($_POST['gender']));
$monthlysub = stripslashes(strip_tags($_POST['monthlysub']));
$mysqli = new mysqli("localhost", "root", "","testdb")or exit("Error connecting to the database.");
$stmt = $mysqli->prepare("INSERT INTO user
(name, password, nationality, contactno, dateofbirth, email, address, gender, monthlysub)
VALUES (?,?,?,?,?,?,?,?,?)");
$stmt->execute();
$stmt->bind_param("sssssssss", $name, $pass, $nationality, $contactno, $dateofbirth, $eaddress, $address, $gender, $monthlysub);
$stmt->fetch();
$stmt->close();
$mysqli->close();
try:
success: success,
instead of :
success: success(),
Not sure if this might help, but your dataString variable looks like you're building it to go into a URL which would use get instead of post. It could be that your php script doesn't know how to parse what's getting passed to it because it's looking in the post variables instead. Since you're passing a password you wouldn't want to use get for security reasons though.
You need to be calling the $stmt->bind_param before the $stmt->execute();
If there is still an issue then you need to break it down to see what is given you the issue:
1) Ensure that the Javascript is getting called. Put an alert() in your Javascript and reload the page. If the alert pops up then your are fine there and you can rule out any include URL issues.
2) If you are using Firefox, install firebug and then hit F12 and view the console. You will see the HTML/registeruser.php getting called and you will also be able to see the parameters that are getting sent and other info. You can also do this in Chrome. If the URL is getting called and you are receiving a 200 response then there are no problems there and that is one more thing you can rule out.
3) At this point we have ruled out the Javascript and the Ajax call. So now we focus on the Database connection and then the SQL query. After your connection on the registeruser.php do a select statement of a table that you know has records, echo them out to ensure you definitely have a connection and that you are connected to the correct database.
4) Echo your SQL statement to ensure that it has all the parameters.
By the way, you should also check your error handling, instead of using exit you should be checking for the mysqli error so after the new mysqli call then add this:
if (mysqli_connect_errno()) {
printf("Error connecting to the database: %s\n", mysqli_connect_error());
exit();
}
You may use a library that does that automatically, like http://phery-php-ajax.net already do the bridge between jQuery and PHP automatically
phery.remote('registeruser', {
'name': name,
'pass': pass,
'nationality': nationality,
'contactno': contactno,
'dateofbirth': dateofbirth,
'eaddress': eaddress,
'address': address,
'gender': gender,
'monthlysub': monthlysub,
});
Phery::instance()->set(array(
'registeruser' => function($data){
$data = array_map('strip_tags', $data);
/* rest of mysql code */
return PheryResponse::factory(); // do any DOM manipulation, redirect, etc
}
))->process();

Updating HTML Element Every Second With Content From MySQL Database

I'd like to have a div on my web page that is based off of the data in my MySQL database. When the data in the database changes, the content in the div should change as well.
Example: Let's say I have a field in the first row of a table called "server_statistics" in my MySQL database which keeps track of a server being online or offline. When the server goes offline, the MySQL field changes from 1 to 0. When it goes online, it goes from 0 to 1.
So I want to use Javascript to display the server status on my webpage and update it without refreshing the page.
I thought I'd be able to do it like this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
var statusElement = document.getElementById("status");
var status = "<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>";
if (status == 0) {
statusElement.style.color = "red";
statusElement.innerHTML = "offline";
}
else {
statusElement.style.color = "green";
statusElement.innerHTML = "online";
}
}
</script>
But this doesn't work. The page needs to be refreshed for it to update and I don't know why...
I've read I can use JQuery but I have no knowledge of this language at all.
I tried this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
$('#status').load('load.php');
}
</script>
and then in load.php I had this:
<?php
echo "test";
?>
But nothing happened after 1 second passed. I'm probably doing it wrong because as I said, I don't know anything about this JQuery/AJAX stuff.
So how can I accomplish retrieving a field from a MySQL database at every specified interval and then automatically update an HTML element accordingly? It would be ideal to only update the HTML when a change occurred in the database but for now, I just want it to change every few seconds or minutes...
Thanks in advance.
What you need to do is utilize AJAX. Your page will need to make a request to the server each time it wants to check the status. There are two ways to do it: manually refresh the page yourself, or use an AJAX call.
AJAX really isn't all that difficult, you start by creating a separate PHP page check_status.php with the following in it:
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>
Then, in your HTML page, the easiest way to do this would be to use jQuery:
var statusIntervalId = window.setInterval(update, 1000);
function update() {
$.ajax({
url: 'check_status.php',
dataType: 'text',
success: function(data) {
if (parseInt(data) == 0) {
$("#status").css({ color: "red" }).text("offline");
} else {
$("#status").css({ color: "green" }).text("online");
}
}
}
}
That's it really. Every second, it will call the update() method which makes an AJAX call and inserts the result back into your HTML.
instead of var int = self.setInterval("update()", 1000); try using self.setInterval(update, 1000); and place it after the update function.

resetting variables in php to display in javascript

I'm trying to get some values off a DB and then putting those values into javascript variables. I managed to do just that, the problem I'm having is when the values in the DB change the values of the variables don't. I figured the problem lies within my PHP, but I cant find it. Can you guys help me?
here's my code:
PHP
<?php
session_start();
if(!isset($_SESSION['u_name'])){
$_SESSION['u_name'] = '';
}
mysql_connect ("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db('raffleiz_Main')or die ("cannot select DB :(");
$signups = mysql_query("SELECT * FROM `Rafflez_info`") or die ('Error: ' . mysql_error());
$row = mysql_num_rows($signups);
//pull all of the data and store it
for($p = 0; $p < $row; $p++){
$participants[$p] = mysql_result($signups, $p, "#_participants");
};
for($a = 0; $a < $row; $a++){
$max_participants[$a] = mysql_result($signups, $a, "max_participants");
};
?>
and my javascript function:
function progress(){
var signups = "<?php echo $participants[0]; ?>";
var maxP = "<?php echo $max_participants[0]; ?>";
alert (signups);
alert (maxP);
var pSignup = signups / maxP;
alert (pSignup);
var total = 550 * pSignup;
var theImg = document.getElementById('progress');
theImg.width = total;
alert (total);
};
I put the "alert" command there so that I could see the change in the values. right now the values don't change no matter what I change them to in the DB.
PHP is a server-side language, meaning that when it served the script from the server to the client, there is no going back.
JavaScript is a client-side language, thus can receive values from a server-side language such as PHP. The values received are then client-side only, a copy if you will.
You can use the XMLHttpRequest API to request a script from a server, updating the local client-side values.
I recommend using the jQuery $.ajax function to easily achieve that.
Here's a nice tutorial from Nettuts to get your started.
You need to call your php page and ask it if values are changes. You can easily use jQuery AJAX to achieve that. Use JSON for easier data transfer. If you want to check if values are changes every 3 seconds for example you can do this:
var interval = window.setInterval(function(){
jQuery.ajax({
url: 'your php file address',
success: function(data){
progress(data)
}
});
}, 3000);
You will need to change you proccess and php code. This is just to give you the idea.

mySQL insert statement NOT working?

I've been looking around for an answer. I've been cross-referencing my code with others. And I don't seem to see any blatant errors...
My database does not update, my database does nothing. Oh and the page also does nothing too...... It's frustrating because, I'm just using notepad ++ and can't pinpoint the error. I'm using XAmpp as well, and, all the values match the ones I have made.
The .post statement (Using jQuery 1.7.1):
//Make sure DOM is loaded before running jQuery based code: [STATIC CODE]
$(document).ready(function(){
$('#uploadbtn').click(function() {
//Parse name and song.
var name = $('#songname').val();
var song = $('#songupload').val();
$.ajax(
{
type: 'POST',
data: 'db/upload.php?name=' + name + 'song=' + song,
success: function(res) {
$('#nav-playlist').html(res);
}
}
)
});
});
Now here is my php file:
<?php
/*Connection to database.
First with mysql_connect (to log in). Then selecting the master database.
*/
echo "Upload.php accessed...";
$connection = mysql_connect("localhost", "root", "root") or die ( mysql_error() );
$database = mysql_select_db("betadb") or die( mysql_error() );
//Properties (to be inserted into database).
$name = mysql_real_escape_string($_POST["name"]);
$song = mysql_real_escape_string($_POST["song"]);
//Insertion formula for mySQL
$query = "INSERT INTO songs SET name= '$name' song='$song' ";
if (mysql_query($query)){
echo "Success";
}
else {
}
?>
ADDITIONAL NOTES:
the song table consists of id, name, song (in that order).
Song is the BLOB datatype, as it is used to store .mp3s
The problem is with the following line
data : 'db/upload.php?name='+name+'song='+song,
data should be an array containing the values, such as
var data
data["name"] = name
data["song"] = song
The $.ajax call is also missing the url parameter which is needed to carry out the request
url: 'db/upload.php'
Try to specify your column.
$query = "INSERT INTO songs (youcoulmn1,youcolumn2) VALUES ('$name', '$song')";
See also:
PHP MySQL Insert Into
Regards
$name = mysql_real_escape_string($_POST["name"]); //Assign to name & song variables.
$song = mysql_real_escape_string($_POST["song"]);
//Insertion formula for mySQL
$query = "INSERT INTO songs VALUES ('$name', '$song')";
$result = mysql_query($query, $connection) or die ("Unsucessful");
had better using SET, is more easier for some conditions, and for Jquery Command use $.ajax, you can try this one
for javascript / JQuery
$(function(){
$('#uploadbtn').click(function(){
var name = $('#songname').val();
var song = $('#songupload').val();
$.ajax({
type :'POST',
data : 'db/upload.php?name='+name+'song='+song,
success :function(res){
$('#nav-playlist').html(res);
}
});
});
});
and for Insert command in the php
$name = mysql_real_escape_string($_POST["name"]);
$song = mysql_real_escape_string($_POST["song"]);
$query = "INSERT INTO songs SET name='$name' song='$song'";
if(mysql_query($query)){
// some process if success
}else{
// some proses if not
}
use mysql_real_escape_string to filtering data before insert to database
in order to debug it
1) do print_r($_POST); to check do you have anything to insert
2) then instead of
$result = mysql_query($query, $connection) or die ("Unsucessful");
do
$result = mysql_query($query, $connection) or die (mysql_error());
to get the exact error and search for the error fix
The single quotes around variables might be causing the problem.. check it..
As far as I remember, the line
$query = "INSERT INTO songs SET name= '$name' song='$song' ";
should be
$query = "INSERT INTO songs SET name= '$name', song='$song' ";
Pay attention to commas!
And also:
data: 'db/upload.php?name=' + name + 'song=' + song,
should be at least:
data: 'db/upload.php?name=' + name + '&song=' + song,
because there is no delimiter between fields right now.

Database Entry not showing up in IE unless browser is fully closed and reopened

I have a form currently has 2 drop downs. Selecting an option from the first drop down populates the second drop down.
This works fine. I just noticed though that when I add a new item to the second dropdown that It will enter it in the database fine but it will not show up in the drop down menu in Internet Explorer. However if I completely close the browser and reopen it they new entry will show up. It almost seems like a cache type error. It works fine in all other browsers.
The code I am using is
function populateSubCategory() {
$.getJSON('../inc_selectlogic.php', {category_id:$('#category_id').val()}, function(data) {
var select = $('#sub_category_id');
var options = select.attr('options');
$('option', select).remove();
$("#sub_category_id").append('<option value="">CATEGORY</option>');
$.each(data, function(index, array) {
$("#sub_category_id").append('<option value='+array['sub_category_id']+'>'+ array['sub_category_name'] +'</option>');
});
});
}
The PHP is calls is
$dsn = "HIDDEN";
$username = "HIDDEN";
$password = "HIDDEN";
$pdo = new PDO($dsn, $username, $password);
$rows = array();
if(isset($_GET['category_id'])) {
$stmt = $pdo->prepare("SELECT SQL_NO_CACHE sub_category_name, sub_category_id FROM sub_categories WHERE category_id = ?");
$stmt->execute(array($_GET['category_id']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);
You can work around the cache issue by adding a variable to the end of the request url that makes the request unique each time.
var time = new Date().getTime();
$.getJSON('../inc_selectlogic.php?time=' + time, {category_id:$('#category_id').val()}, function(data) {

Categories