Using php -r
is almost certainly the wrong approach; if you need to use PHP you'd be better off writing the whole script in PHP instead of a mix of Shell as well.
The reasons link=php -r "mysql_connect('localhost', 'root', 'mypassword');"
doesn't work is that (a) mysql_connect
returns a resource to the database connection, which is not something that can be coerced into a string, and (b) your one-line PHP script (mysql_connect('localhost', 'root', 'mypassword');
doesn't echo
that resource anyway, i.e. it doesn't even attempt to coerce the resource into a string.
The mysql_connect
function returns false
on failure, so if you want your link
variable to indicate success or failure you can assign a string to it accordingly. In a one-liner the ternary operator is a simple way to do that, as fab2s noted in his answer (echo @mysql_connect('localhost', 'root', 'mypassword')? 'connected' : 'not connected'
). In that code the @
(silence operator) prevents a failed connection from raising a Warning from PHP, and the use of the ternary operator conditionally returns "connected"
if the call returned something "truthy" and "not connected"
if it returned false
.
As an aside, note that you really shouldn't use the old MySQL extension any longer. In fact, it's generally best to use PDO:
<?php
$dbConn = new \PDO(
'mysql:dbname=my_db;host=localhost;charset=utf8',
'user',
'password',
[PDO::ATTR_ERRMODE => PDO::ERR_EXCEPTION]
);