Drop mysql user using PHP - php

I'm trying to DROP database and its user using PHP.
Though I could able to DROP database but failed to DROP user.
Following command which I have tried,
$cpanel_user = 'abc';
$cpanel_user_password = 'xyz';
$conn = mysql_connect($dbhost = 'localhost', $cpanel_user , $cpanel_user_password );
$sql = 'DROP DATABASE dbname';
$retval = mysql_query( $sql, $conn ); // works perfect
$drop_user = "DROP USER 'username'#'localhost'";
$retval = mysql_query( $drop_user , $conn );
Unfortunately it showing "Access denied; you need (at least one of) the CREATE USER privilege(s) for this operation".
The user which is use for connection is cPanel user so must be having full privileges.
I refereed other threads like, MySQL: Check if the user exists and drop it but no luck.
Do I missing anything?

You should grant 'CREATE USER' Privileges to the user you used to connect to the database.
As your code, you should run this statement by the 'root' user:
GRANT CREATE USER ON *.* TO abc;

Related

MySQL copy table to different database with same credentials

I am using the standard MySQL functions that PHP has built in for copying one table to an new table.
This works perfect when the tables are in the same database. But I want to copy it to another databasename with same user and password.
Any suggestions how to achive this?
(Since $database can only contain 1 databasename)
Error shown is Table 'torzahttp_rsw.torzahttp_rsw.kwaliteit' doesn't exist
torzahttp_rswis the database name, and kwaliteit the table name.
Why is the databasename used twice?
// Create a new MySQL database connection
if (!$con = new mysqli('localhost', $username, $password, $database)) {
die('An error occurred while connecting to the MySQL server!<br><br>' . $con->connect_error);
}
// Create an array of MySQL queries to run
$sql = array(
'DROP TABLE IF EXISTS `backup_db.backup_table`;',
'CREATE TABLE `backup_db.backup_table` SELECT * FROM `live_db.live_table`'
);
// Run the MySQL queries
if (sizeof($sql) > 0) {
foreach ($sql as $query) {
if (!$con->query($query)) {
die('A MySQL error has occurred!<br><br>' . $con->error);
}
}
}
$con->close();
From the MySQL manual:
If any components of a multiple-part name require quoting, quote them individually rather than quoting the name as a whole. For example, write `my-table`.`my-column`, not `my-table.my-column`.
Your code:
$sql = array(
'DROP TABLE IF EXISTS `backup_db.backup_table`;',
'CREATE TABLE `backup_db.backup_table` SELECT * FROM `live_db.live_table`'
);
should look like this:
$sql = array(
'DROP TABLE IF EXISTS `backup_db`.`backup_table`;',
'CREATE TABLE `backup_db`.`backup_table` SELECT * FROM `live_db`.`live_table`'
);
Or, just drop the backticks altogether.
I have used this solution to create an mysql dump first and then processioning it.
//DB
$user = 'xxxxx';
$password = 'xxxxx';
$host = 'localhost';
$database_old = 'old_db';
$database_new = 'new_db';
$table = 'kwaliteit';
$file = 'kwaliteit.sql';
exec('mysqldump --user='.$user.' --password='.$password.' --host='.$host.' '.$database_old.' '.$table.' > uploads/'.$file);
exec('mysql --user='.$user.' --password='.$password.' --host='.$host.' '.$database_new.' < uploads/'.$file);
unlink('uploads/'.$file);

Cant connect to sql database using xampp as local server

I have a problem connecting to sql database:
<?php
$servername = "localhost";
$username = "";
$password = "";
$myDB = "udemy";
// Create connection
$link = mysqli_connect($servername, $username, $password, $myDB );
if (mysqli_connect_error()){
die ("There was an error connecting to the database");
}
$query = "SELECT * FROM users";
if (mysqli_query($link, $query)){
echo "Query was successfull"
}
?>
Error is showing when I try to connect database named "udemy"...
Set username and password or add a new user in your mysql server and try with those user details.
To create new user :-
To create user in MySQL/MariaDB 5.7.6 and higher, use CREATE USER syntax:
CREATE USER 'new_user'#'localhost' IDENTIFIED BY 'new_password';
then to grant all access to the database (e.g. my_db), use GRANT Syntax, e.g.
GRANT ALL ON my_db.* TO 'new_user'#'localhost';
Where ALL (priv_type) can be replaced with specific privilege such as
SELECT, INSERT, UPDATE, ALTER etc
Then to reload newly assigned permissions run:
FLUSH PRIVILEGES;
Now set newly created username and password in your code.
Hope it helped.

Query was empty with MySQL select Query

So I'm new to php and mysql and over the past few days have created a log in system using php and mysql. I am trying to make a function where a user can change their password with the following query:
$query2 = mysql_query("SELECT password FROM adminusr WHERE id =$idToChange");
$result = mysql_query($query2) or die($idToChange.mysql_error());
With SELECT statements you only select rows. To change them you need UPDATE. Consider using PDO because mysql_* functions are deprecated. Also try to hash your passwords and don't store them in plain text.
You need something like this:
$query2 = mysql_query("UPDATE adminusr SET password = '$new_password' WHERE id = '$idToChange'");
Using PDO
//Make the connection using PDO
try {
$conn = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
echo "PDO connection object created";
}
catch(PDOException $e) {
echo $e->getMessage();
}
//Make your query
$sql = 'UPDATE adminusr SET password = :new_password WHERE id = :id';
$stmt = $conn->prepare($sql);
$stmt->execute(array(':new_password'=>$new_password, ':id'=>$idToChange));
EDIT answering to comment
Then you need to have also username and password fields at your form. So, you need four fields: username, oldPassword, newPassword, confirmNewPassword. Before the update statement you need to select the user having credentials username, oldPassword. If you find only one then you have to check if newPassword and confirmNewPassword match. If match then proceed to update. Otherwise print some error message.

How to create mysql user and database using php script?

I want to Create mysql user and database using php script
how to create mysql user using mysql_query()
<?php
mysql_query("CREATE USER 'demodemodemo'#'localhost' IDENTIFIED BY 'jayul321';");
?>
this is not working..
PHP script to create MySQL database, add user and grant privileges.
## make sure you connect first to mysql with a super user (ex: root)
mysql_connect('localhost', 'root', 'password');
$dbName = 'database_name'; // new database name
$dbUser = 'db_user'; // new user name
$dbPass = 'db_pass'; // new user password
$queries = array(
"CREATE DATABASE `$dbName` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci",
"CREATE USER '$dbUser'#'localhost' IDENTIFIED BY '$dbPass'",
"GRANT USAGE ON * . * TO '$dbUser'#'localhost' IDENTIFIED BY '$dbPass' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0",
"GRANT SELECT , INSERT , UPDATE, DELETE ON `$dbName` . * TO '$dbUser'#'localhost'",
"FLUSH PRIVILEGES"
);
foreach($queries as $query) {
echo 'Executing query: "'.htmlentities($query).'" ... ';
$rs = mysql_query($query);
echo ($rs ? 'OK' : 'FAIL') . '<br/><br/>';
}

No Database Selected - PHP & MySQL

I am trying to connect to my database and when I run the code, I get an error. Can anybody tell me what is wrong also any errors in my PHP code? Thanks.
Error: No database selected
PHP Code:
include('.conf.php');
$prof = $_GET['profile'];
$prof = addslashes(htmlentities($prof));
$query = "SELECT * FROM aTable where id = '".mysql_real_escape_string($prof)."'";
$info_array = mysql_query($query, $con) or die (mysql_error()).;
while($row = mysql_fetch_array( $info_array ))
{
echo $row['num1'];
echo "</br>";
echo $row['num2'];
echo "</br>";
echo $row['num3'];
echo "</br>";
echo $row['num4'];
};
mysql_close($con);
.conf.php file:
<?php
$conf['db_hostname'] = "xxx";
$conf['db_username'] = "xxx";
$conf['db_password'] = "xxx";
$conf['db_name'] = "xxx";
$conf['db_type'] = "mysql";
$con = mysql_connect('xxx', 'xxx', 'xxx') or die (mysql_error());
$db = mysql_select_db("aTable", $con);
?>
I had that problem and solved it with prefixing the table name with the database name, so
select * from database.table
Unless you have the password incorrect and need to fix it, run a GRANT statement to grant access to your database user:
GRANT ALL PRIVILEGES ON aTable.* TO xxx#localhost IDENTIFIED BY 'password_for_xxx';
The above grants all privileges. It's often better to restrict to only what's needed. For example, if you only intend to SELECT, but not modify data,
GRANT SELECT ON aTable.* TO xxx#localhost IDENTIFIED BY 'password_for_xxx';
Update
Since you have identified the database name as dedbmysql, change your mysql_select_db() call to:
$db = mysql_select_db("dedbmysql", $con);
Following this, the GRANT statements above are probably unnecessary, as your host may have already worked out the correct database permissions.

Categories