Page 1 of 1

[SOLVED]Weird connection issue with PHP and Mysql

Posted: Thu Sep 19, 2013 6:19 pm
by abishur
I'm connecting to mysql using php's mysqli. It works great and by far and large I've been enjoying it. I'm having a weird issue where I can't get notified when the connection fails though!

Here's what I'm doing. In PHP I've written a db_connect.php that I include in every php file that needs it.

Code: Select all

<?php
error_reporting(E_STRICT);
error_reporting(-1);
ini_set('display_errors',1);
$dbInfo = parse_ini_file('/db_connect/db.in');
define ("HOST", $dbInfo["HOST"]); // The host you want to connect to.
define("USER", $dbInfo["USER"]); // The database username.
define("PASSWORD", $dbInfo["PASSWORD"]); // The database password. 
define("DATABASE", $dbInfo["DATABASE"]); // The database name.

  $mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
// If you are connecting via TCP/IP rather than a UNIX socket remember to add the port number as a parameter.
if (!$mysqli) { 
  die('fail'); 
} else {
  echo 'success';
}
var_dump($mysqli);
echo '<br>';
var_dump(mysqli_connect_error());


If ((USER == "USERNAME HERE") || (PASSWORD == "PASSWORD HERE")){
  print 'ERROR - Please set up the script first';
	exit();
}
?>
The correct path to my ini file is /db_connect/db.ini, to test the if statement I just delete the last i (making it /db_connect/db.in); no such file exists. However in both cases I get "success" :evil:

the var dump on $mysqli is identical regardless of if I point it to the actual file or to a bogus file name.

Code: Select all

object(mysqli)#1 (19) { ["affected_rows"]=> int(0) ["client_info"]=> string(6) "5.5.32" ["client_version"]=> int(50532) ["connect_errno"]=> int(0) ["connect_error"]=> NULL ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["field_count"]=> int(0) ["host_info"]=> string(25) "Localhost via UNIX socket" ["info"]=> NULL ["insert_id"]=> int(0) ["server_info"]=> string(23) "5.5.32-0ubuntu0.12.10.1" ["server_version"]=> int(50532) ["stat"]=> string(135) "Uptime: 8944 Threads: 1 Questions: 2445 Slow queries: 0 Opens: 275 Flush tables: 1 Open tables: 67 Queries per second avg: 0.273" ["sqlstate"]=> string(5) "00000" ["protocol_version"]=> int(10) ["thread_id"]=> int(468) ["warning_count"]=> int(0) }
I've tried doing a try/catch statement and using @new mysli to suppress the default error handler, I've tried using if (NULL !== mysqli_connect_error()), no matter what I do I can't get a notification that it's failed!

When I try putting:

Code: Select all

echo 'Success... ' . $mysqli->host_info . "\n";
instead of echo success, I get

Code: Select all

Success... Localhost via UNIX socket
It's almost as if in the absence of properly defined variables, it's seeing that there is a database on the localhost and returning a successful connection without actually trying? I'm using PHP version 5.4.6-1ubuntu1.4 (I'm developing on a machine outside my pi)

Re: Weird connection issue with PHP and Mysql

Posted: Thu Sep 19, 2013 6:45 pm
by abishur
The answer!

When I supplied a fake directory, the variables were uninitialized and therefore "null", the documentation for the mysqli construct states that if hostname is null is will assume localhost and if password is null it will attempt to authenticate the user against those user records which have no password only. The default setup of mysql is to have three users with global access (usage privileges only) and no password. This meant when I didn't define my file it was still successfully connecting as one of those users.

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Sun Nov 24, 2013 6:40 pm
by williebegoode
I have been having fits getting PHP to talk with MySql. I have used the following code to connect PHP to every other combination of MySql, but not on the Raspberry Pi debian linux.

I used an interface to store details as constants:

Code: Select all

<?php
//Filename: IConnectInfo.php
interface IConnectInfo
{
	const HOST ="localhost";
	const UNAME ="usernow";
	const PW ="secret";
	const DBNAME = "mydb";
	
	public static function doConnect();
}
?>
A general implementation does the error checking and makes the connect. It works in conjunction with the IConnect interface.

Code: Select all

<?php
ini_set("display_errors","1");
ERROR_REPORTING( E_ALL | E_STRICT );
include_once('IConnectInfo.php');
 
class UniversalConnect implements IConnectInfo
{
	private static $server=IConnectInfo::HOST;
	private static $currentDB= IConnectInfo::DBNAME;
	private static $user= IConnectInfo::UNAME;
	private static $pass= IConnectInfo::PW;
	private static $hookup;
	
	public static function doConnect()
	{
		self::$hookup=mysqli_connect(self::$server, self::$user, self::$pass, self::$currentDB);
		if(self::$hookup)
		{
			echo "Successful connection to MySQL:<br/>";
		}
		elseif (mysqli_connect_error(self::$hookup)) 
		{
    		echo('Here is why it failed: '  . mysqli_connect_error());
		}
		return self::$hookup;
	}
}
?>
It throws the following error on my RasPi:
Fatal error: Call to undefined function mysqli_connect() in /var/www/php/ConnectTest/UniversalConnect.php on line 16
I tried the solution on this page, and your code throws the following error:
Warning: parse_ini_file(/db_connect/db.in): failed to open stream: No such file or directory in /var/www/php/ConnectTest/ConnectTest2.php on line 5

Fatal error: Class 'mysqli' not found in /var/www/php/ConnectTest/ConnectTest2.php on line 11
I've been able to create and test databases using the Root Terminal and run other PHP programs on Raspi but no luck so far in getting them to play nice together.

Any ideas?
Kindest regards,
Bill

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Sun Nov 24, 2013 7:05 pm
by rpdom
Have you got the php5-mysql package installed?

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Sun Nov 24, 2013 7:42 pm
by williebegoode
I installed PHP some time ago and then more recently re-install MySQL. Is there a recommended package for both PHP-MySQL for the RasPi?

Kindest regards,
Bill

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Sun Nov 24, 2013 9:58 pm
by DougieLawson
williebegoode wrote:I installed PHP some time ago and then more recently re-install MySQL. Is there a recommended package for both PHP-MySQL for the RasPi?

Kindest regards,
Bill
sudo apt-get install php5-mysql

see http://www.raspberrypi.org/phpBB3/viewt ... ql#p458439 for a sample program that uses MySQL and php to capture registration information for a sports competition.

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Sun Nov 24, 2013 10:19 pm
by williebegoode
Thanks for the tip. I know how to program PHP/MySQL running on Linux and MS (much prefer Linux). Here's a basic OOP set for the fundamentals:

http://nemo.mwd.hartford.edu/~wsanders/ ... syOOP.html

Oddly, I have both PHP and MySql running independently of one another on Raspi; they just won't run together. I'll clear it all out and re-install everything using your tip.

Kindest regards,
Bill

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Sun Nov 24, 2013 11:25 pm
by DougieLawson
williebegoode wrote: Oddly, I have both PHP and MySql running independently of one another on Raspi; they just won't run together. I'll clear it all out and re-install everything using your tip.
Are they both running both php and MySQL or is one the database server and the other the web server?
MySQL can be horribly fussy about security.

Most MySQL accounts tend to be available on the localhost only. Also the server only listens on "bind-address 127.0.0.1" (not 0.0.0.0). That needs a change to your mysql.cnf file. You've also got to have some accounts set up to work anywhere in your local area network. [I find that phpmyadmin makes that stuff easier. Although you won't find http://127.0.0.1/phpmyadmin on my Apache server, I've moved it to another obscure directory name. I've also removed the mysql root id and added a specially named all powerful user with a strong password.]

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Mon Nov 25, 2013 1:37 am
by williebegoode
Thanks for the tip. It's just that I haven't run into this problem on my other machines or servers. However, I am sure you are right about the conflicts, and I'll see if I can resolve them using your pointers.

Kindest regards,
Bill

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Mon Nov 25, 2013 12:31 pm
by williebegoode
Hi Basingstoke,

Well I managed to remove all of my PHP and MySQL, and I used your tip:

sudo apt-get install php5-mysql

and it would not install. It suggested I update my raspi system, which I did, and still no joy. One of the reasons I got a Raspi was to explore these very kinds of issues (I'm a programmer; not a systems guy) without wrecking one of my other systems or servers which I use for development.

For some reason, my Raspi is the only one I cannot get working with both PHP and MySQL. So, I'm all ears for any further suggestions you have. Worst case scenario is that I re-install the whole system or even get a new SD card.

Is there perhaps a sequence to follow? First PHP or Mysql, should MySQL server go in first? Any help is appreciated.

Kindest regards,
Bill

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Mon Nov 25, 2013 12:43 pm
by DougieLawson
sudo apt-get install mysql-server php5-mysql
should be enough to pull in everything.

The idea of dpkg & apt-get & aptitude is to make that stuff easier. You try to install something you need and those tools resolve the dependencies and install all of the other related stuff.

One tool that does make it all a lot easier is aptitude (sudo apt-get install aptitude && aptitude). It's a menu driven front end to all of that arcane stuff (dpkg, apt-get, etc.) that runs underneath.

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Tue Nov 26, 2013 2:07 pm
by williebegoode
Hello again,

Completely removed all old PHP and MySQL and reinstalled using :

sudo apt-get install mysql-server php5-mysql

Everything seemed to go smoothly on the install. Tested the MySql by creating a new db using LXTerminal, and it works fine. However, I've lost my PHP.

Previously, I had installed PHP and it worked great. See a blog post I made:

http://www.php5dp.com/easy-writer-setup ... /#more-209

My Apache server is still working because I can call the default HTML file, but when I test my PHP, I get:

Code: Select all

<?php
   phpinfo();
?>
Instead of the table that used to appear when I ran it.

Any ideas on fixing this? Should I burn down the whole thing, including Apache server, and start all over using:

sudo apt-get update
sudo apt-get install apache2 php5 php5-mysql mysql-server

Or is there some way I can connect PHP?

Kindest regards,
Bill

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Tue Nov 26, 2013 5:16 pm
by rpdom
Now try sudo apt-get install libapache2-mod-php5 , and see if your page works after that.

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Tue Nov 26, 2013 6:23 pm
by williebegoode
Hello and thanks,

I tried that, and it didn't seem to quite be able to install everything, but it didn't crash either. The Web server still works and I can run HTML over a LAN, but it still acts like PHP is not installed.

Is there some file I can fiddle with to get PHP up and running?

Kindest regards,
Bill

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Tue Nov 26, 2013 6:44 pm
by DougieLawson
williebegoode wrote: Is there some file I can fiddle with to get PHP up and running?
Create /srv/www/tester.php and put

Code: Select all

<?php phpinfo() ?>
in it.

cd /srv/www/
nano tester.php
Then try to run it with: php tester.php
Does that create lots of exciting output?
Or does it moan that php isn't found?
Try php5 tester.php.

When you go to http://127.0.0.1 do you get a web page? Or do you get busted with 404 or 502 or 503?
Does it work with http://127.0.0.1/index.htm or http://127.0.0.1/index.html # one of those should exist on a free Apache install
When you go to http://127.0.0.1/tester.php (which points to /srv/www/tester.php) do you get any output

Take a look in /var/log/apache/access.log and /var/log/apache/error.log
Can you see your attempt to visit those three pages at http://127.0.0.1? Are there any error messages in the error log?
Cut'n'paste them on here.

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Tue Nov 26, 2013 7:38 pm
by williebegoode
Hi Donnie,

There's no 'www' directory in the srv/ directory, and it would not let me create one.

The baffling part of all of this is that when I first installed PHP on Raspi, everything worked fine. However, from reading about the sequence of installation, MySQL should precede PHP, and so PHP was removed and MySQL put in and then followed by re-installing PHP. The MySQL still works fine, but now I cannot connect to PHP, let alone connect PHP to MySql. (Fortunately, I have several of systems where I can work with both, but with Raspberry Pi I learn a good deal more!)

Any other suggestions?

Thanks for both your help and patience. (Especially the latter!)

Kindest regards,
Bill

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Tue Nov 26, 2013 8:00 pm
by DougieLawson
OK, what's defined in /etc/apache2/apache2.conf or /etc/apache2/sites-enabled/*default* for the DocumentRoot directive.

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Tue Nov 26, 2013 8:12 pm
by williebegoode
Hi Donnie,

In etc/apache2/sites-enabled/ is python_games and Desktop.

Kindest regards,
Bill

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Tue Nov 26, 2013 8:29 pm
by DougieLawson
OK. It looks like DocumentRoot is set to /var/www on Raspbian.

So do the experiment above but everywhere I've written /srv/ assume I've written /var/.
If PHP doesn't work you'll get a blank page at http://127.0.0.1/tester.php

So change /var/www/tester.php to:

Code: Select all

<h2>phpinfo starts</h2>
<?php phpinfo() ?>
<h2>phpinfo ends</h2>
then at least you'll get some output.

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Tue Nov 26, 2013 8:59 pm
by williebegoode
Hi Dougie,

That worked. I also tried it remotely on my LAN, and it worked. Some of the other PHP programs I had written earlier also work.

The ones I have in my old PHP folder do not work until I move them to var/www/ I'm going to delete my PHP folder, create a new one and then try again. This is sick fun.

Thanks again for your patient help. Next step is to set up some users for MySQL and tackle that problem.

Kindest regards,
Bill

Re: [SOLVED]Weird connection issue with PHP and Mysql

Posted: Thu Nov 28, 2013 1:06 pm
by williebegoode
Finally!

Everything is working together. I tested the PHP<->MySql with the following OOP PHP:

1. IConnectInfo.php

Code: Select all

<?php
//Filename: IConnectInfo.php
interface IConnectInfo
{
	const HOST ="localhost";
	const UNAME ="userName";
	const PW ="passWord";
	const DBNAME = "dataBaseName";
	
	public static function doConnect();
}
?>
2. UniversalConnect.php

Code: Select all

<?php
ini_set("display_errors","1");
ERROR_REPORTING( E_ALL | E_STRICT );
include_once('IConnectInfo.php');
 
class UniversalConnect implements IConnectInfo
{
	private static $server=IConnectInfo::HOST;
	private static $currentDB= IConnectInfo::DBNAME;
	private static $user= IConnectInfo::UNAME;
	private static $pass= IConnectInfo::PW;
	private static $hookup;
	
	public static function doConnect()
	{
		self::$hookup=mysqli_connect(self::$server, self::$user, self::$pass, self::$currentDB);
		if(self::$hookup)
		{
			echo "Successful connection to MySQL:<br/>";
		}
		elseif (mysqli_connect_error(self::$hookup)) 
		{
    		echo('Here is why it failed: '  . mysqli_connect_error());
		}
		return self::$hookup;
	}
}
?>
3. UseMySQLConnect.php

Code: Select all

<?php
include_once('UniversalConnect.php');
class UseMySQLConnect
{
	private $doConn;
	
	public function __construct()
	{
		try
		{
			$this->doConn=UniversalConnect::doConnect();
			echo "Succesful connection";
			$this->doConn->close();
		}
		catch (Exception $e)
		{
			echo "There is a problem: " . $e->getMessage();
			exit();
		}
	}
}
$worker=new UseMySQLConnect();
?>
The two connection files (IConnectInfo.php and UniversalConnect.php) can be re-used with PHP. With it you can make PHP<->MySQL connections with a single line:

Code: Select all

$this->doConn=UniversalConnect::doConnect();
$this->doConn is a private variable defined as;

Code: Select all

private $doConn
So, once these files are included in the PHP folder using MySql and your user name, password and database name are saved in the IConnectInfo, you're set.

The arduous task of getting PHP/MySql set up in Raspberry Pi is greatly eased if you put in everything in at once using a Raspi package rather than putting them in one at a time.

Also, the fantastic help I got from Dougie Lawson on this forum was invaluable.

Kindest regards,
Bill