how can I drop user from "system.users" using mongodb and PHP? - 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

Related

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

MySQL wont connect

Im having trouble with MySQLi.
Every time I run this code it returns an error on line 13(mysql_select_bd()).
I cant figure out where the problem is.
Code:
<?php
$conn_error = 'Could not connect';
$mysqli_host = 'localhost';
$mysqli_user = 'root';
$mysqli_password = '';
$mysql_db = 'a_database';
#$mysqli_conn = mysqli_connect($mysqli_host, $mysqli_user, $mysqli_password);
mysqli_select_db('a_database', $mysqli_conn);
?>
You have an incorrect usage of the function:
mysqli_select_db('a_database', $mysqli_conn);
The connection must come first before the database name in the arguments:
mysqli_select_db($mysqli_conn, 'a_database');
// ^ connection object, then database name
Alternatively, you could also do this:
$mysqli_conn = mysqli_connect($mysqli_host, $mysqli_user, $mysqli_password, $mysql_db);
Or the object oriented interface:
$mysqli_conn = new mysqli($mysqli_host, $mysqli_user, $mysqli_password, $mysql_db); // personal preference
Instead of doing that you can do something like this:
$conn = mysqli_connect('localhost', 'root', '', 'a_database');

PHP / MySQL - Create Table If Not Exist

I have 2 db connections, db1 is the main db and db2 is the copy from.
my script is copying from db2 (has this was the development) to make db1 the same.
However i cannot get the create table if not exist to work with using more then 1 database and using "LIKE".
This is the connection:
<?php
$host = 'localhost';
$db1 = "***";
$username_db1 = '***';
$password_db1 = '***';
$db_c1 = mysql_connect($host, $username_db1, $password_db1) or die('Error connecting to Database!<br>'.mysql_error());
$db2 = "***";
$username_db2 = '***';
$password_db2 = '***';
$db_c2 = mysql_connect($host, $username_db2, $password_db2, true) or die('Error connecting to Database!<br>'.mysql_error());
mysql_select_db($db1, $db_c1);
mysql_select_db($db2, $db_c2);
?>
This is the script well part of it.
$tables1 = array();
$tables2 = array();
$res = mysql_list_tables($db1, $db_c1);
while (list($tmp) = mysql_fetch_row($res))
{
$tables1[] = $tmp;
}
$res = mysql_list_tables($db2, $db_c2);
while (list($tmp) = mysql_fetch_row($res))
{
$tables2[] = $tmp;
}
// Tables creates if not exists
foreach($tables2 as $k=>$v)
{
mysql_query("CREATE TABLE IF NOT EXISTS ".$db1.".".$v." LIKE ".$db2.".".$v, $db_c1);
}
I think the problem is with the LIKE i dont think it is reading it correctly, i have var dumped $tables2 and it does come up with the results.
Thanks
try it in mysql first. drop the table 2 then try your query before doing it dynamically. then one by one change your query to variables. i cant read much from the code but that would be my approach

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

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

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result [duplicate]

This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 11 months ago.
I get the error when trying to run this:
<?php
require_once('includes/DbConnector.php');
$connector = new DbConnector();
$result = $connector->query('SELECT title,content FROM staff_vacancies ORDER BY ordering LIMIT 0,100');
// Get an array containing the results.
// Loop for each item in that array
while ($row = $connector->fetchArray($result)){
echo $row['title'].'</h3>';
echo $row['content'];
}
?>
I have a linked file: DbConnector.php:
<?php
////////////////////////////////////////////////////////////////////////////////////////
// Class: DbConnector
// Purpose: Connect to a database, MySQL version
///////////////////////////////////////////////////////////////////////////////////////
require_once 'SystemComponent.php';
class DbConnector extends SystemComponent {
var $theQuery;
var $link;
//*** Function: DbConnector, Purpose: Connect to the database ***
function DbConnector(){
// Load settings from parent class
$settings = SystemComponent::getSettings();
// Get the main settings from the array we just loaded
$host = $settings['dbhost'];
$db = $settings['dbname'];
$user = $settings['dbusername'];
$pass = $settings['dbpassword'];
//the settings
$host = 'localhost';
$db = 'xxx';
$user = 'xxx';
$pass = 'xxx';
// Connect to the database
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
}
//*** Function: query, Purpose: Execute a database query ***
function query($query) {
$this->theQuery = $query;
return mysql_query($query, $this->link);
}
//*** Function: getQuery, Purpose: Returns the last database query, for debugging ***
function getQuery() {
return $this->theQuery;
}
//*** Function: getNumRows, Purpose: Return row count, MySQL version ***
function getNumRows($result) {
return mysql_num_rows($result);
}
//*** Function: fetchArray, Purpose: Get array of query results ***
function fetchArray($result) {
return mysql_fetch_array($result);
}
//*** Function: close, Purpose: Close the connection ***
function close() {
mysql_close($this->link);
}
}
?>
Does anyone know what the problem is?
Your query must have a problem which is causing $result to be an invalid resource.
Try checking for mysql_error() after the line on which you run your query.
Edit:
In fact, I would alter your DBConnector class function query() to something like the following, so that an identifiable error is thrown when you have a bad query:
function query($query) {
$this->theQuery = $query;
$queryId = mysql_query($query,$this->link);
if (! $queryId) {
throw new Exception(mysql_error().". Query was:\n\n".$query."\n\nError number: ".mysql_errno();
}
return $queryId;
}
I find this in a post, to me solved my problem.
Slds.
Yeah, Answer is simple, the query used is not a true result as it's a query inside of a getrow so to speak..
Here is the fix:
Find all lines that look like this:
mysql_fetch_array(mysql_query("...snip...";-) );
And just add a "#" in front of it so it looks like this:
#mysql_fetch_array(mysql_query("...snip...";-) );
Then do the same thing for the following lines..
Code:
mysql_num_rows(mysql_query("...snip...";-) );
Perform the same steps as above by adding the "#" to it so it looks like this:
#mysql_num_rows(mysql_query("...snip...";-) );
All this does it say "While doing xxx within yyy" Otherwise, it's dead due to missing result value. It's a PHP thing..
Works like a charm, took me 5 mins to rip the whole code apart and slap it all into Modernbill, Shares the same database and works perfectly for me.
This error means your query failed. mysql_query() returns false if an error occurred, you are then passing false to mysql_fetch_array() which is triggering the error message.
Your query could be failing due to a missing/wrong table or field. To see the detailed error, print out the result of mysql_error().
The mysql_* library is deprecated. It is recommended to upgrade to MySQLi or PDO.
// Load settings from parent class
$settings = SystemComponent::getSettings();
// Get the main settings from the array we just loaded
$host = $settings['dbhost'];
$db = $settings['dbname'];
$user = $settings['dbusername'];
$pass = $settings['dbpassword'];
//the settings
$host = 'localhost';
$db = 'xxx';
$user = 'xxx';
$pass = 'xxx';
Did you mean to reassign the connection vars? OR was that a few lines of stub code you forgot to take out? Or just an example to show what $settings contains?
Please provide the error from mysql_error(). Without that I can only guess... try escaping your field names?
$result = $connector->query('SELECT `title`,`content` FROM `staff_vacancies` ORDER BY `ordering` LIMIT 0,100');
Your query must have a problem which is causing $result to be an invalid resource.
Use this
<?php
require_once('includes/DbConnector.php');
$connector = new DbConnector();
$result = $connector->query('SELECT title,content FROM staff_vacancies ORDER BY ordering LIMIT 0,100');
// Get an array containing the results.
// Loop for each item in that array
if($result){
while ($row = $connector->fetchArray($result)){
echo $row['title'].'</h3>';
echo $row['content'];
}
}
?>

Categories