Trouble with PHP $connection command and MySQL - php

Probably just because I'm not experienced with this sort of thing, but I downloaded MySQL with Apache running, and I'm working with the following code in a PHP file:
public static $connection = NULL;
private static $host = MYSQL_HOST;
private static $username = MYSQL_USER;
private static $passwd = MYSQL_PASS;
private static $db = MYSQL_DBNAME;
public static function init() {
if(!self::$connection) {
self::$connection = new mysqli(self::$host, self::$username, self::$passwd, self::$db);
}
}
It comes up with this when I open it in Firefox:
trying to connect via unix:///var/mysql/mysql.sock (says this doesn't exist—which, it doesn't)
I replaced MYSQL_HOST with 'localhost', MYSQL_USER with both 'mysql' and 'root' (stupid, yes), MYSQL_PASS with both my system password and NULL, and MYSQL_DBNAME with a few more things (I am having trouble finding out what my database name is called, even with MySQLWorkbench...I started learning this entire field of computing two days ago). It does say that a MySQL server is running on my machine, just not sure how to put the legos together here. Most of the settings are default (port 3306 and such). A test database migration over MySQLWorkBench failed (something to do with not reading the number of rows correctly), but otherwise it was fine and dandy, from what I saw.
Any help would be very welcome!

When you specify localhost as the host name, your computer will try to access the MySQL server using sockets in /var/mysql/mysql.sock. Since that file does not exist, this won't work. However, when you specify 127.0.0.1 as host name, the MySQL connection is set up over TCP/IP.
See also this question.
So the answer is to either find where MYSQL_HOST is defined and change it to be 127.0.0.1, or forget about MYSQL_HOST and just enter 127.0.0.1 instead. The latter is harder to maintain in case you would want to move your site to some other location (server).

Try restarting SQL server. This may recreate the missing .sock file. See here for info on restarting: http://theos.in/desktop-linux/tip-that-matters/how-do-i-restart-mysql-server/

Related

How do I connect my PHP file to an external database?

I was wondering if I may get some help with trying to connect to an external database for one of my PHP config files. This PHP file is from a plugin I downloaded from cartmega, which is supposed to tie-in with our ticketing system called osTicket. When we connect to our DB, data is supposed to be fetched from one of the tables via a protected function and a few commands that were already on the config file.
Now I'm able to connect to my local database, however, I'm only able to connect to that local DB using localhost. I've tried using the hostname of the local server, but for some reason it wasn't pulling the data from my mariadb table structure. I need both the local and external databases because both DB's have different data that needs to populate on our ticketing system.
This is how the connection code is currently setup
protected $parent
private $_db
public function_construct($parent) {
$this->parent = $parent;
$this->_db = mysqli_connect("localhost", "username", "password", "osticket_db")
Now my thinking is that if I want to connect to an external db, then I should do the following
protected $parent
private $_db
private $_db2
public function_construct($parent) {
$this->parent = $parent;
$this->_db = mysqli_connect("localhost", "username", "password", "osticket_db")
$this->_db2 = mysqli_connect("name.name.com", "username", "password", "snipeIT")
So thanks for your guidance everyone. It gave me an idea for what to look for, so I managed to figure it out. I had to grant access to the sql server by granting access to the sql user that is trying to log into the external server. After that I edited the sql .cnf file and added a bind address, once I completed that I tried to allow the ports again, and then ran a few iptables command to allow the IP and port that is trying to access the localserver and external server. After that I was able to connect to the external database from the local database.
Thanks again!
You need to put IP of the external database instead of localhost and you need to allow remote access from the outside database to grant the access. Remote access can be accessed from cPanel.

mysql_real_escape_string not showing error

I am moving my application from Mysql extension to PHP PDO.
I am facing a strange problem.
In my development environment, I have both db server [MySQL] and web server are in single system where as in testing environment web and db servers are in different system.
The following test code runs perfectly in dev environment and fails in test environment.
require "class.DB.php" ;
class DbMaster extends DB
{
public function __construct()
{
$this->Host = "192.168.1.00";
$this->Database = 'test_database';
$this->User = "root";
$this->Password = "12345";
}
}
// Creates the instance
$db = new DbMaster();
$table = mysql_real_escape_string('persons');
$result_array = $db->query("SELECT Id, Age FROM $table WHERE Id >= :Id", array("Id" => 1));
foreach ($result_array as $rec)
{
echo '<br>'.$rec["Id"].' -> '.$rec['Age'];
}
In dev, mysql_real_escape_string should fail, because there is no mysql_connect().
But, mysql_real_escape_string works when there is a mysql server running locally. To test this in dev environment I stopped the local mysql and connected to remote database. Then I got the following error:
Warning: mysql_real_escape_string(): A link to the server could not be established
So with my existing development setup [both web and db server together], I am not able to see the PDO related errors.
Any way to resolve this problem.
mysql_real_escape_string() tries to open a connection to a server with mysql_connect() if no connection exist. The default values for mysql_connect() are "localhost" and "root" without a password.
If you have the root account without a password in your development environment (which is a pretty common setup) this will work without problem, since a connection can be esteblished.
On the live environment on the other hand, the root user hopefully has a password set, so this call will fail.
In this case mysql_real_escape_string() will return false instead of your escaped value.
The solution: Use the mysqli or PDO equivalent of the function. Or open an additional connection using mysql_connect() with valid credentials for the time being so mysql_real_escape_string() can use it.

How can I access PDO in MAMP?

I'm setting up a PDO connection in a test script:
use app\SomeDAO;
class SomeTest extends \PHPUnit_Framework_TestCase
{
protected $db;
public function setUp()
{
$dsn = "mysql:host=localhost;dbname=baseball;user=root;password=root";
$this->db = new PDO($dsn);
}
I'm getting an error:
PDOException: SQLSTATE[HY000] [2002] No such file or directory.
How can I use PDO here?
In Unix based (like linux, bsd, or OS X) systems, with MySQL localhost is secret code for try-to-use-a-socket, unless a you force it via a protocol flag to not do this (and no one ever does this). Just remember localhost usually equals socket file.
If Mysql in your MAMP is running in non-socket mode, you can try replacing the host value with 127.0.0.1 which connects via TCP on via port to the local machine--you'll need to figure out which port it's running on if it's not the default port.
If you look at the MAMP start script
less /Applications/MAMP/bin/startMysql.sh
You can see if it's starting in socket mode, and what file it's using if it has a config param like:
--socket=/Applications/MAMP/tmp/mysql/mysql.sock
You can also investigate what open socket mysql might be using by following the answer in this question: error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
If you're running in socket mode, you need to make sure PDO knows the path to the socket file. One way to do this is specify the unix_socket instead of host in the dsn:
$dsn = "mysql:unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=baseball;user=root;password=root";
I had problem like that at MAMP. My decided it, when I connected with PDO I used next line code:
$this->pdo = new \PDO("mysql:unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock;port=8889;dbname=mydatabase;charset=utf8", 'root', 'root');

Can you use pg_connect in PHP to use ONLY local unix-domain sockets?

Okay, this is something I've been banging my head on for a few weeks now, so just bear with me. When I set up my postgres database, I wanted to connect to it only through the local Unix socket. Just like how I set up my MySQL database, and subsequent PHP scripts I wrote for it. Thus, the bottom of my pg_hba.conf file looked like this:
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all md5
# IPv4 local connections:
#host all all 127.0.0.1/32 md5
# IPv6 local connections:
#host all all ::1/128 md5
I was, and still am, able to interface with my db via the psql command-line utility, and do anything I need to do without issue. However, when I tried to write a simple PHP script to connect to the db, it would always fail:
<?php
$dbhost = "localhost";
$dbname = "postgres";
$dbuser = "postgres";
$dbpassword = "####";
$conn_string = "host=$dbhost dbname=$dbname user=$dbuser password=$dbpassword";
$dbconn = pg_connect($conn_string);
if($dbconn)
{
echo "<p>Win!</p>";
}
else
{
echo "<p>Connect failed!</p>";
exit();
}
pg_close($dbconn);
?>
I was absolutely dumbstruck for weeks as to why PHP wouldn't establish a simple Unix socket connection, especially after writing quite a few scripts with the mysqli library for my MySQL db that used local connections! However, I finally un-commented the line associated with the loop-back address, and like magic it suddenly worked! This indicates to me that when 'localhost' is passed as the host parameter of pg_connect, it uses the loop-back interface, rather than just the local Unix socket.
It's not the end of the world, but is there a way to use PHP in a way so that it connects via a local Unix socket, or does it not support this type of connection with postgresql?
Set host in the connection string to the value of the directory that holds the unix socket.
So if the socket is at /var/run/postgresql/psql.sock then try:
pg_connect("host=/var/run/postgresql dbname=..etc...");
Other comments on the PHP docs page for pg_connect indicate that you can also leave out the host key/value completely and it will work - but I haven't tried.:
http://php.net/manual/en/function.pg-connect.php

public webserver trying to query sqlserver on internal network with private IP

I am using php to send a query to an existing database to use existing login credentials for a webbased program to allow access to a members section page. My web server is public and has a public ip as well as a private ip. However, my sql server is sitting on the local lan and does not have a public ip. I am very new to php, but I feel I have a done a good job writing it. the code works amazingly when I hosted the site for internal use with a dummy database on my pc. I set up Apache on my pc to run the php code and set up a sql database for testing purposes. I could access the site and login and out from any other computer in the office, by typing in my 192.168.x.x into the web browser.
Now that the site is moved to the web server and I am linking to an active database on another server it doesnt want to work. I am pretty sure i dont have any coding erors causing this its a configuration issue. I am wondering what ports should be open where? and will existing DB users be able to query the DB from a remote private ip? I realize this may be a beginners question, but I have looked everywhere for days now and my brain is fried. I need a basic checklist of the main things to look for or set when establishing this type of connection.
Website is running on 192.168.1.1 with public ip of 173.72.173.x
SQL DB is running on 192.168.1.2
I log into the sql engine on the sql server with 'user' and 'password' so my config file i use:
$server = "192.168.1.2:3306"; // server to connect to.
$database = "myusers"; // the name of the database.
$db_user = "user"; // mysql username to access the database with.
$db_pass = "password"; // mysql password to access the database with.
$table = "dbo.users"; // the table that this script will set up and use.
And I call it into every file that need to query anything.
So are theses setting right? Or do I need to create another user on my sql engine to access the db from a remote host? and what about ports? sql server has 3306 opened, but that's it?
If you are using MySQL (you mentioned port 3306), you will most likely want to check the my.cnf configuration file on the MySQL server, and have it allow remote connections.
Just do a fast search for bind-address = 127.0.0.1 and comment it by putting a hash# in front of it and disable interface binding.
Since you did not specify the OS you are using, I can't know for sure whether it may be bound to a specific NIC or not. Try it yourself.

Categories