0

I prefer running php scripts in the shell as the output comes directly and not in tranches like in a browser. This can be very helpful to see the script is actually still working and also to see which part of a long script takes the longest.

When I call php scripts from the shell like this

php filename.php

it works fine, but only so long as no db connection is established in the script.

Apparently, the mysql_connect() seems to fail:

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///var/mysql/mysql.sock)

How can I fix this?

Thanks!

Charles

EDIT 1

I connect to the db as follows:

//Connect to db
$user="root";
$databasePassword="";
$host="localhost";
$database="database1";
$identifier=mysql_connect($host,$user,$databasePassword,true);
$db1=mysql_select_db($database);

SOLUTION FOUND

This showed me the right way to do it - it's as simple as replacing "localhost" with "127.0.0.1", because: "The reason is that "localhost" is a special name for the mysql driver making it use the unix socket to connect to mysql instead of the a tcp socket."

Community
  • 1
  • 1
Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115
  • Does the mysql unix socket exist at `/var/mysql/mysql.sock`? – Jon Lin Jul 23 '12 at 18:49
  • What OS? You might have to change the path of mysql, check the path – Kush Jul 23 '12 at 18:49
  • 2
    As stated in [the introduction to the PHP manual chapter on the `mysql_*` functions](http://www.php.net/manual/en/intro.mysql.php): *This extension is not recommended for writing new code. Instead, either the [mysqli](http://www.php.net/manual/en/book.mysqli.php) or [PDO_MySQL](http://www.php.net/manual/en/ref.pdo-mysql.php) extension should be used. See also the [MySQL API Overview](http://www.php.net/manual/en/mysqlinfo.api.choosing.php) for further help while choosing a MySQL API.* – eggyal Jul 23 '12 at 18:53
  • Kush I run Mac OS X 10.7.4. @JonLin How do I check whether the socket exists there? – Dennis Hackethal Jul 23 '12 at 18:53
  • you COULD have permission issues... – Bulvak Jul 23 '12 at 18:55
  • Solution found. Please see question edit. Thank you very much nonetheless! – Dennis Hackethal Jul 23 '12 at 19:15

1 Answers1

1

Show your mysql_connect() statement, perhaps you should try to connect to localhost:3306 if your daemon listens on this port.

see: php.net/mysql_connect

If the same script works when called via browser obviously your ini files for the command line environment differ. ini_get("mysql.default_host") shows what setting is used if you do not specify a host to connect to.

mdo
  • 6,961
  • 3
  • 24
  • 26