Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: mysql_connect() won't work via command line

Tags:

php

mysql

I have a script which calls mysql_connect() to connect to a MySQL DB. When I run the script in a browser, it works. However, when I run it from a command line I receive the following error:

Call to undefined function mysql_connect()

This seems completely paradoxical. Anyone have any ideas as how I can run it from the command line. Btw, I run it from a bash shell like so:

php /path/to/script.php
like image 482
CoolGravatar Avatar asked Oct 08 '08 03:10

CoolGravatar


3 Answers

This problem can arise when you are running Mac OS X and MAMP. The command line version tries to use the MAC OS X version, which happens to load no php.ini by default.

You can check that with the command:

php --ini

See the missing config file?

Configuration File (php.ini) Path: /etc
Loaded Configuration File:         !!! THE CONFIG FILE IS MISSING HERE !!!
Scan for additional .ini files in: /Library/Server/Web/Config/php
Additional .ini files parsed:      (none)

What you have to do is, load up the php.ini of your choice and copy it to the default location of your command line interpreter which is /etc and then run the above command again, you should see that the php.ini file is loaded which should look like:

Configuration File (php.ini) Path: /etc
Loaded Configuration File:         /etc/php.ini
Scan for additional .ini files in: /Library/Server/Web/Config/php
Additional .ini files parsed:      (none)

You should also add this to the PHP.ini file in /etc

mysql.default_socket = /Applications/MAMP/tmp/mysql/mysql.sock

This should fix every problem.

phew..

like image 90
Herr Avatar answered Sep 24 '22 05:09

Herr


It maybe using a default PHP configuration. I have found before that it doesn't use the same php.ini or doesn't use one at all. Therefore some of the extensions won't be enabled.

Do this instead:

php -c /etc/php.ini /path/to/script.php

Where /etc/php.ini is the path to your ini file. You can find this by doing a phpinfo();

like image 32
Darryl Hein Avatar answered Sep 22 '22 05:09

Darryl Hein


Check if you php cmd version actually has mysql support:

 <? php
  echo php_info()
 ?>

If not, then probably it's because it is a different version than the one used by your web server.

Run php using the "-m" parameter in order to list all the compiled modules:

  $ php -m

You should see the "mysql" module. If not, then i guess the php cmd version has not been compiled using the --with-mysql or the "configure" script could not included it due some reason.

like image 29
Gravstar Avatar answered Sep 24 '22 05:09

Gravstar