Skip to content

Instantly share code, notes, and snippets.

@gautamk
Created March 19, 2012 00:49
Show Gist options
  • Save gautamk/2087994 to your computer and use it in GitHub Desktop.
Save gautamk/2087994 to your computer and use it in GitHub Desktop.
Script to insert an array into mongodb and retrieve its id
<?php
/**
* This Script inserts a mongo array in the database and
* retrieves its id and displays it
*/
$form=array(
"model"=>"DynamicFormResponse",
"options"=>array(
"type"=>"post",
),
"inputs" => array(
"username"=>array(
"placeholder"=>"Enter your username",
),
"password"=>array(
"placeholder" => "Enter your Password",
"type"=>"password"
),
),
"submit"=>"Login",
"mongoschema"=>array(
"username"=>array("type"=>"string"),
"password"=>array("type"=>"string")
),
"validation"=>array(
"username"=>array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only',
"allowEmpty"=>false
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters',
"allowEmpty"=>false
)
),
'password' => array(
"minLength"=>array(
'rule' => array('minLength', '8'),
'message' => 'Minimum 8 characters long',
"allowEmpty"=>false
),
),
),
"created"=> new MongoDate(),
);
$collectionName="dynamicForms";
$m = new Mongo(); // connect
$db = $m->cake;
$collection = $db->selectCollection($collectionName);
$collection->insert($form);
$result = $collection->find()->sort(array('$natural'=>-1))->limit(1);
$result = $result->getNext();
?>
<html>
<head>
<meta charset="utf-8">
<title><?php echo $result['_id']; ?>:<?php echo $collectionName; ?></title>
<style>
.dbid{
border-style: none;
font-size: 70px;
font-weight: bolder;
font-family: monospace;
}.dbid:{
border-style: none;
}
</style>
</head>
<body>
<h1>DO NOT RELOAD THE PAGE</h1>
<h3>Reloading the page inserts a new entry into the collection</h3>
<h2>
The following was added to the database _id:
<input value="<?php echo $result['_id']; ?>"
class="dbid"
onclick="this.select();"
/>
in collection : <?php echo $collectionName; ?>
</h2>
<pre>
<?php
// $pattern = array(',"', '{', '}');
// $replacement = array(",\n\t\"", "{\n\t", "\n}");
// echo str_replace($pattern, $replacement, json_encode($form) );
print_r($result);
?>
</pre>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment