Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Created May 29, 2023 03:46
Show Gist options
  • Save code-boxx/fa3ada850ce6ad1dfbfae0fd0dd1b3af to your computer and use it in GitHub Desktop.
Save code-boxx/fa3ada850ce6ad1dfbfae0fd0dd1b3af to your computer and use it in GitHub Desktop.
Store & Retrieve PHP Array In MYSQL Database

STORE & RETRIEVE PHP ARRAY IN MYSQL DATABASE

https://code-boxx.com/store-arrays-mysql-php/

NOTES

  1. Change the database settings in 1-database.php to your own.
  2. Files starting with 2- - Store & retrieve array as a JSON string.
  3. Files starting with 3- - Store array in a "dedicated standalone" table.

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.

<?php
class Database {
// (A) CONSTRUCTOR - CONNECT TO DATABASE
private $pdo = null;
private $stmt = null;
public $error = "";
function __construct() {
$this->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
]);
}
// (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
function __destruct() {
if ($this->stmt !== null) { $this->stmt = null; }
if ($this->pdo !== null) { $this->pdo = null; }
}
// (C) HELPER - EXECUTE SQL QUERY
function exec ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) FETCH COLUMN
function fetch ($sql, $data=null) {
$this->exec($sql, $data);
return $this->stmt->fetchColumn();
}
// (E) FETCH ALL ON A SINGLE COLUMN
function fetchCol ($sql, $data=null) {
$this->exec($sql, $data);
return $this->stmt->fetchAll(PDO::FETCH_COLUMN);
}
// (F) FETCH ALL
function fetchAll ($sql, $data=null) {
$this->exec($sql, $data);
return $this->stmt->fetchAll();
}
}
// (G) SETTINGS - CHANGE THESE TO YOUR OWN !
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (H) DATABASE OBJECT
$_DB = new Database();
CREATE TABLE `people` (
`id` bigint(20) NOT NULL,
`name` varchar(255) NOT NULL,
`colors` JSON NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `people`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `name` (`name`);
ALTER TABLE `people`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;
<?php
// (A) LOAD DATABASE LIBRARY
require "1-database.php";
// (B) JSON ENCODE & INSERT INTO DATABASE
$sql = "INSERT INTO `people` (`id`, `name`, `colors`) VALUES (?,?,?)";
$_DB->exec($sql, [1, "Job", json_encode(["Red", "Green", "Blue"])]);
$_DB->exec($sql, [2, "Joe", json_encode(["Red", "Blue"])]);
$_DB->exec($sql, [3, "Joy", json_encode(["Red", "Green"])]);
echo "OK";
<?php
// (A) LOAD DATABASE LIBRARY
require "1-database.php";
// (B) FETCH & JSON DECODE
$sql = "SELECT `colors` FROM `people` WHERE `id`=?";
$colors = json_decode($_DB->fetch($sql, [1])); // JOB
print_r($colors);
$colors = json_decode($_DB->fetch($sql, [2])); // JOE
print_r($colors);
$colors = json_decode($_DB->fetch($sql, [3])); // JOY
print_r($colors);
CREATE TABLE `colors` (
`id` bigint(20) NOT NULL,
`color` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `colors`
ADD PRIMARY KEY (`id`,`color`);
<?php
// (A) LOAD DATABASE LIBRARY
require "1-database.php";
// (B) COLORS (USER ID => COLORS)
$colors = [
"1" => ["Red", "Green", "Blue"],
"2" => ["Red", "Magenta", "Orange", "Yellow"],
"3" => ["Red", "Blue", "Cyan", "Lime"]
];
// (C) SQL INSERT DATA
$sql = "INSERT INTO `colors` (`id`, `color`) VALUES ";
$data = [];
foreach ($colors as $id=>$col) { foreach ($col as $c) {
array_push($data, $id, $c);
$sql .= "(?,?),";
}}
$sql = substr($sql, 0, -1) . ";";
echo $sql; print_r($data);
// (D) GO!
$_DB->exec($sql, $data);
echo "OK";
<?php
// (A) LOAD DATABASE LIBRARY
require "1-database.php";
// (B) FETCH
$sql = "SELECT `color` FROM `colors` WHERE `id`=?";
$colors = $_DB->fetchCol($sql, [1]); // JOB
print_r($colors);
$colors = $_DB->fetchCol($sql, [2]); // JON
print_r($colors);
$colors = $_DB->fetchCol($sql, [3]); // JOY
print_r($colors);
<?php
// (A) LOAD DATABASE LIBRARY
require "1-database.php";
// (B) POPULAR COLORS
$colors = $_DB->fetchAll("SELECT `color`, COUNT(*) `count`
FROM `colors`
GROUP BY `color`
ORDER BY `count` DESC");
print_r($colors);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment