Connecting to a MySQL database via jQuery

I know how to process a form via AJAX, but I don’t know how would I pass a string via jQuery to PHP in order for it to be saved in a MySQL database. I have a variable in jQuery which holds a value from Moment.js, a time when a particular employee logged in, and I want to pass that string to PHP function and update the MySQL table for that user so that it is saved in the column ‘startTime’. My question is, how would I go about doing that? I know how to process forms via AJAX, but not how to pass a variable from jQuery to PHP like this. Any help would be greatly appreciated. Thank you.

exactly the same. in the jQuery AJAX there is a setting called data which accepts the content to transfer. further details on how to use that can be found in the jQuery API Docs.

Something like:

var startTime = your variable which holds a value from Moment.js
$.ajax({
  type : "POST",
  url: "myScriptphp",
  data: {startTime: startTime},
});

Then in myScript.php:

$pdo = new PDO('mysql:host=host_name;dbname=db_name', 'user', 'pass');
$sql = "INSERT INTO myTable(startTime,:startTime);
$stmt = $pdo->prepare($sql);                                              
$stmt-> bindParam(':startTime', $_POST['startTime'], PDO::PARAM_STR);
$stmt-> execute();

Thanks for response, but I’ve run into another problem. I did manage to UPDATE the database (which is an improvement), but I’m getting a wrong result.

Here’s my PHP code:

<?php

$pdo = new PDO('mysql:host=localhost;dbname=sample_db', 'root', '');

$sql = "UPDATE sample_table SET start=\"(timeNow, timeNow)\" WHERE name=\"John\"";

$stmt = $pdo->prepare($sql);

$stmt->bindParam(':timeNow', $_POST['timeNow'], PDO::PARAM_STR);

$stmt->execute();

?>

And here’s the jQuery:

var timeNow = moment().format("HH:mm:ss");

$("button").on("click", function(event) {
	event.preventDefault();

	$.ajax({
		type: "POST",
		url: "test.php",
		data: {timeNow: timeNow},
	});
});

The problem is, I’m getting (timeNow, timeNow) saved into the database whenever I press a button. I suppose the problem is in how I use an UPDATE statement?

I got it working this way:

$sql = 'UPDATE sample_table SET start=:timeNow WHERE name="John"';

Thank you for guiding me in right direction!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.