Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Created July 3, 2023 01:44
Show Gist options
  • Save code-boxx/69c975b76f367b13f967a909c04c342c to your computer and use it in GitHub Desktop.
Save code-boxx/69c975b76f367b13f967a909c04c342c to your computer and use it in GitHub Desktop.
Javascript Connect To Database

JAVASCRIPT CONNECT TO DATABASE

https://code-boxx.com/connect-database-javascript/

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE `users` (
`user_id` bigint(20) NOT NULL,
`user_name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `users` (`user_id`, `user_name`) VALUES
(1, 'Joe Doe'),
(2, 'Jon Doe'),
(3, 'Joy Doe');
ALTER TABLE `users`
ADD PRIMARY KEY (`user_id`),
ADD KEY `user_name` (`user_name`);
ALTER TABLE `users`
MODIFY `user_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
<?php
// (A) SETTINGS - CHANGE TO YOUR OWN !
error_reporting(E_ALL & ~E_NOTICE);
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (B) CONNECT TO DATABASE
$pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
// (C) GET USERS
$stmt = $pdo->prepare("SELECT * FROM `users`");
$stmt->execute();
$users = $stmt->fetchAll();
foreach ($users as $u) {
printf("<div>[%u] %s</div>", $u["user_id"], $u["user_name"]);
}
// (D) CLOSE DATABASE CONNECTION
$pdo = null;
$stmt = null;
<!DOCTYPE html>
<html>
<head>
<title>AJAX Demo</title>
</head>
<body>
<!-- (A) LIST USERS HERE -->
<div id="demo"></div>
<!-- (B) FETCH USERS VIA AJAX -->
<script>
// NOTE: RUN WITH HTTP://, NOT FILE://
window.addEventListener("load", () => {
fetch("1b-database.php", { method: "POST" })
.then(res => res.text())
.then(txt => document.getElementById("demo").innerHTML = txt);
});
</script>
</body>
</html>
// (A) LOAD DB MODULE
const mysql = require("mysql");
// (B) CREATE CONNECTION - CHANGE TO YOUR OWN !
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "test"
});
db.connect(err => {
if (err) { throw err; }
console.log("DB connection OK");
});
// (C) QUERY
db.query("SELECT * FROM `users`", (err, results) => {
if (err) { throw err; }
console.log(results);
});
<!DOCTYPE html>
<html>
<head>
<title>Localstorage Demo</title>
<script>
// (A) DATA OBJECT
var user = {
name : "Jon Doe",
email : "jon@doe.com"
};
// (B) STORE IN LOCAL STORAGE
// note: json encode
localStorage.setItem("User", JSON.stringify(user));
// (C) RETRIEVE
// note: json decode
user = localStorage.getItem("User");
user = JSON.parse(user);
console.log(user);
</script>
</head>
<body></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment