开发者

How to do interactive with the prompt this way in PHP?

开发者 https://www.devze.com 2022-12-26 14:40 出处:网络
C:\\>mysql -uroot -padmin Welcome to the MySQL monitor.Co开发者_开发百科mmands end with ; or \\g.
C:\>mysql -uroot -padmin
Welcome to the MySQL monitor.  Co开发者_开发百科mmands end with ; or \g.
Your MySQL connection id is 6
Server version: 5.0.37-community-nt-log MySQL Community Edition (GPL)

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> show databases
    -> ;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| attendance         |
| fusionchartsdb     |
| mysql              |
| sugarcrm           |
| test               |
+--------------------+
6 rows in set (0.09 sec)

mysql> use mysql;
Database changed
mysql>

So I want to start a process by mysql -uroot -padmin,and in that process I want to run these statements:

 show databases
 use mysql
 insert xxx (..) values (..)

How to do it in PHP?


I don't think I follow your question completely...

If you're trying to execute statements in MySQL in PHP, you can use the mysql_* functions.

If you just want to execute a series of commands via the command line, you can use

`mysql -u root -p admin --execute "show databases; use mysql; insert ...."`

If you want to write your own interactive replacement for the MySQL command line tools in PHP, you're going to need a hell of a lot of time and perseverance. Start by reading about PHP's CLI: http://php.net/manual/en/features.commandline.php


You can write your own console or use ready-made one called PHPMyAdmin. If your intention is just to interact with mysql server using web-frontend.

Although writing your own could be tricky. Unfortunately, HTTP servers are not interactive. HTTP is stateless protocol. So, you have to find a way to save a state between requests. One of solutions is to use persistent connection. But with goal being unclear it's hard to advise anything certain.


The MySQL client uses the readline() library, which is available to PHP as well.

PHP's PEAR commandline app (invoked when you run pear install <package> processes interactive command line input in a similar manner, but without using the full readline library. There's some of the input-reading source here. The key line being $line = fgets(STDIN, 2048);


You can do so via proc_open.

$bin = 'path/to/mysql.exe';
$cmd = $bin . ' -ulocalonly';
$descriptors = array(
  0 => array('pipe', 'r'), 
  1 => array('pipe', 'w'),
  2 => array('pipe', 'r')
);

$process=proc_open($cmd, $descriptors, $pipes, dirname($bin));
if (is_resource($process)) {
  // ....

}

The tricky part is to parse the output of the other process (from $pipes[0] and $pipes[2]) and react on all possible situations (including error handling). You might want to look into the expect pecl extension for that.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号