Cannot connect PHP to Postgres - php

I have had the hardest time getting PHP to talk to Postgres SQL. Here is my setup:
Ubunu Desktop 13.10
PHP 5.5.3
Postgres 9.1.10
Apache 2.4.6
Netbeans 7.4 with xdebug
Everything is working fine. I am able to enter and retrieve data in the Postgres Database fine from the command line but not in PHP. Here are the lines of code that I am using to connect:
$dbConn = new softwareDB('localhost', 'postgres', 'root', 'softwareuitest');
...
$results = $dbConn.getClients();
while($client = pg_fetch_result($results)){
echo '<option value=\"'.$client.'\">'.$client.'</option>';
}
The softwareDB class constructor is as follows:
Class softwareDB {
private $conn;
function _construct($host, $user, $password, $dbname) {
$connectString =
'host=' . $host .
' port=5432' .
' user=' . $user .
' password=' . $password .
' dbname' . $dbname;
$this->conn = pg_connect($connectString);
}
...
public function getClients() {
global $conn;
return pg_query($conn,'getClients','SELECT * FROM clients');
}
...
}
When running the code nothing happens... I see nothing in the Apache log file, nothing in the postgres log, nothing from the debugger, and only HTML (without query data) in the output.
I cannot post images yet but here are the details about Postgres from phpInfo():
PDO
PDO Drivers | pgsql
pdo_pgsql
version 9.1.9
module 1.0.2
revision $id$
pgsql
PostgreSQL(libpq) | PostgreSQL 9.1.9 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu/Linaro 4.8.1-10ubuntu1) 4.8.1, 64-bit
allow_persistent is on

You have two main issues. The first is a typo; PHP class instance methods are called via the arrow operator. It should be...
$results = $dbConn->getClients();
The second is your use of global $conn. You don't have a variable named $conn, global or not. What you do have is a member property $conn which you may reference by prefixing it with $this, eg
public function getClients() {
return pg_query($this->conn, 'SELECT * FROM clients');
}
Looking further, I would suggest that if you're going to abstract DB details away in your softwareDB class, you might as well do it completely. I'd go with something like this
class softwareDB {
private $conn;
public function __construct($host, $user, $password, $dbname) {
$this->conn = pg_connect(sprintf('host=%s port=5432 user=%s password=%s dbname=%s',
$host, $user, $password, $dbname));
if ($this->conn === false) {
throw new Exception(pg_last_error());
}
}
public function getClients() {
$result = pg_query($this->conn, 'SELECT * FROM clients');
return pg_fetch_all($result);
}
}
I'm not too familiar with the PostgreSQL Functions so you may need to tweak this but the general idea is that code using your softwareDB class doesn't need to know anything about postgres or other DB operations.

Related

PHP: Using an SSH class inside a different class constructor

I am still rather green when it comes to PHP. Not quite sure where the issue comes in here. I am using a rather simple SSH2 class (https://www.phpclasses.org/browse/file/34450.html) that works well for my needs, or has until this point.
This is the class I have set up. I put the ssh connection into the constructor, and attempt to use $this->ssh throughout the rest of the class functions.
include ("/var/www/html/class/ssh2_class.php"); ##https://www.phpclasses.org/browse/file/34450.html
class crontab {
function __construct($host,$params) {
$this->host = $host;
$this->pubkey = $params['pubkey'];
$this->privkey = $params['privkey'];
$this->usr = $params['user'];
$this->port = $params['port'];
$this->secret = $params['secret'];
$this->ssh = new SSH2($this->host)
or die ("Unable to connect to ". $this->host ."!");
$this->ssh->auth($this->usr, $this->pubkey, $this->privkey, $this->secret)
or die ("Unable to authenticate to ". $this->host ."!");
}
function show($sudo) {
if ($sudo) { $sudo = "sudo"; } else { $sudo = ""; }
$cmd = $sudo."$sudo crontab -l";
$this->ssh->exec($cmd);
return ($this->ssh->output);
}
The issue I run into is in the return line of the show function above. The $this->ssh->exec($cmd); works without issue; I've tested it by simply touching a file.
PHP Notice: Undefined property: SSH2::$output in /home/mackay_c/scripts/deploy/deploy.class.php on line 26
I've searched around the web, and am at a bit of a loss as to why this occurs. The 'output' function in the SSH2 class is:
function output() {
return stream_get_contents($this->stream);
Any help would be appreciated.
return ($this->ssh->output())

Issue with MySQL connection inside class

I have a MySQL class that I use to connect to MySQL. But after doing the upgrade of PHP to 5.4.16, it doesn't work any more. Can anyone help with it?
Below is the code that I use. Whenever I try to connect it gets into the error part.
final class MySQL {
private $connection;
public function __construct($hostname, $username, $password, $database) {
if (!$this->connection = mysql_connect($hostname, $username, $password)) {
exit('Error: Could not make a database connection using ' . $username . '#' . $hostname);
}
}
SOLVED : Did the following on command prompt and
setsebool -P httpd_can_network_connect=1
More details here :
https://maanasroyy.wordpress.com/2015/06/04/php-cant-connect-to-mysql-with-error-13-but-command-line-can/

PDO Fatal error: Call to a member function prepare() on a non-object (using classes)

I am receiving the following error when loading my index page:
Fatal error: Call to a member function prepare() on a non-object in /Applications/MAMP/htdocs/parse/helloworld/helloworld/libraries/Database.php on line 32
I will place all of the relevant code below, sorry for the length but it should be fairly straight forward to read. The short version is I am practicing PDO and PHP classes so I am remaking an existing project I had on a different machine. (which is why a there is a lot of calls in the index file which acts more like a controller).
I am pulling my hair out here because it works on my other machine and from what i can tell the two projects are identical... I am just getting this error. I had this in my previous project, but that was because I had misspelled the database in the config file... I am 100% positive I did not do that again but I don't know what else I missed -- clearly the PDO class is not being made if I var_dump it returns null... Any and all help would be greatly appreciated (especially if it is in regards to my PDO class style I am just following a blog which seemed to make sense when it worked).
EDIT:
After some debugging it was clear that the try block in the database class was failing because a connection could not be established. This was clear after running $this->error = $e->getMessage() which returned:
string(119) "SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2)"
As the accepted answer below states the error indicates localhost trying to connect via a unix socket and mysqld not being able to able to accept unix socket connections.
So the original error leads to the ultimate question of: how do you connect to a unix socket when mysqld is not accepting unix socket connections and/or why does mysqld not accept unix socket connections?
End EDIT.
This is my (relevant) PDO class:
<?php
class Database {
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $dbh;
private $error;
private $stmt;
public function __construct() {
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array (
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try {
$this->dbh = new PDO ($dsn, $this->user, $this->pass, $options);
} // Catch any errors
catch ( PDOException $e ) {
var_dump($dsn);
$this->error = $e->getMessage();
}
}
public function query($query) {
$this->stmt = $this->dbh->prepare($query);
}
This is the index file that gets called
<?php
require('core/init.php');
//Create objects...
$type = new Type;
$post = new Post;
$group = new Group;
$follower = new Follower;
//Create template object
$template = new Template('templates/front.php');
$template->types = $type->getAllTypes();
$template->groups = $group->getAllGroups();
$template->posts = $post->getAllPosts();
$template->replies = $post->getReplies();
$template->followers = $follower->getAllFollowers();
echo $template;
and these are the other relevant files:
config --
<?php
//DB Params
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "root");
define("DB_NAME", "dobbletwo");
define("SITE_TITLE", "Welcome To Dooble!");
init --
//include configuration
require_once('config/config.php');
//helper functions
require_once('helpers/photo_helper.php');
require_once('helpers/system_helper.php');
//Autoload Classes
function __autoload($class_name){
require_once('libraries/'.$class_name . '.php');
}
for the sake of brevity (which may be far gone at this point I will only show one of the classes i load to prove that I am constructing the db(type, post, group, follower, template...)
<?php
class Type {
//Initialize DB variable
public $db;
/*
* Constructor
*/
public function __construct(){
$this->db = new Database;
}
the mysql libraries seem to interpret localhost as meaning you want to connect via a unix socket. your error indicates your mysqld isn't setup to accept unix socket connections.
to connect via tcp/ip instead, change define("DB_HOST", "localhost"); to define("DB_HOST", "127.0.0.1");

OOP - Connecting to database via __construct [duplicate]

This question already has an answer here:
PHP: mysql_connect not returning FALSE
(1 answer)
Closed 8 years ago.
I'm very new to OOP and am trying to learn it. So please excuse my noobness. I'm trying to connect to mysql and to test whether the connection is successful or not, I'm using if-else conditions.
Surprisingly, the mysql_connect is always returning true even on passing wrong login credentials. Now I'm trying to figure out why it does and after spending about 20 minutes, I gave up. Hence, I came here to seek the help of the community. Here is my code:
class test
{
private $host = 'localhost';
private $username = 'root2'; // using wrong username on purpose
private $password = '';
private $db = 'dummy';
private $myConn;
public function __construct()
{
$conn = mysql_connect($this->host, $this->username, $this->password);
if(!$conn)
{
die('Connection failed'); // this doesn't execute
}
else
{
$this->myConn = $conn;
$dbhandle = mysql_select_db($this->db, $this->myConn);
if(! $dbhandle)
{
die('Connection successful, but database not found'); // but this gets printed instead
}
}
}
}
$test = new test();
Please don't use the mysql_* functions, there are many, many reasons why - which are well documented online. They are also deprecated and due to be removed.
You'd be much better off using PDO!
Also I'd strongly advise abstracting this database code into a dedicated database class, which can be injected where necessary.
On-topic:
That code snippet seems to work for me, have you tried var_dumping $conn? Does that user have correct rights?
I also hope that you don't have a production server which allows root login without a password!
Ignoring the fact that you're using mysql_* functions rather than mysqli or pdo functions, you should utilise exceptions in OOP code rather than die(). Other than that, I can't replicate your problem - it may be that your mysql server is set up to accept passwordless logins.
class test
{
private $host = 'localhost';
private $username = 'root2'; // using wrong username on purpose
private $password = '';
private $db = 'dummy';
private $myConn;
public function __construct()
{
// returns false on failure
$conn = mysql_connect($this->host, $this->username, $this->password);
if(!$conn)
{
throw new RuntimeException('Connection failed'); // this doesn't execute
}
else
{
$this->myConn = $conn;
$dbhandle = mysql_select_db($this->db, $this->myConn);
if (!$dbhandle)
{
throw new RuntimeException('Connection successful, but database not found'); // but this gets printed instead
}
}
}
}
try {
$test = new test();
} catch (RuntimeException $ex) {
die($ex->getMessage());
}

Should objects be created chronologically as class defined?

I am having a strange error while creating objects. While I create an objects in chronological orders as classed defined, it is going on good. But when I change the order or object creation, it gives error.
The classes I am using are as follows:
<?php
class dbClass{
private $dbHost, $dbUser, $dbPass, $dbName, $connection;
function __construct(){
require_once("system/configuration.php");
$this->dbHost = $database_host;
$this->dbUser = $database_username;
$this->dbPass = $database_password;
$this->dbName = $database_name;
}
function __destruct(){
if(!$this->connection){
} else{
mysql_close($this->connection);
}
}
function mysqlConnect(){
$this->connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die("MySQL connection failed!");
mysql_select_db($this->dbName,$this->connection);
}
function mysqlClose(){
if(!$this->connection){
} else{
mysql_close($this->connection);
}
}
}
class siteInfo{
private $wTitle, $wName, $wUrl;
function __construct(){
require_once("system/configuration.php");
$this->wTitle = $website_title;
$this->wName = $website_name;
$this->wUrl = $website_url;
}
function __destruct(){
}
function showInfo($keyword){
if($keyword=="wTitle"){
return $this->wTitle;
}
if($keyword=="wName"){
return $this->wName;
}
if($keyword=="wUrl"){
return $this->wUrl;
}
}
}
?>
The problem is when I create objects in the following order, it is working perfectly:
include("system/systemClass.php");
$dbConnection = new dbClass();
$dbConnection -> mysqlConnect();
$siteInfo = new siteInfo();
But if I change the order to following
include("system/systemClass.php");
$siteInfo = new siteInfo();
$dbConnection = new dbClass();
$dbConnection -> mysqlConnect();
It gives error!
Warning: mysql_connect() [function.mysql-connect]: Access denied for user '#####'#'localhost' (using password: NO) in /home/#####/public_html/#####/system/systemClass.php on line 19
MySQL connection failed!
Your problem comes from the unconventional use of a configuration file that is read ONCE, but should be used in all classes.
When you instantiate the dbclass first, the configuration is read, probably variables get assigned, and you use these in the constructor.
After that, instantiating siteinfo will not read that file again, which is less harmful, because you only end up with an empty object that does return a lot of null, but does work.
The other way round, you get a siteinfo object with all the info, but a nonworking dbclass.
My advice: Don't use a configuration file that way.
First step: Remove the require_once - you need that file to be read multiple times.
Second step: Don't read the file in the constructor. Add one or more parameters to the constructor function and pass the values you want to be used from the outside.
Info: You can use PHP code files that configure stuff, but you shouldn't define variables in them that get used outside. This will work equally well:
// configuration.php
return array(
'database_host' => "127.0.0.1",
'database_user' => "root",
// ...
);
// using it:
$config = require('configuration.php'); // the variable now has the returned array

Categories