Issue with MySQL connection inside class - php

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/

Related

How to execute more than one statement in try command

I am trying to establish a PDO connection using the try block and then printing a success message after the connection gets established. My code is as follows:
index.php :
<?php
require_once './vendor/autoload.php';
$con = new \app\db\Connect();
if ($con)
{
echo 'connection successful.';
}
connect.php
<?php
namespace app\db;
class Connect
{
public function __construct()
{
// set the connection variables
$host = 'localhost';
$dbname = 'pdoposts';
$username = 'root';
$password = 'root';
// create the DSN
$dsn = 'mysql:host=' . $host . ';dbname=' .$dbname;
// create PDO connection
try {
static $con;
$con = new PDO($dsn, $username, $password);
} catch(Exception $e) {
echo $e->getMessage();
}
return $con;
}
}
My problem is that there is no way for me to use the $concreated in the try - catch command in the index.php file. I am very sorry if this question seems very basic and elemental one, but please help me understand how it can work. Thank you very much in advance.
Accoring to the answer below:
The solution here on stackoverflow
I just added the backslash right before PDO and made it to be \PDO and it is now working properly. The link below can help understanding PHP Callbacks and how they work better:
Using namespaces: fallback to global function/constant
I should have kept in mind the namespace from which I wanted to use PDO from. In this case, using a \ would tell php to use PDO from the Global Namespace and not from the namespace from which the code runs in (app\db).

Unable to connect PHP application with MySQL

From a friend, I got a website (zip file) with PHP and HTML files in it. I also got a SQL script from him. Now what I'm trying to do is run the application on localhost (Xampp apache server) and the website does load, but it looks like I can't connect to the database.(I did import the SQL script and it worked, But I'm still getting this error) This is an error for example that I'm receiving on the home page:
Connection failed: SQLSTATE[HY000] [1045] Access denied for user 'dewaai'#'localhost' (using password: YES)
Notice: Undefined index: logged in C:\xampp\htdocs\deWaai\includes\header.php on line 14
The name of the database is 'dewaai'
The username is: root
And I think there is no password...
This is the connection.php file:
<?php
session_start();
include "db.php";
$db = new db();
$db->setDB("localhost", "dewaai", "dewaai", "dewaai");
$db->connect();
?>
These are database functions in the db.php file:
<?php
class db {
private $conn;
private $servername;
private $dbuser;
private $dbpass;
private $dbname;
function setDB($servername, $dbuser, $dbpass, $dbname) {
$this->servername = $servername;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
$this->dbname = $dbname;
}
function connect() {
try {
$this->conn = new PDO("mysql:host=$this->servername;dbname=$this->dbname", $this->dbuser, $this->dbpass);
// set the PDO error mode to exception
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
Does anyone know how I can fix this so the database runs the application?
I really don't know why I'm getting that error.
Any kind of help is appreciated, thx
There is problem with your username or password.
$db->setDB("localhost", "root", "", "dewaai");
Try this it will help you to connect with your database
Hi the issue clearly from the error message states that your username and password given in connection.php file is incorrect.
The format for DB connection is
$db->setDB( Database host IP address or DNS name , Username , Password, DatabaseName);
From what you said i guess connection.php file should be
<?php
session_start();
include "db.php";
$db = new db();
$db->setDB("localhost", "root", "", "dewaai");
$db->connect();
?>
And i think your PDO connection might have an issue as well. It should be
$this->conn = new PDO('mysql:host='.$this->servername.'; dbname='.$this->dbname, $this->dbuser, $this->dbpass);
Hope this helps.

"No database selected" error from mysql db and myphp site

I keep getting 'No database selected' everytime I login to my php website. The backend is MySQL database. The following code is in my database.php file. I appreciate any help on the issue. Thank you.
{
public $conn;
function __construct($server, $user_name, $pass, $db) {
$this->conn = mysql_connect($server, $user_name, $pass);
mysql_select_db($db, $this->conn);
}
function __destruct() {
mysql_close($this->conn);
}
}
What do you get if you do this?
mysql_select_db($db, $this->conn)
|| die ("select_db failed: " . mysql_error($this->conn));
It may halp you understand what's going wrong.
Also please stop using the mysql_ apis.

Cannot connect PHP to Postgres

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.

Including php file with database connection error

I want a generic php file with all the database info (dbname,host,username,password)
But when I include the page, in like index.php I get this error:
Access denied for user 'apache'#'localhost' (using password: NO)
connect.php
<?php
class dbconnect{
private $host = '**';
private $user = '**';
private $pass = '**';
public $con;
function Connect($db = '**') {
if($db=='**'){
$this->host="localhost";
$this->user="**";
$this->pass="**";
$db="**";
}else{
$this->host="**";
$this->user="**";
$this->pass="**";
}
$this->con = mysql_connect($this->host,$this->user,$this->pass);
if (!$this->con)
{
die('Could not connect: ' . mysql_error());
}
$blaa = mysql_select_db($db, $this->con);
mysql_query("SET NAMES UTF8");
return $blaa;
}
function Disconnect() {
//$this->con = mysql_connect($this->host,$this->user,$this->pass);
mysql_close();
}
}
?>
I am sure the ** information is correct because when I specify it as:
$con=mysqli_connect("example.com","example","password","my_db");
In index.php it works
It's important to note, your test case doesn't actually prove it works.
What does this output:
$conn = mysql_connect("example.com", "user", "password");
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
As you won't necessarily get the information that's failing it without that.
To top that off, let's simplify your class a little bit for debugging purposes:
class dbconnect
{
private $host = '**';
private $user = '**';
private $pass = '**';
public $con;
public function Connect($host = "localhost", $user = "root", $pass = "")
{
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->con = mysql_connect($this->host, $this->user, $this->pass);
if (!$this->con) {
die('Could not connect: ' . mysql_error());
}
$blaa = mysql_select_db($db, $this->con);
mysql_query("SET NAMES UTF8");
return $blaa;
}
public function Disconnect()
{
mysql_close($this->con);
}
}
Now what do you get when you do
$db = new dbconnect("example.com", "user", "password");
Be sure you're using credentials that work, and that you're not running into issues such as default values or incorrect variable assignment through these methods.
Now, if you don't want to provide the values, you can simply:
$db = new dbconnect();
Public Service Announcement
Check out PHP's PDO or at minimum (but really, just use PDO) the mysqli alternative. PHP's mysql extension is NOT secure, and you should not be using it in any environment, ever.
If the connection information are correct, check your MySQL User's host access permission:
SELECT user, host FROM mysql.user
If "localhost" is set, then the user can only access the database locally, otherwise "%" will open access.
Usually it is an issue with the connection credentials.
Check that you can log into your mysql using the details you have set for that website.
mysql -u apache -p
It will then ask you for the password.
If that login does not work, then you have a problem with that user's mysql account.
You use incorrect parameters for accessing. Just dump variables which at the line $this->con = mysql_connect($this->host,$this->user,$this->pass);. You can use debugger or echo, print instructions.
Furthermore use PDO extension for accessing to databases. It's better!
Why shouldn't I use mysql_* functions in PHP?

Categories