Why can't I run a working PDO connection through terminal? - php

My working index.php that runs in a browser looks like this:
<?php
$dbh = new PDO(...whatever
It works in a bowser just fine. I can do anything.
Running in terminal like:
shell> php index.php
I get some error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] No such file or directory' in /Library/WebServer/Documents/index.php:3
Stack trace:
#0 /Library/WebServer/Documents/index.php(3): PDO->__construct('mysql:host=loca...', 'root', 'frekinpassword')
#1 {main}
thrown in /Library/WebServer/Documents/index.php on line 3
What's going on here?

I think, your unix_socket changed and you didn't change your php client php.ini
First of all, get your unix_socket location.
$ mysql -uroot -p
Enter your mysql password and login your mysql server from command line.
mysql> show variables like '%sock%';
+---------------+---------------------------------------+
| Variable_name | Value |
+---------------+---------------------------------------+
| socket | /opt/local/var/run/mysql5/mysqld.sock |
+---------------+---------------------------------------+
Your unix_soket could be diffrent.
Then change your php.ini, find your php.ini file from
<? phpinfo();
You maybe install many php with different version, so please don't assume your php.ini file location, get it from your 'phpinfo';
Change your php.ini:
mysql.default_socket = /opt/local/var/run/mysql5/mysqld.sock
mysqli.default_socket = /opt/local/var/run/mysql5/mysqld.sock
pdo_mysql.default_socket = /opt/local/var/run/mysql5/mysqld.sock
Then restart your apache or php-fpm.

It looks like you're using localhost as the connection string for your MySQL database. When MySQL sees localhost, it interprets that as "use a mysql.sock" file. PHP is telling you it can't find that mysql.sock file.
The most likely cause for this is your web server and command line PHP are configured to use different php.ini files, and those php.ini files have differently configured mysql.sock files. You can find your web server php.ini file(s) by running
phpinfo();
from a PHP file loaded via the web server. You can find your command line php.ini file(s) by running the following
$ php --ini
If you can't fix your command line php.ini file, consider connecting to your MySQL server via 127.0.0.1 instead of localhost. When you use the IP address, PHP should attempt to connect via the network instead of a socket file.

Related

php pg_connect() works in terminal but not in the browser

<?php
echo "Inside php file!<br>";
$dbconn = pg_connect("host=localhost dbname=atharvacm user=atharvacm port=5432 password=Dominicmcs9") or die("Cannot connect to DB");
echo "after con<br>";
$query = "select * from person;";
$result = pg_query($dbconn, $query) or die("cannot exec query");
while ($answer = pg_fetch_row($result)) {
echo $answer[0];
echo $answer[1];
echo " huh<br>";
}
echo "<br>end";
?>
this is the code im trying to execute. It outputs the records in the table person in terminal but in the browser it only echoes "Inside php file" and nothing after it.
Here is the terminal output:
atharvacm#kali:/var/www/html$ php psqltest.php
Inside php file!<br>after con<br>1abc huh<br>2def huh<br>3pqr huh<br>4xyz huh<br><br>end
atharvacm#kali:/var/www/html$
Here is the output from the web browser
Inside php file!
Fatal error: Uncaught Error: Call to undefined function pg_connect() in /var/www/html/psqltest.php:4 Stack trace: #0 {main} thrown in /var/www/html/psqltest.php on line 4
I have kali linux and running apache2, psql, php7.
I installed the php-pgsql package and uncommented the extention in the php.ini file.
I cant seem to figure out what the problem is but my guess is that the pg_connect function is not finding the psql database or something form the browser.
thanks!
Please check the config.ini file of ur php configuration file "php.ini" within Apache Tomcat
In some case the software is not configured for psql
So go in the file and uncomment the line
Extension= pgsql
Also enable ur error log in Apache
U can refer
Please check the config.ini file of ur php configuration file "php.ini" within Apache Tomcat
In some case the software is not configured for psql
So go in the file and uncomment the line
Extension= pgsql
Also enable ur error log in Apache
U can refer
Please check the config.ini file of ur php configuration file "php.ini" within Apache Tomcat
In some case the software is not configured for psql
So go in the file and uncomment the line
Extension= pgsql
Also enable ur error log in Apache
U can refer
Please check the config.ini file of ur php configuration file "php.ini" within Apache Tomcat
In some case the software is not configured for psql
So go in the file and uncomment the line
Extension= pgsql
Also enable ur error log in Apache
U can refer
How do I get PHP errors to display?

mysqli_connect() error with PHP's built-in web server

I compiled PHP with mysqlnd using the prescriptions from Mysqlnd installation. PHP works fine. php -m | grep mysql shows that neccessary MySQL modules are actually installed. Then I run php -S localhost:8088 -t <dir>. In PHP code function_exists('mysqli_connect') does return true. But when I run mysqli_connect() warning mysqli_connect(): (HY000/2002): No such file or directory arises. In /etc/php.ini I set default socket to /tmp/mysql.sock then to /var/lib/mysql/mysql.sock. Both variants didn't work. How can I enable mysql support in PHP-built-in server?
Have you tried those solutions ?
Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in
First try to use 127.0.0.1 instead of "localhost" in your mysqli_connect call.
Then make sure there is sockets where it should : make a symbolic link from /tmp/mysql.sock to /var/mysql/mysql.sock (or other way depending what exists on your computer)
Finally try to read all answers listed in the link above, maybe one of them will hel you

Unable to connect mysql and getting socket error

I have installed xampp in my linux server. But during connection in command prompt i am getting below error. Please help me to fix the error.
linux-pott:/opt/lampp/var/mysql # mysqladmin -u root -p status
Enter password:
mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket'/var/run/mysql/mysql.sock' (2)'
Check that mysqld is running and that the socket: '/var/run/mysql/mysql.sock' exists!
I had similar problem on a CentOS VPS. If MySQL won't start or keeps crashing right after it starts, try these steps:
1) Find my.cnf file (mine was located in /etc/my.cnf) and add the line:
innodb_force_recovery = X
replacing X with a number from 1 to 6, starting from 1 and then incrementing if MySQL won't start. Setting to 4, 5 or 6 can delete your data so be carefull and read http://dev.mysql.com/doc/refman/5.7/en/forcing-innodb-recovery.html before.
2) Restart MySQL service. Only SELECT will run and that's normal at this point.
3) Dump all your databases/schemas with mysqldump one by one, do not compress the dumps because you'd have to uncompress them later anyway.
4) Move (or delete!) only the bd's directories inside /var/lib/mysql, preserving the individual files in the root.
5) Stop MySQL and then uncomment the line added in 1). Start MySQL.
6) Recover all bd's dumped in 3).
Good luck!

MySQL: Still can't LOAD DATA LOCAL INFILE '/path/to/file.txt' INTO TABLE test FIELDS TERMINATED BY '\n'

Using Ubuntu Server 14.04 x64 / PHP 5.5.9-1ubuntu4 (cli) w/ FPM / MySQL InnoDB version 5.5.35
I've created a PHP script that downloads a text file from a remote server and then attempts to import it with the LOAD DATA LOCAL INFILE '/path/to/file.txt' INTO TABLE test FIELDS TERMINATED BY '\n'.
I've gone through the process of modifying the php.ini file:
[MySQL]
; Allow accessing, from PHP's perspective, local files with LOAD DATA statements
; http://php.net/mysql.allow_local_infile
mysql.allow_local_infile = On
I've modified my.cnf (both [mysql] and [mysqld] entries):
local-infile=1
local-infile
I've run MySQL from the terminal and then issue:
SET GLOBAL local_infile = 'ON';
I've manually started and stopped MySQL with:
sudo /etc/init.d/mysql start --enable-local-infile
After each of these commands I can run SHOW GLOBAL VARIABLES LIKE 'local_infile'; and it always says the value is ON. I have no problem whatsoever executing my LOAD DATA command from MySQL prompt but if I try to run the LOAD DATA stored in a PHP file it errors out with:
The used command is not allowed with this MySQL version
From what I've read, there seems to be a few who suggest to recompile PHP with "--with-mysql=/usr" but that seems like a real sledge hammer approach to me, maybe I'm wrong. I can issue ANY MySQL query except for that that from a PHP file. What am I doing wrong?
You have to write twice the following line into the file /etc/mysql/my.cnf
sudo gedit /etc/mysql/my.cnf
then under paragraph [mysql]
and paragraph [mysqld]
add the following line :
local-infile=1
then save the file
then restart

Will I need to recompile/install php to add the mssql extension?

I have a system that is running php, and I recently needed to add connectivity to an MSSQL database. I have FreeTDS and UnixODBC installed/configured correctly, and I can make successful queries in python, and via utilities like tsql and isql. After looking at phpinfo() I've discovered I don't have a 'sqlsrv' section, and there is no mssql.so file in my php extensions directory.
I want to add this to my system without having to recompile/install php. Would I be able to find and download the mssql.so file, put it into my extensions directory, add extension=/path/to/mssql.so to my php.ini file, and reload apache to get this working? Or is there more steps I would need to take?
EDIT:
The system is running SLES11 with PHP 5.2
EDIT 2:
I've managed to get the php5-mssql extension installed. I grabbed the source, extracted it, and copies these files:
ext/mssql/config.m4
ext/mssql/php_mssql.c
ext/mssql/php_mssql.h
Then, in the directory where I copied the files to, I ran phpize (you will need to install php5-devel to get this tool), and compiled the extension like so:
./configure --with-mssql=/usr/local/freetds
make
I also had to add a line and comment out a line in php_mssql.c before it could actually compile correctly (not everyone will need to do this):
{NULL,NULL,NULL}
/*PHP_FE_END*/
This created the mssql.so file in /php_mssql/modules/ (relative to where I compiled the code), which I was able to move to my extensions directory (you can find this with php -i | grep extensions). I added extension=mssql.so to my php.ini file; however, there is still no 'sqlsrv section in phpinfo().
Some connection methods seem to partially work:
When running the following code from a shell, <h1>Connection Success</h1> is shown; but when opened in a browser, nothing after the mssql_connect line is shown:
<?php
//*************************************************************************
//Open Database Connection
//*************************************************************************
//phpinfo();
$dbserver="MyServer";
$dbusername="user";
$dbpassword="pass";
$defaultdb="DBName";
$cn = mssql_connect($dbserver,$dbusername,$dbpassword) or die("Connection Error");
$db = mssql_select_db($defaultdb,$cn) or die("Database Error");
echo "<h1>Connection Success</h1>";
?>
So it looks like I'm partially getting a connection that way? When I try with a PDO object, I get another error:
Code:
<?php
$con = new PDO('odbc:host=MyServer;dbname=DBName','user','pass');
?>
Error:
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[IM002] SQLDriverConnect: 0 [unixODBC][Driver Manager]Data source name not found, and no default driver specified' in /path/to/php/file/test3.php:3
Stack trace:
#0 /path/to/php/file/test3.php(3): PDO->__construct('odbc:host=MySer...', 'user', 'pass')
#1 {main}
thrown in /path/to/php/file/test3.php on line 3
I've also tried the following (assuming that the PDO statement/DSN in the previous code was incorrrect):
<?php
try {
$db = new PDO("odbc:Driver=FreeTDS; Server=MyServer; Port=1433; Database=DBName; UID=user; PWD=pass;");
} catch (PDOException $exception) {
die("$exception");
}
echo "<h1>Success!</h1>";
?>
This showed <h1>Success!</h1> from the shell, but showed the following error in my web browser:
exception 'PDOException' with message 'SQLSTATE[08001] SQLDriverConnect: 0 [unixODBC][FreeTDS][SQL Server]Unable to connect to data source' in /path/to/php/file/test4.php:3 Stack trace: #0 /path/to/php/file/test4.php(3): PDO->__construct('odbc:Driver=Fre...') #1 {main}
In ODBC the error message contains elements in [] at the start of the message and the rightmost one is the part of the chain reporting the error (see ODBC Diagnostics & Error Status Codes. So, "[unixODBC][Driver Manager]Data source name not found, and no default driver specified" was reported by unixODBC. What unixODBC is saying is the string passed to the ODBC API SQLConnect or SQLDriverConnect does not identify a DSN (data source name) or an ODBC driver and there is no default DSN defined. You can find where your data sources are defined by running odbcinst -j e.g.,
$ odbcinst -j
unixODBC 2.2.14
DRIVERS............: /etc/odbcinst.ini
SYSTEM DATA SOURCES: /etc/odbc.ini
FILE DATA SOURCES..: /etc/ODBCDataSources
USER DATA SOURCES..: /home/martin/.odbc.ini
SQLULEN Size.......: 4
SQLLEN Size........: 4
SQLSETPOSIROW Size.: 2
Here, drivers are defined in /etc/odbcinst.ini, system data sources in /etc/odbc.ini and user data sources in /home/martin/.odbc.ini. As you'll probably be running PHP probably under a web server I'd stick to using the system data sources if I were you. You can list your system data sources with odbcinst -q -l -s. You find a a very good explanation of Linux/ODBC at Linux/UNIX ODBC.
Your second error "[unixODBC][FreeTDS][SQL Server]Unable to connect to data source" is reported by the SQL Server driver from FreeTDS so in this case you must have passed sufficient information to unixODBC to at least allow it to identify the driver, load it and call SQLConnect/SQLDriverConnect in it. You can see what was passed to unixODBC's SQLConnect/SQLDriverConnect by enabling tracing in unixODBC. You enable tracing of unixODBC by editing your odbcinst.ini file (locate with odbcinst -j command above) and adding the following to the top of it:
[ODBC]
Trace = yes
TraceFile = /tmp/unixodbc.log
Now, when you run your php example it will log to /tmp/unixodbc.log all ODBC API calls and the one you are looking for is SQLConnect or SQLDriverConnect. e.g., when I connect to a DSN called mydsn with a username and password of XXX and YYY I see:
[ODBC][31521][1374740062.012973][SQLDriverConnect.c][687]
Entry:
Connection = 0x9d7d430
Window Hdl = (nil)
Str In = [DSN=mydsn;UID=XXX;PWD=********][length = 29]
Str Out = 0xbfdeb83c
Str Out Max = 512
Str Out Ptr = 0xbfdeb638
Completion = 0
UNICODE Using encoding ASCII 'ISO8859-1' and UNICODE 'UCS-2LE'
DIAG [01000] [Easysoft][SQL Server Driver][SQL Server]Changed database context to 'master'.
DIAG [01000] [Easysoft][SQL Server Driver][SQL Server]Changed language setting to us_english.
Note, this connection was successful and it clearly shows part of the connection string was DSN=mydsn and mydsn exists as a DSN in my /etc/odbcinst.ini.
isql can work differently to some ODBC enabled applications as isql calls the ODBC API SQLConnect whereas most ODBC applications these days are ODBC 3 aware and use SQLDriverConnect. The main difference is SQLConnect is only given 3 arguments, a DSN name, a username and a password where SQLDriverConnect is given a single string of attribute/value pairs defining the connection. I only tell you this so you are aware how it is possible for isql to work and something else not to.
However, in your second case when you examine your trace you'll see unixODBC got something useful enough to identify the driver, load it and call freeTDS's ODBC driver and the error "Unable to connect to data source" is coming from freeTDS. So, I suggest your DSN is probably ok and your freetds.conf is incorrect in some way. As I don't use freeTDS myself I'm not sure but I've heard you can use ODBC with freeTDS without any reference to the freetds.conf file and switches based on whether you use Server or ServerName. I'm sure there are loads of examples on the freeTDS web site.
Here's how I connect to MS SQL servers from a LAMP (Ubuntu) stack:
/etc/odbc.ini
# Define a connection to a Microsoft SQL server
# The Description can be whatever we want it to be.
# The Driver value must match what we have defined in /etc/odbcinst.ini
# The Database name must be the name of the database this connection will connect to.
# The ServerName is the name we defined in /etc/freetds/freetds.conf
# The TDS_Version should match what we defined in /etc/freetds/freetds.conf
[mssql]
Description = MSSQL Server
Driver = freetds
Database = XXXXXX
ServerName = MSSQL
TDS_Version = 8.0
/etc/odbcinst.ini
# Define where to find the driver for the Free TDS connections.
[freetds]
Description = MS SQL database access with Free TDS
Driver = /usr/lib/i386-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/i386-linux-gnu/odbc/libtdsS.so
UsageCount = 1
/etc/freetds/freetds.conf
# The basics for defining a DSN (Data Source Name)
# [data_source_name]
# host = <hostname or IP address>
# port = <port number to connect to - probably 1433>
# tds version = <TDS version to use - probably 8.0>
# Define a connection to the Microsoft SQL Server
[mssql]
host = XXXXXX
port = 1433
tds version = 8.0
And here's the PHP code:
$con = new PDO('dblib:host=mssql;dbname=MyDB', 'domain\username', 'password');
You may need to tweak things a bit for your OS. To install the necessary software on Ubuntu I did something like this:
sudo apt-get install php5-odbc php5-sybase tdsodbc
Use PDO and instal this http://www.php.net/manual/en/ref.pdo-sqlsrv.php
I always use PDO it can easy do all the database interaction you need with different db drivers and the same php code. Except the query languages which is sometimes a little different.
For MSSQL you only need to add the drivers just paste the .dll's, add the entry to the conf.ini and restart apache.

Categories