views:

239

answers:

3

I've got a PHP command line program running. And I want to connect to a mysql shell straight from PHP. I've done this before in Python using os.execvp But I can't get the same thing to work in PHP.

I've tried the following functions:

  • system
  • passthru
  • exec
  • shell_exec

example:

system('mysql -u root -pxxxx db_name');

But they all seem to wait for mysql to exit and return something. What I really want is for PHP to launch the mysql shell and then exit it self. any ideas?

A: 

Give MySQL a script to run that's separate from the PHP script:

system('mysql -u root -pxxxx db_name < script.mysql');
acrosman
A: 

In addition to what acrosman said, you can also use the -e switch to pass SQL from the command line.

$sql = ".....";
system("mysql -u root -pxxxx db_name -e \"$sql\"");

Also, I hope your not actually connecting to the database as root from a PHP application.

tj111
Thankyou for the tip but it's not what I'm looking for. I want to move the user from the PHP cli into a mysql shell.
Mattias
+2  A: 

If you want shell commands to be interactive, use:

system("mysql -uroot -p db_name > `tty`");

That will work for most cases, but will break if you aren't in a terminal.

too much php
Brilliant! this is exactly what I was looking for!
Mattias