How to create backup of one database into another database using php - php

I want to create backup of my website database in which is in MySQL in another database on regular basis , is it possible to do it using php
Already tried exporting database using php but requirement is something else

I think mysqldump is what you're looking for.
Export database A to SQL file to import to database B:
mysqldump --host=localhost --user=dbauser --password=dbapassword dba_name > /path/to/store/dba.sql
Import database A dump into database B:
cp /path/to/store/dba.sql | mysql --host-localhost --user=dbbuser --password=dbbpassword dbb_name
You can wrap these commands in a call to system() in a PHP script.

$host_name = "localhost";
$user_name= "root";
$password= "";
$database1 = "database_name";
$database2 = "second_database_name";
$con1 = mysqli_connect($host_name ,$user_name,$password,$database1);
$con2 = mysqli_connect($host_name ,$user_name,$password,$database2);
mysqli_select_db($con1,$database1)
mysqli_select_db($con2,$database2)
$sql = "SELECT id, firstname, lastname FROM users";
$result = mysqli_query($con1, $sql);
$result1 = mysqli_query($con2, $sql);

Related

PHP selects in Firebird database always return empty

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.

PHP script to select MySQL data fields and return JSON

So I am trying to download JSON into an iOS application and I don't really know a lot about PHP.
Currently I'm using a generic php scrip as a delegate that connects the the MySQL database and returns JSON results.
<?php
$host = "localhost"; //database host server
$db = "***"; //database name
$user = "root"; //database user
$pass = "root"; //password
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db("***", $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM table";
$resultset = mysql_query($query, $connection);
$records = array();
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
The issue with this is that I don't want to encode the entire table in JSON I just want to return a few select data fields from the particular table so I don't download unnecessary data.
I know that you do this in the SELECT query but something is wrong with my syntax for this.
I had been trying with:
$query = "SELECT *[datafield],[otherdatafield],... FROM table";
but that doesnt seem to be working.
Also, In that table there are two separate data fields that are used to build a URL for an image, and Im not sure how to combine the two here so that they are returned in the JSON as one field.
For example: I Have a base string
"http://wwww.mysite.com/"
and i would like the add the two data Fields to that string so that when it returns the JSON objects they have those fields already concatenated so that the app can just use that URL:
"http://wwww.mysite.com/[data field1]/[datafield2]"
The query you should be trying looks like
$query = "SELECT col1,col2 FROM table";// no need of asterisk if you mention col names
Now if you need to combine two columns there itself in the query, try something like
$query = "SELECT CONCAT('mysite.com/',col1,'/',col2) FROM table";
"/" is the separator between two columns.
The query to fetch individual cols is
select col1,col2,col3 from table_name
No need to provide * like you did
$query = "SELECT *[datafield],[otherdatafield],... FROM table";
^........here * is causing the problem.

INSERT table row to another table

I have two identical tables in my database. I'm trying to ask the user the package number, then when the user clicks a button, it will copy the row matching the user input to another table.
My tables are:
awb - where the original data is.
temp - table to insert the data into.
Here's my code:
$dbhost = "localhost";
$dbuser = "root";
$dbname = "outbound";
mysql_connect($dbhost, $dbuser);
mysql_select_db($dbname) or die(mysql_error());
$packNO = $_GET['packNO'];
// Escape User Input to help prevent SQL Injection
$packNO = mysql_real_escape_string($packNO);
//build query
$query_add="INSERT INTO temp FROM awb WHERE packNO = '$packNO'";
#mysql_query($query_add);
$query = "SELECT * FROM temp";
$qry_result = mysql_query($query) or die(mysql_error());
The code that follows outputs the content of the temp table. But when I print it, I get nothing.
Why is the temp table empty when I print its values?
Try something like this
$query_add="INSERT INTO temp SELECT * FROM awb WHERE packNO = '$packNO'";
Documentation
Similar query, but not using *
$query_add="INSERT INTO temp (packNO, name)
SELECT packNO, name
FROM `awb`
WHERE `packNO` = '$packNO'";

PHP Select fields from database where username equals X

im having problems in PHP with selecting Infomation from a database where username is equal to $myusername
I can get it to echo the username using sessions from the login page to the logged in page.
But I want to be able to select things like 'bio' and 'email' from that database and put them into variables called $bio and $email so i can echo them.
This is what the database looks like:
Any ideas?:/
You should connect to your database and then fetch the row like this:
// DATABASE INFORMATION
$server = 'localhost';
$database = 'DATABASE';
$dbuser = 'DATABASE_USERNAME';
$dbpassword = 'DATABASE_PASSWORD';
//CONNECT TO DATABASE
$connect = mysql_connect("$server", "$dbuser", "$dbpassword")
OR die(mysql_error());
mysql_select_db("$database", $connect);
//ALWAYS ESCAPE STRINGS IF YOU HAVE RECEIVED THEM FROM USERS
$safe_username = mysql_real_escape_string($X);
//FIND AND GET THE ROW
$getit = mysql_query("SELECT * FROM table_name WHERE username='$safe_username'", $connect);
$row = mysql_fetch_array($getit);
//YOUR NEEDED VALUES
$bio = $row['bio'];
$email = $row['email'];
Note 1:
Dont Use Plain Text for Passwords, Always hash the passwords with a salt
Note 2:
I used MYSQL_QUERY for your code because i don't know PDO or Mysqli, Escaping in MYSQL is good enought but Consider Using PDO or Mysqli , as i don't know them i can't write the code with them for you
Simplistic PDO examples.
Create a connection to the database.
$link = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Use the $link variable when creating (preparing) and executing your SQL scripts.
$stmt = $link->prepare('insert into `history` (`user_id`) values(:userId)');
$stmt->execute(array(':userId' => $userId));
Code below will read data. Note that this code is only expecting one record (with 2 data elements) to be returned, so I'm storing whatever is returned into a single variable (per data element), $webId and $deviceId.
$stmt = $link->prepare('select `web_id`, `device_id` from `history` where `user_id` = :userId');
$stmt->execute(array(':userId' => $userId));
while($row = $stmt->fetch()) {
$webId = $row["web_id"];
$deviceId = $row["device_id"];
}
From the picture I can see you are using phpMyAdmin - a tool used to handle MySQL databases. You first must make a connection to the MySql server and then select a database to work with. This is shown how below:
<?php
$username = "your_name"; //Change to your server's username
$password = "your_password"; //Change to your server's password
$database = "your_database" //Change to your database name
$hostname = "localhost"; // Change to the location of your server (this will prolly be the same for you I believe tho
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db($database, $dbhandle)
or die("Could not select examples");
?>
Then you can write something like this:
<?php
$bio = mysql_query("SELECT bio FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
and
<?php
$email = mysql_query("SELECT email FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
Where *your_database_table_name* is the table in the database you selected which you are trying to query.
When I was answering your question, I was referencing this site: http://webcheatsheet.com/PHP/connect_mysql_database.php. So it might help to check it out as well.

Inserting data MySQL

I am a beginner in MySQL and I'm trying to enter some values in my database. The database is already made and its based localy.
I have a Schema named 'test' and within the schema I have a table named 'contacts'. Within the contacts I have an id, first and last name.
So I am trying to enter some data in the contacts. This is my php file:
<?
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '*******'; // root pass
$db_database = 'contacts';
$link = #mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_database,$link);
$query = "INSERT INTO contacts VALUES ('','John','Smith')";
mysql_query($query);
mysql_close();
?>
When I run the file on my browser, my database doesnt get any values. How can I execute that file so that John Smith gets added to my database?
Your php file has to start with <?php instead of <?.
Try this:
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '*******'; // root pass
$db_database = 'contacts';
$link = #mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_database,$link);
$query = "INSERT INTO contacts VALUES ('','John','Smith')";
mysql_query($query);
mysql_close();
?>
Change
mysql_query($query);
to
mysql_query($query) or trigger_error(mysql_error() . $query);
then all will be revealed.
You might consider trying PHP ADODB and using AutoExecute with INSERT, if you know your field names
$db->AutoExecute('tablename',array('field1'=>'value','field2'=>'value'));
Can also be used for update:)
http://adodb.sourceforge.net/
First how is the structure of your table? If you have only 2 fields on the table that is the error if not please try to post the error the console gives back to you.
$query = "INSERT INTO contacts (first,last) VALUES ('John', 'Smith')";
$e=mysql_fetch_assoc($query);
also do not forget that your table structure says not null for the field id and the default value is null, so it will not accept this kind of insertion
Your ID is probably auto_increment, if so add order of attributes to your query :
INSERT INTO contacts(`first_name`, `last_name`) VALUES ('John','Smith')
Replace first_name and last_name with your real column names.

Categories