/** * Disconnect from MongoDB * * @returns null */ public function disconnect() { if ($this->_connection) { $this->_connection->close(); } $this->_db = $this->_connection = NULL; }
/** * Closes the currently active Mongo connection. * It does nothing if the connection is already closed. * @since v1.0 */ protected function close() { if ($this->_mongoConnection !== null) { $this->_mongoConnection->close(); $this->_mongoConnection = null; Yii::trace('Closing MongoDB connection', 'ext.MongoDb.EMongoDB'); } }
/** * Disconnect from a mongo database. * * @return boolean disconnect result */ public function disconnect() { if ($this->connection->close()) { $this->connected = false; return true; } return false; }
public function testClose() { $this->object = new Mongo(); $this->assertTrue($this->object->connected); $this->object->close(); $this->assertFalse($this->object->connected); $this->object->close(); $this->assertFalse($this->object->connected); }
/** * Disconnect from MongoDB * * @return null */ public function disconnect() { if ($this->_connection) { try { $this->_connection->close(); } catch (\Exception $e) { } } $this->_db = $this->_connection = null; }
public function save() { $conn = new Mongo('localhost'); $db = $conn->users; $collection = $db->items; $collection->save($this->auth); $this->obj->bid->userAuthData(); $this->result = 'ok'; $conn->close(); }
function cse() { // Open the log file to which to write outputs $fp = fopen('test.log', 'at'); // Get all http headers in the received message $headers = getallheaders(); // Get the posted message body // NOTE: The message body is currently in Avro binary form $post_data = file_get_contents("php://input"); // Get the URI of the Avro schema on the OCL server that adheres to the /cse/offer/create contract $schema_uri = $headers['X-XC-SCHEMA-URI']; // Get the contents of the Avro schema identified by the URI retrieved above $content = file_get_contents($schema_uri); // Parse the CSE Avro schema and place results in an AvroSchema object $schema = AvroSchema::parse($content); //fwrite($fp, $schema); //fwrite($fp, "\n"); // Use Avro to decode and deserialize the binary-encoded message body. // The result is the plain text version of the message body // The message sender used Avro to binary-encode the text version of the message body before sending the message. // Create an AvroIODatumReader object for the supplied AvroSchema. // An AvroIODatumReader object handles schema-specific reading of data from the decoder and // ensures that each datum read is consistent with the reader's schema. $datum_reader = new AvroIODatumReader($schema); // Create an AvroStringIO object and assign it the encoded message body $read_io = new AvroStringIO($post_data); // Create an AvroIOBinaryDecoder object and assign it the $read_io object $decoder = new AvroIOBinaryDecoder($read_io); // Decode and deserialize the data using the CSE schema and the supplied decoder // The data is retrieved from the AvroStringIO object $read_io created above // Upon return, $message contains the plain text version of the X.commerce message sent by the publisher $message = $datum_reader->read($decoder); //fwrite($fp, $post_data); fwrite($fp, "\n"); //fwrite($fp, print_r($message, true)); fwrite($fp, print_r($headers, true)); // Connect to the Mongo server running on your machine // NOTE: you must start the Mongo server prior to running this web application $conn = new Mongo('localhost'); // Access the cse_data database // If this database does not exist, Mongo creates it $db = $conn->cse_data; // Access the google collection // If this collection does not exist, Mongo creates it $collection = $db->google; // Insert a new document into the google collection $item = $message["products"]; $collection->insert($item); // Write to log file fwrite($fp, print_r($item, true)); fwrite($fp, "Inserted document with ID: " . $item['_id']); fclose($fp); // Disconnect from the MongoDB server $conn->close(); }
/** * Closes the connection to the logging database */ public function close() { if ($this->closed != true) { $this->collection = null; if ($this->connection !== null) { $this->connection->close(); $this->connection = null; } $this->closed = true; } }
/** * modify the information of one student */ public static function modifyDataFrom($collection_name, $data, $id, $id_value) { try { $connection = new Mongo(); $db = $connection->selectDB('nhanviendb'); $collection = $db->{$collection_name}; $collection->update(array($id => $id_value), array('$set' => array("MaNV" => $data["MaNV"], "HoTen" => $data["HoTen"], "NgaySinh" => $data["NgaySinh"], "DiaChi" => $data["DiaChi"], "Phai" => $data["Phai"], "Luong" => $data["Luong"], "Phong" => $data["Phong"]))); $connection->close(); } catch (MongoConnectionException $e) { die('Error connecting to MongoDB server'); } catch (MongoException $e) { die('Error : ' . $e->getMessage()); } }
/** * Show the application welcome screen to the user. * * @return Response */ public function index() { try { $mongo = new Mongo(); //create a connection to MongoDB $databases = $mongo->listDBs(); //List all databases echo '<pre>'; print_r($databases); $mongo->close(); } catch (MongoConnectionException $e) { //handle connection error die($e->getMessage()); } return view('welcome'); }
/** * get table with condition * @param string $restaurant local restaurant or the other * @param string $areaID area * @param string $status table status * @param datetime $from php datetime, formatted with standard ("2010-01-15 00:00:00") * @param datetime $to php datetime, formatted with standard ("2010-01-15 00:00:00") * @return array table + info */ public function getTableWithCondition($restaurant = null, $areaID = null, $status = null, $from, $to) { try { // create connection $connection = new Mongo(TableDAO::Host); $db = $connection->selectDB(TableDAO::DbName); // step 1 : get tables which's booked between (from, to) $collectionName = "ChiTietDatCho"; $collection = $db->{$collectionName}; $condition = $this->createConditionToGetTable(null, null, null, $from, $to); $result = $collection->find($condition, array("MaBanAn" => 1, "_id" => 0)); $bookedTables = array(); foreach ($result as $idx => $document) { foreach ($document as $key => $value) { $bookedTables[$idx] = $value; } } // step 2 : get all tables $collectionName = "BanAn"; $collection = $db->{$collectionName}; $result = $collection->find(array(), array("MaBanAn" => 1, "_id" => 0)); $tables = array(); foreach ($result as $idx => $document) { foreach ($document as $key => $value) { $tables[$idx] = $value; } } // step 3 : except and get result $availTable = array_diff($tables, $bookedTables); // step 4 : get detail info of free-table $availTableDetails = array(); foreach ($availTable as $idx => $val) { $availTableDetails[] = $this->getTableInfo($val); } $connection->close(); return $availTableDetails; } catch (MongoConnectionException $e) { die('Error connecting to MongoDB server'); } catch (MongoException $e) { die('Error: ' . $e->getMessage()); } }
public function loadUser($model = 'users', $options = array()) { $_options = array('actions' => array('metodo' => array('type' => 'find', 'where' => array()))); $options = Set::merge($_options, $options); try { $conn = new Mongo('localhost'); $db = $conn->{$model}; $collection = $db->{$model}; foreach ($options['actions'] as $action) { $res[] = $collection->{$action['type']}($action['where']); } $conn->close(); return $res; //$this->U->remove(array('email'=>'{')); //prMongo($this->U->find()); } catch (MongoConnectionException $e) { die('Error connecting to MongoDB server'); } catch (MongoException $e) { die('Error: ' . $e->getMessage()); } }
$date = $_POST['date']; // convert from american format to data format $date1 = substr($date, 6, 4); $date2 = substr($date, 0, 2); $date3 = substr($date, 3, 2); $date = $date1 . $date2 . $date3; try { // open connection to LOCAL MongoDB server // $conn = new Mongo('localhost'); // open connection to CLOUD MongoDB server $conn = new Mongo("mongodb://*****:*****@dbh56.mongolab.com:27567/pianos"); // access database $db = $conn->pianos; // access collection $collection = $db->mile; // define a new document with safe insert $item = array('userid' => $userid, 'ldate' => $date, 'start' => $fstart, 'end' => $fend, 'tot' => $ftot, 'expl' => $fexpl); $options = array("safe" => True); // insert the new document $collection->insert($item, $options); // disconnect from server $conn->close(); header("location: mileage.php"); } catch (MongoConnectionException $e) { die('Error connecting to MongoDB server'); } catch (MongoException $e) { die('Error: ' . $e->getMessage()); } ?>
$data = $collection->find()->limit(10)->skip(5); foreach ($data as $key => $value) { // var_dump( $value ) ; } /* 排序条件查询sort() */ $data = $collection->find()->limit(10)->sort(array('_id' => -1)); // $data = $data->snapshot() ; # 排序和snapshot() 查询出对象不能使用foreach foreach ($data as $key => $value) { // var_dump( $value ) ; } /* 指定查询的列 fields() true 显示 false 不显示 */ $data = $collection->find()->limit(10)->fields(array('_id' => false)); // _id 列不显示 // $data = $collection->find()->limit(10)->sort(array('_id' => -1 ))->fields(array('username'=> true)) ; # 只显示username(_id默认显示) foreach ($data as $key => $value) { // var_dump( $value ) ; } /** * *** 7.索引操作 ensureIndex() ^.^ ---> * ensureIndex( array() , array( 'name' =>'索引名称' ,' background' = true , 'unique' = true)) * 详见:http://www.php.net/manual/en/mongocollection.ensureindex.php */ $collection->ensureIndex(array(‘age’ => 1, ’type’ => -1)); // 表示降序 -1表示升序 $collection->ensureIndex(array(‘age’ => 1, ’type’ => -1), array(‘background’ => true)); // 索引的创建放在后台运行(默认是同步运行) $collection->ensureIndex(array(‘age’ => 1, ’type’ => -1), array(‘unique’ => true)); // 该索引是唯一的 // *** 8.关闭连接 close() ^.^ ---> $connection->close();
/** @proxy */ public function close() { $this->initialize(); return $this->mongo->close(); }
/** * Method used to close de connection to the database * * @return boolean True on success, false otherwise * @access public */ public function close() { $this->_db = NULL; return $this->_conn->close(); }
// $cursor = $collection->find(); //foreach ($cursor as /*$obj*/$time => $id) { /* $time = $obj["date"]; if($time == $id) { $query = array("date" => $time); $cursor = $collection->find($query); $filter = array("date" => $id); $names = array("name" => $name); $emails = array("email" => $email); $titles = array("title" => $title); $bodys = array("blog" => $body); $collection->update($filter,$names,$titles, $bodys,false,false); } }*/ } $m->close(); ?> </div> <?php include "sidebar.php"; ?> </div> </body> </html>
function getParameter() { try { $path = __DIR__ . '/../app/config/parameters.ini'; $content = array('[parameters]'); $tmp = $_GET['server_host']; $imTmp = $_GET['im_host']; if (empty($tmp) || empty($imTmp)) { throw new Exception("服务器地址不能为空,请检查并重新填写"); } if (!empty($imTmp)) { if (strpos('http', $imTmp) === false) { $imTmp = 'http://' . $imTmp; } $urls = parse_url($imTmp); $content[] = 'ejabberd-server-http = "' . $urls['scheme'] . '://' . $urls['host'] . ':5280"'; $content[] = 'fafa_webim_url = "' . $tmp . '"'; $content[] = 'open_api_url = "' . $tmp . '"'; $content[] = 'FILE_WEBSERVER_URL = "' . $tmp . '/getfile/"'; $content[] = 'FAFA_REG_JID_URL = "' . ($urls['scheme'] . '://' . $urls['host']) . ':9527"'; $content[] = 'fafa_appcenter_url = "' . $tmp . '"'; } if (!empty($tmp = $_GET['mongodb_host'])) { $mongodb_auth = $_GET['mongodb_auth']; $mongodb_conn_str = ''; //测试数据库连接 //$conn=new Mongo(“xiaocai.loc:10086″); #连接指定端口远程主机 //$conn=new Mongo(“mongodb://sa:123@localhost”); #带用户名密码 if ($mongodb_auth === "1") { $mongodb_conn_str = 'mongodb://' . $_GET['mongodb_user'] . ':' . $_GET['mongodb_pwd'] . '@' . $tmp . ':' . $_GET['mongodb_port']; } else { $mongodb_conn_str = 'mongodb://' . $tmp . ':' . $_GET['mongodb_port']; } try { $conn = new Mongo($mongodb_conn_str, array('timeout' => 5000, 'connect' => true)); if (empty($conn)) { throw new Exception("Mongodb连接失败,请检查并重新配置"); } $mongodb_database = $_GET['mongodb_name']; if (empty($mongodb_database)) { throw new Exception("Mongo数据库未设置,请检查并重新配置"); } //创建数据库 $conn->selectDB($mongodb_database); $conn->close(); } catch (Exception $e) { if (isset($conn) && !empty($conn)) { $conn->close(); } throw new Exception("Mongo数据库连接失败:" . $e->getMessage()); } $content[] = 'mongodb_server = ' . $mongodb_conn_str; $content[] = 'mongodb_default_database = "' . $_GET['mongodb_name'] . '"'; $content[] = 'mongodb_username = "******"'; $content[] = 'mongodb_password = "******"'; } if (!empty($tmp = $_GET['db_host'])) { $port = $_GET['db_port']; $sns_db_user = $_GET['sns_db_user']; $sns_db_pwd = $_GET['sns_db_pwd']; $sns_db_dbname = $_GET['sns_db_dbname']; $im_db_user = $_GET['im_db_user']; $im_db_pwd = $_GET['im_db_pwd']; $im_db_dbname = $_GET['im_db_dbname']; $content[] = 'database_driver = "pdo_mysql"'; $content[] = 'database_host = "' . $tmp . '"'; $content[] = 'database_port = "' . $port . '"'; $content[] = 'database_name = "' . $sns_db_dbname . '"'; $content[] = 'database_user = "******"'; $content[] = 'database_password = "******"'; $content[] = 'database_driver_im = "pdo_mysql"'; $content[] = 'database_host_im = "' . $tmp . '"'; $content[] = 'database_port_im = "' . $port . '"'; $content[] = 'database_name_im = "' . $im_db_dbname . '"'; $content[] = 'database_user_im = "' . $im_db_user . '"'; $content[] = 'database_password_im = "' . $im_db_pwd . '"'; //测试数据库连接 $conn = mysql_connect($tmp . ':' . $port, $sns_db_user, $sns_db_pwd, true); if (!$conn) { throw new Exception("WEB接口服务数据库连接失败,请重新配置"); } mysql_select_db($sns_db_dbname, $conn); mysql_close($conn); $conn = mysql_connect($tmp . ':' . $port, $im_db_user, $im_db_pwd, true); if (!$conn) { throw new Exception("IM数据库连接失败,请重新配置"); } mysql_select_db($im_db_dbname, $conn); mysql_close($conn); } if (!empty($tmp = $_GET['mailer_transport'])) { $content[] = 'mailer_transport = "' . $tmp . '"'; $content[] = 'mailer_host = "' . $_GET['mailer_host'] . '"'; $content[] = 'mailer_user = "******"'; $content[] = 'mailer_password = "******"'; } $content[] = 'memcached_servers="[[\\"127.0.0.1\\",11211]]"'; $content[] = 'locale="zh"'; $content[] = 'SMS_ACT=""'; $content[] = 'SMS_PWD=""'; $content[] = 'deploy_mode="E"'; $content[] = 'ssoauthmodule="WefafaAuth"'; $content[] = 'ENO="100001"'; $content[] = 'edomain="' . $_GET['server_domain'] . '"'; $content[] = 'secret="335a052790228abbc6ea61b49ie9280adfaow808"'; if (file_exists($path)) { //先备份 @copy($path, $path . '_1'); } if (!($handle = fopen($path, 'w'))) { throw new Exception("配置文件[{$path}]打开失败,请检查文件是否有效!"); } if (!fwrite($handle, implode("\n", $content))) { throw new Exception("配置文件[{$path}]写入失败,请检查文件是否有效或权限是否正确!"); } fclose($handle); $dir = explode("web", __DIR__); //更改线程执行脚本 $str = "php {$dir[0]}app/threads \$1 \$2 \$3 \$4"; $command = $dir[0] . 'threads.sh'; if (!($handle = fopen($command, 'w+'))) { throw new Exception("脚本文件[{$command}]打开失败,请检查文件是否有效!"); } if (!fwrite($handle, $str)) { throw new Exception("脚本文件[{$command}]写入失败,请检查文件是否有效或权限是否正确!"); } fclose($handle); //发布配置 $str = "php {$dir[0]}app/console cache:clear --env=prod --no-debug\nchmod -R 777 {$dir[0]}app"; $command = $dir[0] . 'clear_cache_prod.sh'; if (!($handle = fopen($command, 'w+'))) { throw new Exception("脚本文件[{$command}]打开失败,请检查文件是否有效!"); } if (!fwrite($handle, $str)) { throw new Exception("脚本文件[{$command}]写入失败,请检查文件是否有效或权限是否正确!"); } fclose($handle); $data = shell_exec($command); if (strpos($data, 'Clearing the cache for the prod environment with debug false') === false) { throw new Exception($data); } $data = array("returncode" => "0000", 'data' => $data); } catch (Exception $e) { $data = array("returncode" => "9999", "msg" => $e->getMessage()); } echo json_encode($data); }
/** * Close the connection to Mongo * * @return boolean if the connection was successfully closed */ public function close() { if ($this->_connected) { $this->_connected = $this->_connection->close(); $this->_db = "{$this->_db}"; } return $this->_connected; }
/** * Executes the shutdown method. */ public function shutdown() { $this->handler->close(); }
/** * {@inheritdoc} */ public function closeConnection() { return $this->_connection->close(); }
function save_2_mongo($docs) { $len = count($docs) == 0 ? 0 : count($docs[0]); if (count($docs) == 0) { echo "Empty Array\n"; } else { if ($len != STANDARD_LEN) { echo "Element not enough\n"; } else { $docLen = count($docs); try { $mongo = new Mongo("192.168.0.159"); //create a connection to MongoDB $db = $mongo->mydb; //选择mydb数据库 $collection = $db->shuobo; //选择集合(选择’表’) $mongoDoc = array(); for ($i = 0; $i < $docLen; $i++) { $mongoDoc[] = $docs[$i]; if (($i + 1) % 50 == 0) { $ok = false; try { $ok = $collection->batchInsert($mongoDoc); } catch (Exception $e) { //var_dump($e); echo "batchInsert Error \n"; save("./non-utf-8.log", var_export($mongoDoc, true), "a+"); } if (!$ok) { echo "Mongodb Insert Error\n"; } $mongoDoc = array(); echo "."; } } if (count($mongoDoc) != 0) { $collection->batchInsert($mongoDoc); } $mongo->close(); echo "save to mongodb ... [{$docLen}]Done\n"; } catch (MongoConnectionException $e) { #die($e->getMessage()); echo $e; } } } }
/** * You should never call this function. * * The PHP driver will handle connections automatically, and will * keep this performant for you. */ public function close() { if (!empty($this->_mongo)) { $this->_mongo->close(); } }
/** * Close the connection */ public function close($ch = NULL) { $this->_connection->close(); }
<?php try { $mongo = new Mongo($server = 'mongodb://localhost:27017/', $options = array('timeout' => 100)); //create a connection to MongoDB $databases = $mongo->listDBs(); //List all databases; echo '<pre>'; print_r($databases); $mongo->close(); } catch (MongoConnectionException $e) { die($e->getMessage()); }
/** * modify the information of a document */ public static function modifyDataFrom($collection_name, $data, $id, $id_value) { try { $connection = new Mongo($this::Host); $db = $connection->selectDB($this::DbName); $collection = $db->{$collection_name}; $collection->update(array($id => $id_value), array('$set' => $data)); $connection->close(); } catch (MongoConnectionException $e) { die('Error connecting to MongoDB server'); } catch (MongoException $e) { die('Error : ' . $e->getMessage()); } }
public function login() { $this->token = $_REQUEST['token']; $url = "https://rpxnow.com/api/v2/auth_info?apiKey=" . $this->jan_api . "&token=" . $this->token . "&extended=false&tokenURL=http://localhost:80"; $infos_user = json_decode('[' . file_get_contents($url) . ']', true); if ($infos_user) { $u = $infos_user[0]; $data_user = $u['profile']; $_SESSION['email'] = @$u['profile']['email'] ? $u['profile']['email'] : $u['profile']['url']; $this->userAuthData(); if (!$this->auth) { $conn = new Mongo('localhost'); $db = $conn->users; $collection = $db->items; required('models', 'schemas'); $user_schema = Schemas::user(); $collection->insert(array_merge_recursive($user_schema, $data_user)); $this->auth = $collection->findOne(array('email' => $_SESSION['email'])); $conn->close(); } return true; } return false; }
function mongoExecute($config, $request) { $query = $request['mode'] . '->' . $request['route']; try { $m = new Mongo($config['server']); $db = $m->{$request}['route']->collection; $result = false; switch ($request['mode']) { case 'SELECT': try { if ($db->find()) { foreach ($db->find()->limit($request['limit'][1]) as $id => $record) { $id = (string) $record['_id']; unset($record['_id']); $result['records'][$id] = $record; } // print_r($result['records']); } else { $result['response']['error'] = 'Failed to get records from MongoDB'; } } catch (MongoException $e) { $result['response']['error'] = $e->getMessage(); return array('query' => $query, 'result' => $result); } break; case 'CREATE': if (!empty($request['items'])) { $counter = 0; foreach ($request['items'] as $item_id => $item) { try { $item['_id'] = new MongoId(); $id = (string) $item['_id']; if ($db->insert($item)) { $result['records'][$item_id]['_id'] = $id; $result['response'][$item_id]['created'] = 1; } else { $result['response'][$item_id]['error'] = 'Failed to create record in MongoDB'; } } catch (MongoException $e) { $result['response'][$item_id]['error'] = $e->getMessage(); return array('query' => $query, 'result' => $result); } $counter++; } } else { $query = null; $result = array('records' => array(0 => null), 'response' => array(0 => array('error' => 'ERROR - incorrect array supplied'))); } break; case 'DELETE': if (!empty($request['items'])) { $counter = 0; foreach ($request['items'] as $item_id => $item) { try { if ($db->remove($item)) { $result['records'][$item_id] = $item; $result['response'][$item_id]['deleted'] = 1; } else { $result['response'][$item_id]['error'] = 'Failed to delete record in MongoDB'; } } catch (MongoException $e) { $result['response'][$item_id]['error'] = $e->getMessage(); return array('query' => $query, 'result' => $result); } $counter++; } } else { $query = null; $result = array('records' => array(0 => null), 'response' => array(0 => array('error' => 'ERROR - incorrect array supplied'))); } break; } $m->close(); return array('query' => $query, 'result' => $result); } catch (MongoConnectionException $e) { // if there was an error, catch and display the problem here return array('query' => $query, 'result' => array('records' => array(0 => null), 'response' => array(0 => array('error' => 'ERROR: ' . $e->getMessage())))); } }