I have a script that clones tables on to uniquely named MySQL databases from a master sql dump file . Each account has their own database, but the table structure is the same for all accounts. My solution was to dump the master database table and then through PHP shell_exec, run the MySQL controller cmd (mysql) to populate the newly created database with default tables.
At Issue: The process works but only when I hard code the accounts unique database name in the master sql dump file.
However, "USE acct_dbID" line inside the master sql file needs to be dynamically set at runtime.
Here is the code:
include('.dbase_credentials'); //constants for connection object
//using PHP built in connection class mysqli
$mysqli = new mysqli(DB_HOST,DB_UNAME,DB_UPWORD,DB_NAME);
if ($mysqli->connect_errno){
echo "Failed to open database connection: ".$mysqli->connect_error;
exit();
}
$dbID=$varNum; //variable, number ID generated earlier in the account setup process
//create database, doesnt return a resultset, no need for object var here
if ($mysqli->query("CREATE DATABASE acct_".$dbID) === TRUE){
//if dbase was created, clone the tables
$res = shell_exec('mysql -u dbaseUser --password=`cat /path/to/pass` -e "source /path/to/master_tables.sql" acct_'.$dbID);
//provide some UI feedback, shell_exec returns null on failure
if ($res!=null){
echo "The tables were cloned!";
}else{
echo "The cloning process failed!";
}
}else{
echo "no database created.";
}
So again, master_tables.sql needs variable data passed it at runtime so the "USE acct_dbID" can be specific to each new account.
Any thoughts are appreciated.
rwhite35
knittl had the right direction for what I need to do. See the comment conversation above. Thanks knittl.
Here is the new code block using multi_query and file_get_contents.
if ($mysqli->query("CREATE DATABASE acct_".$dbID) === TRUE){
$acct="acct_".$dbID;
$query = "USE ".$acct.";";
$query .= file_get_contents('/path/to/master_table.sql');
$result=$mysqli->multi_query($query);
}
Now account can be variable and multi_query will run each query statement in the string. I probably lose some efficiency but gain the ability to clone tables for each new account. The only additional edit made was to the master_table.sql. I removed all the comments that the dump process adds.
Thanks,
rwhite35
Related
We have a remote server containing a SQL MariaDB. I have to write a piece of code to be placed in that same server whose mission is to execute querys asking for data, modify that data and send it to an external api hosted in another server. When I was shown the DB, it was through ssh commands and entering sql mode inside the server rather than trough code like PHP as I have always done it before.
So, my code is to placed in the same server as the DB, brings the data, modifys some info and calls the api to upload it.
As I said, I am completely lost so my question is simple: can this be achieved? if so, how?
I've read about ssh_connect and exec, but since the code will be placed in the same server I don't think this is necessary, correct me if I am wrong. I can't place any code since I don't know how to start.
Thank you guys for all the help, I am closing the question now:
All I had to do was to use PDO as a secure way to establish a connection and to prepare and execute the querys. Remember I placed my php file in the same server that hosts the DB and note that I had to create a user and grant permissions to the DB you can find how in one of the comments above or here. Here is the code:
try {
$conn = new PDO('mysql:host=yourhostserver;dbname=dbname','user','password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e){
echo "ERROR: " . $e->getMessage();
}
//Example of query
$stmt = $conn->prepare('SELECT GROUP_CONCAT(DISTINCT source_external_subscriber_id) AS ids FROM cdr');
$stmt->execute();
foreach ($stmt as $row) {
$string = $row['ids'];
}
Edit: I have googled and searched, read what I could find of their documentation. Even chatted with them. The chatter could help me. This is why I reach to you.
I am a complete beginner and I am having some troubles getting started with databases on hostgator. I guess my question also is valid using other hosts.
I created a db through the cpanel in hostgator and added a user to it.
I copied this script into a test.php in my /public_html/ folder and ran it on my site.
In the script I used the name, user and password from the database and user I previously created in cpanel. This database I can see using phpMyAdmin.
<?php
try
{
//open the database
$db = new PDO('sqlite:localhost;dbname=user_db', 'user_username', 'password');
//create the database
$db->exec("CREATE TABLE Dogs (Id INTEGER PRIMARY KEY, Breed TEXT, Name TEXT, Age INTEGER)");
//insert some data...
$db->exec("INSERT INTO Dogs (Breed, Name, Age) VALUES ('Labrador', 'Tank', 2);".
"INSERT INTO Dogs (Breed, Name, Age) VALUES ('Husky', 'Glacier', 7); " .
"INSERT INTO Dogs (Breed, Name, Age) VALUES ('Golden-Doodle', 'Ellie', 4);");
//now output the data to a simple html table...
print "<table border=1>";
print "<tr><td>Id</td><td>Breed</td><td>Name</td><td>Age</td></tr>";
$result = $db->query('SELECT * FROM Dogs');
foreach($result as $row)
{
print "<tr><td>".$row['Id']."</td>";
print "<td>".$row['Breed']."</td>";
print "<td>".$row['Name']."</td>";
print "<td>".$row['Age']."</td></tr>";
}
print "</table>";
// close the database connection
$db = NULL;
}
catch(PDOException $e)
{
print 'Exception : '.$e->getMessage();
}
?>
This worked, which is nice, but it created a file in my /public_html/ folder called 'localhost;dbname=user_db'
My issue is that I thought I was connecting to the database I created using cpanel, but when I open phpMyAdmin, that database is empty.
How do I change that script to talk to the database I created using cpanel so that I can reach it using phpMyAdmin?
Edit 2:
So I learned that I need to use mysql, not sqlite because phpMyAdmin is based on MySQL.
Also, using the script from http://www.w3schools.com/php/php_mysql_create_table.asp I was able to connect! So, success! Thank you #mituw16 and #Fred -ii- for helping me! :D
I am assuming you created a MySQL database if you used PHPMyAdmin even thought the tags say SQL Lite.
It looks like you're trying to create an SQL Lite database instead of opening a connection to your MySQL database.
Change this line to the following
//open the database
$db = new PDO('mysql:localhost;dbname=user_db', 'user_username', 'password');
Using phpmyadmin, i created a mysql stored procedure called mySP(). After creating the SP, i noticed that the SP is located in the information_schema db under ROUTINE table. I can see it here. Now from within phpmyadmin, under my actual database if i use SQL tab and do a call to the procedure using:
CALL mySP();
it works as required. NO issues.
Now i am trying to extend this by having a php page call this SP.
my php code is like this:
<?php
include("include_db_connection.php");
$callSP_query = "CALL mySP()";
$callSP_result = mysqli_query($db_conn, $callSP_query)
or die('Connected to database, but StoredProc failed');
if(!$callSP_result)
{
echo "Error with StoredProc...";
}
else
{
echo "Succsess! Called Stored Proc..";
}
?>
Now on loading this page on the browser, i always get the 'Connected to database, but StoredProc failed' error meaning that connection to db was established successfully, but there is some problem with calling the SP.
what could be the problem? The SP was created successfully and even called successfully from within phpmyadmin. where is the php call going wrong?
thanks!
EDIT:
I just checked the error code using mysqli_error() and it says "PROCEDURE mySP does not exist"
this was an issue with my own code. actually, u dont have to reference or even look into the information_schema. your sp can be called with the above code, if your database connection details are correct :)
I am rather new to the PDO library, so I apologize for my inexperience. I am writing a class that uses the PDO library to build and execute queries and return the results, no matter what they are.
Within the class, I detect whether there is an open connection to a database, and if it is the same as the one being configured, it uses this one instead. This is really easy to do using the MsSQL library as the PDO::getAttribute() function returns 'CurrentDatabase' and 'SQLServerName', so I can just apply a condition like so:
if(!empty($this->PDO)){
// Get the current connection information
$current_connection = $this->PDO->getAttribute(PDO::ATTR_SERVER_INFO);
// Return if the connection is the same
if($this->connection_parameters['hostname']==$current_connection['SQLServerName']&&$this->connection_parameters['database']==$current_connection['CurrentDatabase']){
return;
}
}
However, when it comes to MySQL, the data returned from PDO::getAttribute is completely different and I cannot seem to get the database name from the current connection.
Does any body know a function or method to get the currently connected database of a MySQL connection using the PDO library in PHP?
I order to connect to both MySQL and MsSQL, you must have 2 connections. However, changing the database on a live connection is very simple.
The following simply checks if a PDO instance already exists and whether or not it is using the required database. If so then it continues with this connection, if not it changes the database.
// Test if the PDO object already exists
if(!empty($this->PDO)){
// If connection is the same then select the database
if($this->connection_engine==$this->PDO->getAttribute(PDO::ATTR_DRIVER_NAME)){
// Get the current database in use
$database = $this->PDO->query("SELECT {$this->select_db_function}");
$database = $database->fetchAll(PDO::FETCH_NUM);
$database = $database[0][0];
// If the current database matches the new database then return
if($database==$this->connection_parameters['database']){
return;
}
}
}
I see no point in looking for the opened connection and - especially - in checking for the current database.
Why can't you just open the connection, select the database for it and then use this connection all the time throughout your class - just like everyone does?
See comments on the MySQL manual page for 'USE database'
I have been learning how to program websites lately and the time has come for me to add a database. I have in fact already successfully created a MySQL database and interacted with it with PHP.
My problem is I can't seem to access a SQLite database file with it. I am using MAMP to host locally for now. Here is a snippet of the code I am using to access the db and find and print out a value stored on it.
<?php
$dbhandle = sqlite_open('/Applications/MAMP/db/sqlite/Users');
if ($dbhandle == false) die ('Unable to open database');
$dbquery = "SELECT * FROM usernames WHERE username=trevor";
$dbresult = sqlite_query($dbhandle, $dbquery);
echo sqlite_fetch_single($dbresult);
sqlite_close($dbhandle);
?>
As you have access to the database (your code doesn't die), I'd say there's got to be an error later ;-)
Looking at your SQL query, I see this :
SELECT * FROM usernames WHERE username=trevor
Are you sure you don't need to put quotes arround that string ?
Like this :
SELECT * FROM usernames WHERE username='trevor'
Also, notice that sqlite_fetch_single will only fetch the first row of your data -- which means you might need to use sqlite_fetch_array or sqlite_fetch_object if you want to access all the fields of your resulset.