0% found this document useful (0 votes)
1 views3 pages

PHP Ajax Mysql Easy Example

The document outlines a simple example of using PHP, AJAX, and MySQL to fetch user data. It includes steps to create a database and table, an HTML file with an AJAX button, and a PHP file to retrieve user information from the database. The implementation allows for fetching user data without reloading the page.

Uploaded by

solankibansi0811
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views3 pages

PHP Ajax Mysql Easy Example

The document outlines a simple example of using PHP, AJAX, and MySQL to fetch user data. It includes steps to create a database and table, an HTML file with an AJAX button, and a PHP file to retrieve user information from the database. The implementation allows for fetching user data without reloading the page.

Uploaded by

solankibansi0811
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Simple PHP + AJAX + MySQL Example

Step 1: Create Database and Table

----------------------------------

CREATE DATABASE testdb;

USE testdb;

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100) NOT NULL

);

INSERT INTO users (name) VALUES ('Alice'), ('Bob'), ('Charlie');

Step 3: Create index.html (AJAX + Button)

-----------------------------------------

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>AJAX + PHP + MySQL Example</title>

<script>

function loadUser() {

var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {

if (this.readyState == 4 && this.status == 200) {


document.getElementById("user").innerHTML = this.responseText;

};

xhttp.open("GET", "fetch_user.php", true);

xhttp.send();

</script>

</head>

<body>

<h2>Fetch User from MySQL Database</h2>

<button onclick="loadUser()">Get User</button>

<div id="user"></div>

</body>

</html>

Step 4: Create fetch_user.php (PHP File)

----------------------------------------

<?php

// fetch_user.php

$conn = new mysqli("localhost", "root", "", "testdb");

if ($conn->connect_error) {

die("Database connection failed!");


}

$result = $conn->query("SELECT name FROM users LIMIT 1");

if ($row = $result->fetch_assoc()) {

echo $row["name"];

} else {

echo "No user found.";

$conn->close();

?>

Summary:

- Create Database -> Table -> Insert Users.

- index.html sends AJAX request on button click.

- fetch_user.php connects to DB and sends back the user name.

- Smooth and NO page reload!

You might also like