SQL query "GRANT ALL PRIVILEGES ON name_$DBname.* TO 'name_$DBname'#'localhost'"
Output for this:
Access denied for user 'name'#'localhost' to database 'name_posmechanics'
when written like below - it outputs the variable correctly but..
SQL query "GRANT ALL PRIVILEGES ON name_$DBname.* TO '. 'name_$DBname'#'localhost'. "
error for syntax
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'name_posmechanics'#'localhost'.' at line 1
It shows that when written the way it wants to be, it will ignore my variable, but it did show correctly 'name_posmechanics'#'localhost' when the syntax error is present and shows 'name'#'localhost' whith no syntax errors? why would the variable work referring to the db name but not when refering to the User
I understand there is a issue with permissions at the moment, however I would like to get the syntax error corrected first and then move on the the next issue.
here is the complete code
add_action( 'plugins_loaded', array( 'pos_URL__db', 'init' )); //This will trigger everytime the page is refreshed but only apply if all conditions are met
class pos_URL__db {
public static function init() {
$POS__sys_db = __CLASS__;
new $POS__sys_db;
}
public function __construct()
{
add_action('init', array($this, 'pos__URL_DB'));
}
public function pos__URL_DB()
{
//--------to access the order objects----start-----
$orders = wc_get_orders(array(
'customer_id' => get_current_user_id(),
'return' => 'ids',
));
//add the id of the custom meta field that lies in the order
$meta_data = array();
foreach ($orders as $order_id) {
$meta_data[$order_id] = get_post_meta($order_id, '_engx_text_field_id', true); //get the field value entered by the vendor on checkout
}
//--------to access the order objects-----end-----
if( isset($meta_data[$order_id]) ) { //is the custom field set
//dependencies
$servername = "localhost"; // always the same "localhost"
//$username = $meta_data[$order_id]; //get name of field unique to each user saved from checkout process
$username = "name"; //get name of field unique to each user saved from checkout process
//$password = "testing22"; //passcode for database
$password = 'TestIngTT'; //passcode for database
$DBname = $meta_data[$order_id]; //get name of field unique to each user saved from checkout process
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//mysql_connect('localhost','user',password);
//mysql_query("CREATE USER 'username'#'localhost' IDENTIFIED BY 'password';");
//mysql_query("GRANT ALL ON db1.* TO 'username'#'localhost'");
// Create User
//$sql = "CREATE DATABASE . $DBname . "; //Name of NEW Database replace "myDB" with the POS-URL custom field meta value from checkout
//$sql = "CREATE DATABASE testDB"; //Name of NEW Database replace "myDB" with the POS-URL custom field meta value from checkout
$sqlcommands = array(
"CREATE DATABASE name_$DBname",
"CREATE USER 'name_$DBname'#'localhost' IDENTIFIED BY 'TestIngTT!'",
//"GRANT ALL PRIVILEGES ON * . * TO name_$DBname",
"GRANT ALL PRIVILEGES ON name_$DBname.* TO 'garagepo_$DBname'#'localhost'",
//"GRANT ALL ON db1.* TO 'username'#'localhost'"
);
foreach ($sqlcommands as $sql)
{
// Create database
if (mysqli_query($conn, $sql)) {
echo "Database created successfully"; //comment when not needed
} else {
echo "Error creating database: " . mysqli_error($conn); //comment when not needed
}
}
mysqli_close($conn);
}
}//end pos__URL_DB
}//end Class pos_URL__db
Related
I have a PHP site that I uploaded in 000webhost. It needs a database to store data. But when I try to sign in it didn't sign in. When I check the connection it turns out the connection was fine. Still not able to access the database. So I wrote a small script to check database access and it failed. I have a table named songs which contains some songs.
Here is the script :
<?php
ob_start();
session_start();
$host = 'localhost';
$user = 'xxxxxxx';
$pass = 'xxxxxxx';
$db = 'xxxxxxx';
$timezone = date_default_timezone_set("Asia/Kolkata");
$con = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
if($con)
{
echo "Connection success";
$query = mysqli_query($con, "SELECT * FROM songs");
if($query){
$tb = mysqli_fetch_array($query);
print_r($tb);
}
else {
echo " failed db access";
}
}
else {
echo " connection failed";
}
?>
The details have been kept hidden for security reasons.
The above script gives the following output:
Connection success failed db access
It doesn't work, because you're using PDO for connection and mysqli to query. Change your connection to mysqli
$con = new mysqli($servername, $username, $password, $dbname);
or change your query to PDO
$query = $con->query("SELECT * FROM songs");
The output you are showing is misleading, failed db access. As per below code, database was connected successfully and you were executing query, which didn't executed it seems and flow going to else block.
if($query){
// your code
}
else {
echo " failed db access";
}
You need to check,
If you are using same user credentials and has access to the table.
If same table exists
If you have provided correct database details where you have created tables.
==Updated==
As I mentioned earlier, user might not have sufficient privilege to access songs table. To GRANT access, you need to execute following SQL
GRANT ALL PRIVILEGES ON *.* TO '<username>'#'localhost; WITH GRANT OPTION;
This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I have a users table and I want to be able to delete a user when a link is clicked. $user_name is set in a session. Here is the link:
<?php echo "Delete Account" ?>
Here is the code on delete_user.php:
<?php
session_start();
session_destroy();
require "connection.php";
?>
<?php
if($_GET['id'] != ""){
$user_name = $_GET['id'];
$sql = "DELETE FROM users WHERE user_name='{$user_name}'";
$result = mysqli_query($connection, $sql);
header('Location: register.php');
}
?>
<?php include "footer.php";?>
I don't understand why it's not deleting the user from the database when this code is executed?
There's no clear reason as to why your code is not working. However, you mentioned being new to PHP, so picking up good practices with your code could (1) help solve the issue at hand, (2) make your code more efficient, and easier to debug.
I recommend you use mysqli in the object-oriented manner, it requires less code, and usually easier to follow.
Making the connection is simple:
<?php
$host = 'localhost';
$user = 'USERNAME';
$pass = 'PASS';
$data = 'DATABASE';
$mysqli = new mysqli($host, $user, $pass, $data);
// catch errors for help in troubleshooting
if ($mysqli->errno)
{
echo 'Error: ' . $mysqli->connect_error;
exit;
}
?>
Creating a safe environment for your server keep in mind these things:
Do not trust user input (ever!)
Do not perform direct queries into your database.
When developing, break your code into steps so you can easily troubleshoot each part.
With those three simple things in mind, create a delete file.
<?php
if (isset($_GET['id'])
{
// never trust any user input
$id = urlencode($_GET['id']);
$table = 'users';
// set a LIMIT of 1 record for the query
$sql = "DELETE FROM " . $table . " WHERE user_name = ? LIMIT 1";
// to run your code create a prepared statement
if ($stmt = $mysqli->prepare( $sql ))
{
// create the bind param
$stmt->bind_param('s', $id);
$stmt->execute();
$message = array(
'is_error' => 'success',
'message' => 'Success: ' . $stmt->affected_rows . ' were updated.'
);
$stmt->close();
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'Error: There was a problem with your query'
);
}
}
else
{
echo 'No user id is set...';
}
The code will help you set the query, and delete the user based on their user_name... Which I am not sure that is the best solution, unless user_name is set to be an unique field on your MySQL database.
Firstly this is a horrible way to do this, you are prone to SQL Injections and also using GET literally just tags the query to the end of the URL which is easily obtainable by a potential hacker or ANY user as a matter of fact. Use POST instead with a bit of jQuery magic, I would also recommend using Ajax so that you don't get redirected to php file and it will just run. As it is not anyone can access that URL and delete users so I recommend using PHP SESSIONS so that only people from your site can delete users. Also simply passing the id to the PHP file is very insecure as ANYONE could simply create a link to your php file on their site and delete users.
Therefore try this to fix your code (with added security):
PLEASE NOTE: I am aware that this may not be the best way nor the worst but it is a fairly secure method that works well.
Your main page, index.php:
<?php
session_start();
// Create a new random CSRF token.
if (! isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
// Check a POST is valid.
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
// POST data is valid.
}
?>
...
<form id="delete_user_form" action="delete_user.php" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_name; ?>" />
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" />
<input type="submit" value="Delete User" />
</form>
In your .js file (make sure you have jQuery linked):
window.csrf = { csrf_token: $("input[name= csrf_token]").val() };
$.ajaxSetup({
data: window.csrf
});
$("#delete_user_form").submit(function(event) {
event.preventDefault(); //Stops the form from submitting
// CSRF token is now automatically merged in AJAX request data.
$.post('delete_user.php', { user_id: $("input[name=user_id]").val() }, function(data) {
//When it it's complete this is run
console.log(data); //With this you can create a success or error message element
});
});
Now for your delete_user.php file, this should fix the errors:
<?php
session_start();
require "connection.php";
// Checks if csrf_token is valid
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
if(isset($_POST['user_id']) && $_POST['user_id'] != ""){
$user_name = $_POST['user_id'];
$sql = "DELETE FROM users WHERE user_name = '$user_name' LIMIT 1"; //LIMIT 1 only allows 1 record to be deleted
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully"; //You get this in your javascript output data variable
} else {
echo "Error deleting record: " . $conn->error; //You get this in your javascript output data variable
}
$conn->close();
}
}
?>
I don't know what your connection.php contains so this is what I'd put in it:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
In the code below there are 2 mysql connections, the issue is that the second connection gives a connection error if the password coming in from the form is anything but 123456.
Now, password coming in from the form should have nothing to do with the second connection because that password in for the new database that is made before the second conenction starts. The second connection is connecting to another database all together.
However, if i use the commented out $grantQ query, the second connection works fine. That means that the issue is got something to do with identified by '{$pass}' in the $grantQ query.
The identified by '{$pass}' query should only affect the new database that has been created. Why is it affecting the existing db that the second connection is connecting to?
please help .. sorry about the long summary !
<?php
if(isset($_POST['submit'])){
// SUPER CONNECTION
$maindb_db = "little_maindb";
$maindb_server = "localhost";
$maindb_username = "admin#littlesidegym.com";
$maindb_password = "123456";//
$conn = new mysqli($maindb_server, $maindb_username, $maindb_password, $maindb_db);
if ($conn->connect_error) {
die($contact_cus_supp);
}
//NAME OF DB FROM POST - CUSTOMER VIEW
$new_dbname = mysqli_real_escape_string($conn, $_POST['db_name']);
$new_pass = mysqli_real_escape_string($conn, $_POST['pass']);
// CREATING DATABASE
$sql = "CREATE DATABASE IF NOT EXISTS $new_dbname ";
if (!mysqli_query($conn, $sql)) {
mysqli_close($conn);
exit();
}
$host = "localhost";
$user = $_SESSION['sess_email'];
$flush_pri = "FLUSH PRIVILEGES";
$pass = $new_pass;
// GRANT USER PRIVILEGES
echo $current_project;
$grantQ = "GRANT ALL PRIVILEGES ON " . $new_dbname . ".* TO '{$user}'#'{$host}' identified by '{$pass}'";
//$grantQ = "GRANT ALL PRIVILEGES ON " . $new_dbname . ".* TO '{$user}'#'{$host}'";
if(!mysqli_query($conn,$grantQ)){
mysqli_close($conn);
exit();
}
if(!mysqli_query($conn,$flush_pri)){
mysqli_close($conn);
exit();
}
// SUPER CONNECTION CLOSE
mysqli_close($conn);
// ALTOGETHER A DIFFERENT CONNECTION
$secdb_db = "little_userdb";
$secdb_server = "localhost";
$secdb_username = "user#littlesidegym.com";
$secdb_password = "123456";//
$conn = new mysqli($secdb_server, $secdb_username, $secdb_password, $secdb_db);
if ($conn->connect_error) {
die($contact_cus_supp);
}
echo "HELLO WORLD";
?>
// FORM
echo '<table>';
echo '<form action="create_project.php" method="POST" id = "myform" name = "myform" >';
echo '<tr><th></th></tr><tr><td><input type = "text" value="" name = "db_name" class = "req alphanums" placeholder = "DB Name" ><td></tr>';
echo '<tr><th></th></tr><tr><td><input type = "password" value="" name = "pass" class = "req" placeholder = "Password" ><td></tr>';
echo '<tr><th></th></tr><tr><td><div id = "submit"><input type="submit" id = "submit" name = "submit" value = "Create Project"></div><td></tr>';
echo '</form>';
echo '</table>';
You are using the same user name for newly created database and for accessing little_userdb, thus changing its password each time.
In mysql user is identified by name and hostname mask (mysql looks for first match). So your code changes password for existing user and grants him access to the new db.
Found lots of similar problems on this site, but the solutions for those issues don't seem to reply. The user in question has full access to the database, and from what I can tell I'm not missing any commas etc. A second set of eyes would be great.
Submitted signature is in an acceptable formatTrying to open a connectionError!: SQLSTATE[42000] [1044] Access denied for user 'emkinsti_user1'#'localhost' to database 'signatures'
<?php
// Tracks what fields have validation errors
$errors = array();
// Default to showing the form
$show_form = true;
// 1. Get the input from the form
// Using the PHP filters are the most secure way of doing it
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$output = filter_input(INPUT_POST, 'output', FILTER_UNSAFE_RAW);
// 2. Confirm the form was submitted before doing anything else
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// 3. Validate that a name was typed in
if (empty($name)) {
$errors['name'] = true;
}
// 3. Validate that the submitted signature is in an acceptable format
if (!json_decode($output)) {
$errors['output'] = true;
}
}
// No validation errors exist, so we can start the database stuff
if (empty($errors)) {
echo "Submitted signature is in an acceptable format";"<br/>";
$dsn = 'mysql:host=localhost;dbname=signatures';
$user = 'emkinsti_user1';
$pass = '6nqq103t26';
}
// 4. Open a connection to the database using PDO
try {
echo "Trying to open a connection";
$db = new PDO($dsn, $user, $pass);
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
// Make sure we are talking to the database in UTF-8
$db->exec('SET NAMES utf8');
// Create some other pieces of information about the user
// to confirm the legitimacy of their signature
$sig_hash = sha1($output);
$created = time();
$ip = $_SERVER['REMOTE_ADDR'];
// 5. Use PDO prepare to insert all the information into the database
$sql = $db->prepare('INSERT INTO signatures (signator, signature, sig_hash, ip, created)
VALUES (:signator, :signature, :sig_hash, :ip, :created)');
$sql->bindValue(':signator', $name, PDO::PARAM_STR);
$sql->bindValue(':signature', $output, PDO::PARAM_STR);
$sql->bindValue(':sig_hash', $sig_hash, PDO::PARAM_STR);
$sql->bindValue(':ip', $ip, PDO::PARAM_STR);
$sql->bindValue(':created', $created, PDO::PARAM_INT);
$sql->execute();
// 6. Trigger the display of the signature regeneration
$show_form = false;
// mysql_close($db);
$db = null;
?>
emkinsti_user1'#'localhost' to database 'signatures'
if you are using CPanel, CPanel uses prefixes also to the database name:
You used: emkinsti_user1 as users.
You should use: emkinsti_signatures as database name.
Log in into your CPanel and there you will find the database name with prefix
Try http://php.net/manual/en/pdo.getavailabledrivers.php to see if the database is supported by PDO.
<?php
print_r(PDO::getAvailableDrivers());
?>
Just an idea. I would expect another error message when it isn't. So, as far as I can tell, the user has no access when accessing the database from the local host.
I have a file called database.php which contains the following:
<?php
// Database connectivity stuff
$host = "localhost"; // Hostname for the database. Usually localhost
$username = "root"; // Username used to connect to the database
$password = "root"; // Password for the username used to connect to the database
$database = "blog"; // The database used
// Connect to the database using mysqli_connect
$connection = mysqli_connect($host, $username, $password, $database);
// Check the connection for errors
if (mysqli_connect_errno($connection)) {
// Stop the whole page from loading if errors occur
die("<br />Could not connect to the database. Please check the settings and try again.") . mysqli_connect_error() . mysqli_connect_errno();
}
?>
I have a new file called functions.php which contains the following:
<?php
// Functions file for the system
function add_post($user_id, $body) {
$post = "INSERT INTO posts (user_id, body, stamp) VALUES ($user_id, $body, now())";
$insert_post = "mysqli_query($connection, $post)";
}
?>
And an insert post php page (newPost.php) which contains the following:
<?php
// Define the user id and get the post from the form
$user_id = 1; // User ID hard coded for testing purposes
$body = substr($_POST['body'],0,200);
// Insert the post in the database using the add_post() function
if (isset($user_id, $body) && ($_SERVER['REQUEST_METHOD'] == 'POST')) {
// Insert the post in the database if conditions were met
add_post($user_id, $body);
}
// If the conditions were not met, display an error
else {
die("The post was not added. Something went wrong. Please try again later");
}
?>
When I try to post some text I get the following error:
Notice: Undefined variable: connection in /Applications/MAMP/htdocs/blog/includes/functions.php on line 7
What am I doing wrong here? isn't $connection supposed to be passed as i used require(); in my newPost.php file?
This is totally wrong:
$insert_post = "mysqli_query($connection, $post)";
^--- ^--
You're not executing your query. You're defining a string which happens to contain some text that LOOKS like a query call. Remove the quotes...
It's a variable scope issue. $connection is not available to add_post() unless you pass it as a parameter:
function add_post($user_id, $body, $connection) {
$post = "INSERT INTO posts (user_id, body, stamp) VALUES ($user_id, $body, now())";
$insert_post = mysqli_query($connection, $post);
}
You can also use the global keyword but that is generally considered a bad practice and should be avoided.
The above answers should get it to work for you, however consider using mysqli prepared statements instead of mysqli_query. Prepared statements are safer and protect you from sql injection through user input.