autumnrustle autumnrustle - 1 year ago 254
MySQL Question

Using mysql via SSH (php)

Try to connect to remote mysql via ssh2 and php.


$ssh_connection=ssh2_connect($ssh_server, $ssh_port);
$ssh_auth=ssh2_auth_password($ssh_connection, $ssh_user, $ssh_password);
$ssh_tunnel = ssh2_tunnel($ssh_connection, $ssh_server, $ssh_port);

$db_hostname = 'localhost';
$db_database = '';
$db_username = '';
$db_password = '';
$db_port = '3306';

$connection_mysql = new mysqli($db_hostname, $db_username, $db_password, $db_database, $db_port);

Tunnel is ok, but I see, that mysql use my local mysql DB, not remote via SSH. So, how can i use mysql via SSH?

OS windows with WAMP on it.

Answer Source
$ssh_connection = ssh2_connect($ssh_server, $ssh_port);
ssh2_auth_password($ssh_connection, $ssh_user, $ssh_password);
$query="SET CHARACTER SET utf8; use ${db_database}; ${query};";
$query=str_replace('"', '\'', stripslashes($query));
$ssh_query="ssh -L 3307:${ssh_server}:${ssh_port}; echo \"${query}\" | mysql -u ${db_username} -h ${db_hostname} --password=${db_password}";
$result=ssh2_exec($ssh_connection, $ssh_query);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download