PHP is a server-side programming language that can be used to interact with a database.
Imagine you have a database on your server, and you want to send a request to retrieve the first 10 rows from a table called “customers.”
On the client side, create a JSON object that specifies the number of rows you want to return.
Before sending the request to the server, convert the JSON object into a string and include it as a parameter in the URL of the PHP page.
Use JSON.stringify() to convert the JavaScript object into a JSON string.
const limit = {“limit”:10}; const dbParam = JSON.stringify(limit); xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { document.getElementById(“demo”).innerHTML = this.responseText; } xmlhttp.open(“GET”,“json_demo_db.php?x=” + dbParam); xmlhttp.send(); |
Now, review the PHP file.
<?php header(“Content-Type: application/json; charset=UTF-8”); $obj = json_decode($_GET[“x”], false); $conn = new mysqli(“myServer”, “myUser”, “myPassword”, “Northwind”); $stmt = $conn->prepare(“SELECT name FROM customers LIMIT ?”); $stmt->bind_param(“s”, $obj->limit); $stmt->execute(); $result = $stmt->get_result(); $outp = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($outp); ?> |