Skip to content

Instantly share code, notes, and snippets.

@Deathnerd
Last active August 29, 2015 13:59
Show Gist options
  • Save Deathnerd/10562538 to your computer and use it in GitHub Desktop.
Save Deathnerd/10562538 to your computer and use it in GitHub Desktop.
<?php
/**
* Created by PhpStorm.
* User: Deathnerd
* Date: 4/12/14
* Time: 5:58 PM
*/
if(empty($_GET)){
echo "Get not set";
die();
}
function key_value_to_JSON($array){
if(!is_array($array)){
trigger_error("getToJSON requires the argument to be an array", E_USER_ERROR);
}
$json = json_encode(stripslashes($array), JSON_PRETTY_PRINT);
$file = fopen('keys_and_values.json', 'w') or die("Cannot create file");
fwrite($file, $json) or die("Cannot write to file");
fclose($file);
}
function get_key_value_from_JSON($fileName){
if(!is_string($fileName)){
trigger_error("get_key_value_from_JSON requires the argument to be a string", E_USER_ERROR);
}
//return as a keyed array
return json_decode(file_get_contents($fileName, true), true);
}
function key_value_to_database($array){
if(!is_array($array)){
trigger_error("getToDatabase requires the argument to be an array", E_USER_ERROR);
}
$json = json_encode(stripslashes($array), JSON_PRETTY_PRINT);
$db = mysqli_connect('localhost', 'root', 'root', 'db');
$table = 'keysToValues';
//check if the table exists
if(!(mysqli_num_rows(mysql_query($db, "SHOW TABLES LIKE '".$table."'")) > 0)) {
mysqli_query($db, "CREATE TABLE '".$table."' (keys VARCHAR(255), val VARCHAR(255) );") or die(mysqli_error($db));
}
//insert the values
foreach($json as $key => $value){
$value = mysqli_real_escape_string($db, $value);
mysqli_query($db, "INSERT INTO `$table` (keys, val) VALUES ($key, $value)") or die(mysqli_error($db));
}
}
function get_key_value_from_database(){
$db = mysqli_connect('localhost', 'root', 'root', 'db');
$table = 'keysToValues';
//check if table exists
if(!(mysqli_num_rows(mysql_query($db, "SHOW TABLES LIKE '$table'")) > 0)){
die(mysqli_error($db));
}
$query = mysqli_query($db, "SELECT * FROM `$table`");
if(mysql_num_rows($query) === 0){
return false;
}
$rows = array();
while($row = $query->fetch_assoc()){
$rows[] = $row;
}
return $rows;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment