Skip to content

Instantly share code, notes, and snippets.

@neckro
Created May 22, 2013 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neckro/5631488 to your computer and use it in GitHub Desktop.
Save neckro/5631488 to your computer and use it in GitHub Desktop.
Quickie key/value store page with PHP/MySQL, example
<?php
/* Table schema
CREATE TABLE `params` (
`key` varchar(255) NOT NULL DEFAULT '',
`value` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
*/
// Settings
$db = new mysqli('localhost', 'simulator', 'pa55word', 'simdb');
$params = array('frobnozzes', 'whatsits', 'doohickeys', 'bronsons');
$password = 'reindeerflotilla';
if ($_SERVER['QUERY_STRING'] == 'json') {
echo json_encode(get_params());
exit;
}
function set_params() {
global $db, $params, $password;
if (empty($_REQUEST['password'])) return;
if ($_REQUEST['password'] !== $password) {
echo "<p>Bad password.</p>\n";
return;
}
foreach($params as $k) {
if (empty($_REQUEST[$k])) continue;
$v = $_REQUEST[$k];
$stmt = $db->prepare("REPLACE INTO params(`key`, `value`) VALUES (?, ?)");
if (!$stmt) continue;
$stmt->bind_param('ss', $k, $v);
if (mysqli_stmt_execute($stmt)) {
echo "<p>Set parameter {$k} to {$v}.</p>\n";
} else {
echo "<p>Error setting parameter {$k}.</p>\n";
}
$stmt->close();
}
}
function get_params() {
global $db;
$out = array();
$stmt = $db->prepare("SELECT `key`, `value` FROM params");
$stmt->execute();
$stmt->bind_result($k, $v);
while($stmt->fetch()) {
$out[$k] = $v;
}
$stmt->close();
return $out;
}
?><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Sim Control</title>
</head>
<body>
<form action="" method="POST">
<?php
set_params();
$data = get_params();
foreach($params as $k) {
if (empty($data[$k])) {
$v = '';
} else {
$v = $data[$k];
}
echo "<p>{$k}: <input type='text' name='{$k}' value='{$v}' /></p>\n";
}
?>
<p>Magic password: <input type="password" name="password" /></p>
<p><input type="submit" /></p>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment