Mongodb PHP driver: how to create database and add user to it? - php

so using the mongodb shell, I was able to create a database and add a username and password to it. How can I do the same in php? I have everything installed and able to connect to mongodb server.
However, I can't find any information in the doc.

I do not believe addUser() is implemented in the PHP driver.
However, there is an execute that should allow you to do an addUser() the same way you would from the mongo shell:
EDIT: After testing, I couldn't get execute to do what you wanted, but I did find that the following works:
<?php
// open connection
$mongo = new Mongo("mongodb://" . MONGO_USER . ":" . MONGO_PASS . "#" . MONGO_HOST, array("persist" => "abcd1234"));
$db = $mongo->selectDB("admin");
// user info to add
$username = "testUser";
$password = "testPassword";
// insert the user - note that the password gets hashed as 'username:mongo:password'
// set readOnly to true if user should not have insert/delete privs
$collection = $db->selectCollection("system.users");
$collection->insert(array('user' => $username, 'pwd' => md5($username . ":mongo:" . $password), 'readOnly' => false));
?>
That adds a new user to the admin db on my server - checked via mongo shell after executing PHP script.
That said - why do you want to add a Mongo user from a PHP script?

A way to create a new mongodb user from PHP is via MongoDB::command:
//info to add
$db_name = 'db_name';
$db_user = 'new_user';
$db_pass = 'new_pass';
//autenticate with a user who can create other users
$mongo = new MongoClient("mongodb://root:root#localhost/admin");
$db = $mongo->selectDB( $db_name );
//command to create a new user
$command = array
(
"createUser" => $db_user,
"pwd" => $db_pass,
"roles" => array
(
array("role" => "readWrite", "db" => $db_name)
)
);
//call MongoDB::command to create user in 'db_name' database
$db->command( $command );
Tested with mongo 3.0 and PHP mongo driver 1.6

Related

Moodle database connection failed in local

I'm trying to install an existing Moodle app in local to develop a child theme, but it appears the following message after configuring config.php. I'm not able to be aware of the error. That's my file:
<?php
unset($CFG); // Ignore this line
global $CFG; // This is necessary here for PHPUnit execution
$CFG = new stdClass();
$CFG->dbtype = 'mysqli'; // 'mysqli', 'mariadb', 'mysqli', 'mssql', 'sqlsrv' or 'oci'
$CFG->dblibrary = 'native'; // 'native' only at the moment
$CFG->dbhost = 'localhost'; // eg 'localhost' or 'db.isp.com' or IP
$CFG->dbname = '(name)'; // database name, eg moodle
$CFG->dbuser = '(same as above)'; // your database username
$CFG->dbpass = '(pass)'; // your database password
$CFG->prefix = 'pztp_'; // prefix to use for all table names
$CFG->dboptions = array(
'dbpersist' => false, // should persistent database connections be
// used? set to 'false' for the most stable
// setting, 'true' can improve performance
// sometimes
'dbsocket' => false, // should connection via UNIX socket be used?
// if you set it to 'true' or custom path
// here set dbhost to 'localhost',
// (please note mysql is always using socket
// if dbhost is 'localhost' - if you need
// local port connection use '127.0.0.1')
'dbport' => '3306', // the TCP port number to use when connecting
// to the server. keep empty string for the
// default port
);
$CFG->wwwroot = 'http://'.$_SERVER['SERVER_NAME'];
$CFG->dataroot = 'C:/wamp64/www/example/data';
$CFG->directorypermissions = 02777;
$CFG->admin = 'admin';
require_once(dirname(__FILE__) . '/lib/setup.php'); // Do not edit
dbname, dbuser and dbpass are censored due to privacy politics, as well as application name, but two first are the same value and the name of the "root" folder (named example) is given in dataroot path. I've created that user and DB in the DBMS, I've assigned all the privileges to the user for that DB and I've imported the DB. I use PHP 7.0.33 (that can't be updated) due to the Moodle version. I've tried using XAMPP and WAMP with the same result.
Thank you all in advance!
Maybe try creating a test PHP file - in the Moodle root folder - to test the connection to see if its Moodle or the database.
<?php
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname, $dbport);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
echo 'Success... ' . $mysqli->host_info . "\n";
$mysqli->close();

how can I drop user from "system.users" using mongodb and PHP?

I need a small help.
I can not delete "System.User" user from MongoDB database.
/*Remove Tenent DB*/
function RemoveTenentDB($mydb){
error_reporting(0);
$connection_string = Config::get('database.creator-tenant-uri');
$m = new MongoClient($connection_string); //create interface to mongo
$command = array
(
"dropUser" => $mydb
);
$db = $m->selectDB( $mydb );
$db->command( $command );
#drop databse
$db = $m->dropDB( $mydb );
return true;
}
Below code delete just database and particular database user only not "System.User"
$command = array
(
"dropUser" => $mydb
);
$db = $m->selectDB( $mydb );
$db->command( $command );
$db = $m->dropDB( $mydb );
The following db.dropUser() operation drops the reportUser1 user on the products database.
use products
db.dropUser("reportUser1", {w: "majority", wtimeout: 5000})
reference : db.dropUser
Try following code for php
$users = $conn->$db_name->selectCollection('system.users')->delete();
If I understand it right, you are looking for deleting one collection in mongodb database using PHP.
If that is the case then, you can use the below method to drop a collection from mongodb.
$collection = $mongo->my_db->System.User;
$response = $collection->drop();
You can follow the below link to get more details about the same -
https://www.php.net/manual/en/mongocollection.drop.php

php how to generate dynamic database connection in for loop in mysql

i am new to working in php, i am work on how to alter table dynamically in database through coding in php
database like this,
database name : data_switch
table name - data
did dataname host dbuser dbpwd dbname
1 abc local root root abc_db // here dataname create new database, when register new dataname
2 pqr ubuntu root passwd pqr_db
php code below:
<?php
$dsn = "localhost";
$username = "root";
$password = "passwd";
$db = new PDO("mysql:host=$dsn;dbname=data_switch", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
foreach ($db->query("select * from data") as $row)
{
$dataname = $row['dataname'];
$host = $row['host'];
$dbuser = $row['dbuser'];
$dbpwd = $row['dbpwd'];
$dbname = $row['dbname'];
$connection_array['data1'][] = array(
'dataname' => $dataname,
'host' => $host,
'dbuser' => $dbuser,
'dbpwd' => $dbpwd,
'dbname' => $dbname
);
}
echo "<pre>";
print_r($connection_array);
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $dbuser, $dbpwd);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// here all dataname find but i dont know how to generate dataname's own connection. dynamically
?>
i am getting all dataname in loop but i am not able to dynamically diffrent connection,i am register new dataname in form as like abc then it create a new database dynamically, but when i am alter the table i am not getting how to connection dynamically on each dataname's host,dbname,dbpwd through each own dataname.
Any body having any idea please help to sort it out. Thanks
I know it's an old post but it came up in a search as a possible relation to a question I had.
I have a script doing very similar to what is being asked. You need to place your connections in a dynamic variable.
eg.
I have a list of branches and their respective database connection details in an array called $branchDcom. I can make calls to all my branches without closing connections and opening all the time.
I have a connection function that connects to a database with the sent values in the function conn_dcom_branch('your_server', 'your_db', 'your_username', 'your_password')
The following creates connections to all databases.
$connection = array();
foreach ($branchDcom as $key => $value) {
$branch = $value['Name'];
if (!is_resource($connections[$branch]['conn'])) {
${'connection_'.$branch} = conn_dcom_branch($value['server'], $value['db'], $value['username'], $value['password']);
${'connection_'.$branch.'_db'} = $value['db'];
}
}
This gives me an array of all branch connections and their respective database names.
To use just enter in the branch name and it will use that connection:
$branch = 'select_name';
$query = "
SELECT
your_field
FROM
[".${'connection_'.$branch.'_db'}."].['table_name']
";
$rs = ${'connection_'.$branch}->execute($query);
This may help someone

Create mysql DB with PHP through cPanel and import *.sql file

I want to create a DB for each user who wants to register to my Web-app. When i try this local everything perfectly works. A User can register with his email and pw. A DB is created and a import.sql file is imported so that the DB created for the User is empty on data but the tables and realtioships are given.
My Host uses cPanel and phpMyAdmin to create DB and db-user. I want to do this with php like i do it local. Does anyone have an idea how i get this done?
I've already searched and tryed stuff out but nothing works for me.
If possible some explanations on cPanel maybe would be enough.
<?php
require("xmlapi.php"); // this can be downlaoded from https://github.com/CpanelInc/xmlapi-php/blob/master/xmlapi.php
$xmlapi = new xmlapi("cpanlel host name");
$xmlapi->set_port( 2083 );
$xmlapi->password_auth('cpanel username','cpanel passsword');
$xmlapi->set_debug(0);//output actions in the error log 1 for true and 0 false
$cpaneluser='cpanel username';
$databasename="something";
$databaseuser="database username";
$databasepass= 'database password';
//create database
$createdb = $xmlapi->api1_query($cpaneluser, "Mysql", "adddb", array($databasename));
//create user
$usr = $xmlapi->api1_query($cpaneluser, "Mysql", "adduser", array($databaseuser, $databasepass));
//add user
$addusr = $xmlapi->api1_query($cpaneluser, 'Mysql', 'adduserdb', array('' . $databasename . '', '' . $databaseuser . '', 'all'));
?>
Using the above code you will be able to create new database, add new user to database and give all access to user on database.

How to restore a mysql database in php

I am trying to restore a mysql database using php. I googled and found out this piece of code :-
<?php
$restore_file = "backup.bkp";
$server_name = "localhost";
$username = "root";
$password = "pass";
$database_name = "db";
$cmd = "mysql -h {$server_name} -u {$username} -p{$password} {$database_name}
< $restore_file";
exec($cmd);
?>
I am using a shared server (linux) and the file was restored using phpmyadmin successfully. But I want to use php to restore. The code does not work. Where am I being wrong?
Thanks to #Scoopy, I found that exec() was disabled my by hosting provider. However, I have solved my problem using the following code I found here :-
$db = mysql_connect ( 'localhost', 'username', 'pass' ) or die('not connected');
mysql_select_db( 'test', $db) or die('Not found');
$fp = fopen ( 'backup-file', 'r' );
$fetchData = fread ( $fp, filesize ( 'backup-file') );
$sqlInfo = explode ( ";\n", $fetchData); // explode dump sql as a array data
foreach ($sqlInfo AS $sqlData )
{
mysql_query ( $sqlData ) or die('Query not executed');
}
BUT, THE CODE IS DEPRECATED. So, I made up this code :-
$host = 'localhost';
$user = 'root';
$password = 'root';
$database = 'test';
$conn = new mysqli($host, $user, $password, $database);
$conn->autocommit(FALSE);
$fp = fopen('bkp-file', 'r');
$fetchData = fread($fp, filesize('bkp-file'));
$sqlInfo = explode(";\n", $fetchData); // explode dump sql as a array data
foreach ($sqlInfo AS $sqlData) {
$conn->query($sqlData);
}
$conn->commit();
$conn->close();
This code is perfect to use. It uses transactions to prevent multiple writes.
Generally a shared hosting server will disable access to system functions as it introduces a security risk for them. You can confirm this if your server provider allows you to use the phpinfo command (docs).
Create a page that dumps the PHP info and then look on that page for a setting called disable_functions - it's under the "Core" section. If exec appears there then you will know that exec is a disabled function and you will not be able to use it. Unfortunately one of the drawbacks of using some shared hosting services as it is impossible/very difficult to implement the sorts of things you are talking about.
I don't see why you need PHP, you can do this directly in the terminal.
Backup
mysqldump -u root -p db> backup.bkp
Restore
mysql -u root -p db < backup.bkp

Categories