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);
Related
Basically, I have two identical tables in SQL Server and MySQL. I want to use PHP in such a way that I'll only have to manually insert new values in one of them. I want to make a PHP code where the newly inserted values in the SQL Server table will also be inserted in its identical counterpart in MySQL with the press of a button.
For example, I have a table named "Customers" in both SQL Server and MySQL with the rows "ID (auto incremented)", Name, and Address. I insert new values into those columns in SQL Server. How do I make it so that I'll only have to press a button made in PHP so that I won't have to do the whole "insert into" process again in MySQL?
Any ideas are much appreciated!
According to new information given in the comments, I'm changing my answer and adjusting the code.
Code example:
<?php
$serverName = "server"; //serverName\instanceName
$connectionInfo_mssql = array("Database"=>"DB", "UID"=>"username", "PWD"=>"password","CharacterSet"=>"UTF-8");
$conn_mssql = sqlsrv_connect($serverName, $connectionInfo_bi);
$conn_mysql = new mysqli("server", "username", "password", "db");
//SELECT FROM MS SQL DB
$mssql_array = array();
$ms_sql = "SELECT column_names FROM db_table";
$mssql_query = sqlsrv_query($conn_mssql , $ms_sql);
while($row = sqlsrv_fetch_array($mssql_query) {
$mssql_array[] = array('name' => $row['name'],
'adress' => $row['adress']);
}
foreach($mssql_array as $key => $value) {
//SELECT FROM MySQL DB
$my_sql = "SELECT column_names FROM db_table WHERE name = '".$value['name']."' AND adress = '".$value['adress']."'";
$mysql_query = mysqli_query($conn_mysql , $my_sql);
$num_rows = mysqli_num_rows($mysql_query);
if ($num_rows == 0) {
//Insert in MySQL DB
$sql = "INSERT INTO db_table (db_columns) VALUES (variables_from_array)";
$sql_query = mysqli_query($conn_mysql, $sql);
} else {
//There is a record in DB, and maybe you want to update it. If not, then lose this else part.
}
}
echo 'Table Customers from MS SQL DB and table Customers from MySQL DB are now synced!';
?>
I'm trying to use Firebird in my PHP application. I already managed to make interbase and Firebird PDO extensions work, and the connection is established without any problems.
But when I try to make a simple select into one of the tables (select * from filial), it always returns empty, just like there's nothing recorded in the table.
I already tested my script in another database, and it worked properly, so I guess it's not a PHP problem, but I think it has something with my database.
This is how I created the database and table with ISQL:
create database 'C:\My\Database\Path.fdb' page_size 4096 user 'myuser' password 'mypass' default character set UTF8;
connect 'C:\My\Database\Path.fdb' user 'myuser' password 'mypass';
create table filial (id int not null primary key, nome varchar(45));
insert into filial (id, nome) values (1, 'test');
When I run the 'select' query in ISQL, it returns the one inserted row. But doing it with interbase or PDO, I get an empty object.
I also tried using capital letters for the table and columns names.
What am I doing wrong?
I'm running this project in a Windows 7, with WAMP and Firebird server installed.
Interbase PHP code:
$db_server = 'localhost';
$db_user = 'SYSDBA';
$db_passw = 'masterkey';
$db_name = 'C:\Users\Joao\Firebirds\Desenvolvimento.fdb';
$host = $db_server.':'.$db_name;
$dbh = ibase_connect($host, $db_user, $db_passw);
$stmt = 'select * from filial';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
echo $row->ID.'<br />';
}
ibase_free_result($sth);
ibase_close($dbh);
PDO PHP code:
$db_server = 'localhost';
$db_user = 'SYSDBA';
$db_passw = 'masterkey';
$db_name = 'C:\Users\Joao\Firebirds\Desenvolvimento.fdb';
$str_conn='firebird:host='.$db_server.';dbname='.$db_name;
$conn = new PDO($str_conn, $db_user, $db_passw);
$q = $conn->prepare('SELECT * FROM filial;');
$q->execute();
$dados = $q->fetchAll(PDO::FETCH_OBJ);
foreach($dados as $row){
echo $row->ID.'<br/>';
}
As I'm working locally, I also put connection data.
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/>';
}
Suppose I have a table called "device" as below:
device_id(field)
123asf15fas
456g4fd45ww
7861fassd45
I would like to use the code below to insert new record:
...
$q = "INSERT INTO $database.$table `device_id` VALUES $device_id";
$result = mysql_query($q);
...
I don't want to insert a record that is already exist in the DB table, so how can I check whether it have duplicated record before inserting new record?
Should I revise the MYSQL statement or PHP code?
Thanks
UPDATE
<?php
// YOUR MYSQL DATABASE CONNECTION
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'device';
$table = 'device_id';
$db_link = mysql_connect($hostname, $username, $password);
mysql_select_db( $database ) or die('ConnectToMySQL: Could not select database: ' . $database );
//$result = ini_set ( 'mysql.connect_timeout' , '60' );
$device_id = $_GET["device_id"];
$q = "REPLACE INTO $database.$table (`device_id`) VALUES ($device_id)";
$result = mysql_query($q);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
Since I understood well your question you have two ways to go, it depends how you would like to do the task.
First way -> A simple query can returns a boolean result in the device_id (Exists or not) from your database table. If yes then do not INSERT or REPLACE (if you wish).
Second Way -> You can edit the structure of your table and certify that the field device_id is a UNIQUE field.
[EDITED]
Explaining the First Way
Query your table as follow:
SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'
then if you got results, then you have already that data stored in your table, then the results is 1 otherwise it is 0
In raw php it looks like:
$result = mysql_query("SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'");
if (!$result)
{
// your code INSERT
$result = mysql_query("INSERT INTO $database.$table `device_id` VALUES $device_id");
}
Explaining the Second Way
If your table is not yet populated you can create an index for your table, for example go to your SQL command line or DBMS and do the follow command to your table:
ALTER TABLE `your_table` ADD UNIQUE (`device_id`)
Warning: If it is already populated and there are some equal data on that field, then the index will not be created.
With the index, when someone try to insert the same ID, will get with an error message, something like this:
#1062 - Duplicate entry '1' for key 'PRIMARY'
The best practice is to use as few SQL queries as possible. You can try:
REPLACE INTO $database.$table SET device_id = $device_id;
Source
Is it possible to empty an entire database by connecting to it with PHP and giving a command?
The simplest way to do it, if you have the privileges, is:
DROP DATABASE dbName;
CREATE DATABASE dbName;
USE DATABASE dbName;
The alternative is to query the information_schema database for triggers, stored routines (procedures and functions), tables, views and possibly something else, and drop them individually.
Even after this, your database might still not be in the same state as a newly created one, since it might have a custom default character set and collation set. Use ALTER DATABASE to change that.
As features keep getting added (events...) you'll have more and more work this way. So really, the only way to completely empty the database is to drop it and re-create it.
You can get table names with
SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'your db'
And make the truncate,
even, you can make
SELECT 'TRUNCATE TABLE ' + table_name + ';' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'your db'
And then iterate the resultset executing the string query for each record.
You can get a list of all tables in a database ($databaseName), loop through them all, and apply TRUNCATE TABLE to each.
$result = mysqli_query($link, "SHOW TABLES IN `$databaseName`");
while ($table = mysqli_fetch_array($result)) {
$tableName = $table[0];
mysqli_query($link, "TRUNCATE TABLE `$databaseName`.`$tableName`");
if (mysqli_errno($link)) echo mysqli_errno($link) . ' ' . mysqli_error($link);
else echo "$tableName was cleared<br>";
}
This clears the contents of all the tables in a database, keeping the structure.
Yes. Basically, you need to get a list of all Tables in the Database, then iterate over that list and issue a TRUNCATE TABLE $tablename for each entry.
This looks like a decent enough implementation: Truncate all tables in a MySQL database
This worked for me.
mysql -u < DB-USER > -p<DB-PASS> --silent --skip-column-names -e "SHOW TABLES" <DB-NAME> | xargs -L1 -I% echo 'DROP TABLE `%`;' | mysql -u < DB-USER > -p< DB-PASS > -v < DB-NAME >
<?php
$connection = new mysqli($host, $user, $pass, $db);
$sql = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA LIKE '".$db."'";
$result = $connection->query($sql);
$tables = $result->fetch_all(MYSQLI_ASSOC);
foreach($tables as $table) {
$sql = "TRUNCATE TABLE `".$table['TABLE_NAME']."`";
$result = $connection->query($sql);
}
?>
Yes. You can connect the database and Truncate the table by assigning as a variable.
$conn = new mysqli($servername, $username, $password, $dbname);
$variableName = $conn->query($que);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query('TRUNCATE TABLE yourtablename;');
if ($result) {
echo "Request ID table has been truncated";
}
else echo "Something went wrong: " . mysqli_error();