隨著NoSQL資料庫管理系統的普及,很多軟體的資料存放區都轉向MongoDB資料庫。它採用動態模式將資料轉化為結構化的JSON文檔儲存,提高應用程式效能。
本章教程我們學習使用PHP和MongoDB實現簡單的使用者登入功能。
學習本教程之前,請保證已經存在PHP mongo驅動,如果你還沒有,請通過下面的地址下載:
Windows:
http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/
Linux和Mac
http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/
串連到MongoDB
無驗證串連
<?php$mongo = new Mongo();$db = $mongo->selectDB(“test”);?>
驗證串連
<?php$mongo = new Mongo(“mongodb://{$username}:{$password}@{$host}”);$db = $mongo->selectDB(“test”);?>
預設情況下,MongoDB有一個“test”樣本資料庫。或者你也可以建立新的資料庫:
$ db = $ mongo - > Database_Name;
查詢
PHP擷取資料庫列表
//擷取資料庫列表$mongo->admin->command(array(“listDatabases” => 1));//擷取test資料庫的表$db->listCollections();
Mongo在終端使用如下命令也可以達到上面的查詢效果:
db.listDatabasesdb.test.showCollections
建立集合(表)
PHP語句建立表
$db->createCollection(“people”,false);
這裡的false表示無窮大小,如果為true,則必須指定表的最大空間。
Mongo終端命令建立表:
$db->createCollection(“people”,false);
插入記錄
PHP代碼插入記錄
<?php$people = $db->people;$insert = array(“user” => “demo@uncletoo.com”, “password” => md5(“demo_password”));$db->insert($insert);?>
Mongo終端命令插入記錄
b.people.insert({user:”user_name”,password:”password”});
更新記錄
PHP代碼實現更新MongoDB
<?php$update = array(“$set” => array(“user” => “demo@9lessons.info”));$where = array(“password” => “password”);$people->update($where,$update);?>
Mongo 終端命令實現更新
db.people.update({password:”password”},{$set : {user:”demo@uncletoo.com”}});
HTML表單
<form action="index.php" method="POST">Email:<input type="text" id="usr_email" name="usr_email" />Password:<input type="password" id="usr_password" name="usr_password" /><input name="submitForm" id="submitForm" type="submit" value="Login" /></form>
完整的PHP代碼 index.php
<?php$succss = "";if(isset($_POST) and $_POST['submitForm'] == "Login" ){$usr_email = mysql_escape_string($_POST['usr_email']);$usr_password = mysql_escape_string($_POST['usr_password']);$error = array();// Email Validationif(empty($usr_email) or !filter_var($usr_email,FILTER_SANITIZE_EMAIL)){$error[] = "Empty or invalid email address";}if(empty($usr_password)){$error[] = "Enter your password";}if(count($error) == 0){$con = new Mongo();if($con){// Select Database$db = $con->test;// Select Collection$people = $db->people;$qry = array("user" => $usr_email,"password" => md5($usr_password));$result = $people->findOne($qry);if($result){$success = "You are successully loggedIn";// Rest of code up to you....}} else {die("Mongo DB not installed");}}}?>
本文講述了PHP MongoDB 實現簡單使用者登入的執行個體,希望本文能給讀者帶來靈感,協助讀者解決疑問,感謝您閱讀本文。