简体   繁体   中英

Import mysql dump into onto a machine using php

I need to create an install.php file that lets my lecturer import a database dump (that I will provide) onto his machine.

The SQL dump will be called dump.sql, I have a config.php file containing credentials and the install.php that should be used to import the sql dump.

config.php

<?php
    //defining variables
    define('DB_HOST','localhost');
    define('DB_USER','root');
    define('DB_PASS','');
    define('DB_NAME','database'); 

    //connection to mysql server
    $conn=mysql_connect(DB_HOST, DB_USER, DB_PASS) or die ("Error connecting to server: ".mysql_error());
?>

install.php

<?php

    include_once ('config.php');

    echo "starting install...";

    //insert dbdump in the same folder as install.php (put them in a separate folder)
    $command = "C:\xampp\mysql\bin\mysql -u".DB_USER." -p".DB_PASS." < dump.sql";
    //echo $command;
    exec($command, $output, $return_var);

    $output = shell_exec($command);

    if ($output) {
    echo "database created";
    }

?>

I`m using the $command variable as I read this is a standard variable which replicates a cmd command but the database is still not being created.

I tested the same command "mysql -uroot < C:\\xampp\\htdocs\\Recipes\\dump.sql" and it works.

can anyone point what the issue may be?

Thanks

1.Find mysql.exe in xampp folder:

E:\xampp\mysql\bin\mysql.exe

2.Open CMD in xampp folder

E:\xampp\mysql\bin\mysql.exe

3.In CMD use following things

mysql -h localhost -u root -p

4.Show Databases

show databases;

Example:

 MariaDB [(none)]> show databases;
+--------------------------+
| Database                 |
+--------------------------+
| information_schema       |
| mysql                    |
| performance_schema       |
| phpmyadmin               |
| test                     |
+--------------------------+
7 rows in set (0.101 sec)

MariaDB [(none)]>

5.Use Database

use databases;

Example

MariaDB [(none)]> use test
Database changed
MariaDB [test]>

6.Dump Database Then finally give source path for sql file

source E:\your\sql\file\path\mysqlfile.sql

Example

MariaDB [test]> >source E:\your\sql\file\path\mysqlfile.sql

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM