Need some help debugging this PHP - mysql

I coded this up a bit ago, but it's not working.
I realize I could do this simpler, but I'm trying to use OOP.
So here is the code..
database.class.php
<?php
class config {
public $host;
public $user;
public $pass;
function __construct($host=NULL,$user=NULL,$pass=NULL) {
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
}
function __destruct() {}
}
class database {
private $host;
private $user;
private $pass;
private $config;
function __construct($config) {
$this->config = $config;
}
function __destruct() {}
public function openCon() {
mysql_connect($this->host,$this->user,$this->pass);
if (mysql_errno()) {
printf('Failed to connect: %s', mysql_error());
} else {
echo 'Connected to DB successfully.<br/><br/>';
}
}
public function closeCon() {
try {
mysql_close();
echo 'Successfully closed connection.<br/><br/>';
} catch (exception $e) {
echo $e;
}
}
}
?>
index.php
<?php
include('db.class.php');
$con = new config('localhost','root','');
$etc = new database($con);
$etc->openCon();
mysql_select_db('tester') or die(mysql_error());
$query1 = mysql_query('SELECT * FROM person') or die(mysql_error());
$rows = mysql_fetch_array($query1) or die(mysql_error());
echo 'First: ' . $rows['First'];
echo 'Age:' . $rows['Age'];
$etc->closeCon();
?>
I'm sure there are blaring errors in this. Could anyone help me find and fix them?
It says: Access denied for user ''#'localhost' to database 'tester'
Not sure why.
I specified root as the user, but it came back with '' as the user I requested to use.
It got the host and the database right.
There is no password to my local root user, so...
Any ideas?

Okay, the problem is that the host, user and password are never set. Look in the database constructor. You only set the configuration.
Either set the private database properties somehow, or use the configuration object in openCon().
Or, even better, just scrap the config object. Right now it plays no significant role. Just change the database constructor like the following and be done with it:
function __construct($host, $user, $pass) {
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
}
Finally, if the __destruct() method does not do anything then you do not need to include it.

Your every thing is correct just you need to change in your database class. You pass $config as an object to the constructor of the database class so to access the variable from that object you need little change. It should be
class database {
private $host;
private $user;
private $pass;
private $config;
public $Connectionlink;
function __construct($config) {
$this->host = $config->host;
$this->user = $config->user;
$this->pass = $config->pass;
}
// function __destruct() {} as your destruct function doing noting so you need not to include this.
public function openCon() {
$this->Connectionlink= mysql_connect($this->host,$this->user,$this->pass);
if (mysql_errno()) {
printf('Failed to connect: %s', mysql_error());
} else {
echo 'Connected to DB successfully.<br/><br/>';
}
}
public function closeCon() {
try {
mysql_close();
echo 'Successfully closed connection.<br/><br/>';
} catch (exception $e) {
echo $e;
}
}
}
mysql_select_db need two parameters, so it should be
mysql_select_db('tester', $etc->Connectionlink) or die(mysql_error());

just try to navigate to your mysql directory using cmd
in xampp its "C:\xampp\mysql\bin"
and then type
"mysql -u root" and check whether you are getting access

Related

Can i connect 2 MySql databases to an application developed in simple MVC Framework

Im developing an application where we are in need to connect to two databases. And the application is developed in PSR Framework. I can easily connect one application. But for the second one, its really tough for me to comprehend and do them. Can someone help me in connecting that?
This is a database configuration file.
{
"current_config":"local",
"current_config2":"local2",
"configs":{
"local":{
"database":"xxx",
"username":"root",
"password":"root",
"host":"localhost"
},
"local2":{
"database":"mobi",
"username":"root",
"password":"root",
"host":"localhost"
}
}
}
This is how i connected my database with my application.
class CyberzoDatabase extends Cyberzo{
protected $dbconn = false;
protected $dbconn2 = false;
public function __construct(){
//Start Database Connection
$this->dbconn = $this->dbConnect();
$this->dbconn2 = $this->dbConnect2();
}
public function connection(){
return $this->dbconn;
return $this->dbconn2;
}
public function dbConnect(){
$connection = false;
$databaseConfig = $this->getConfig("database");
$cc = $databaseConfig['current_config'];
$currentConfig = $databaseConfig['configs'][$cc];
if(!empty($currentConfig)){
try {
$conn = new mysqli($currentConfig['host'],
$currentConfig['username'], $currentConfig['password'],
$currentConfig['database']);
if($conn->connect_errno==0){
//Connected.
$connection = $conn;
}
else{
//Connection error.
echo $conn->connect_error;exit;
}
} catch (Exception $e) {
//throw $e->getMessage();
echo "Unable to connect database.";exit;
}
}
return $connection;
}
public function dbConnect2(){
$connection = false;
$databaseConfig = $this->getConfig("database");
$cc = $databaseConfig['current_config2'];
$currentConfig = $databaseConfig['configs'][$cc];
if(!empty($currentConfig)){
try {
$conn = new mysqli($currentConfig['host'],
$currentConfig['username'], $currentConfig['password'],
$currentConfig['database']);
if($conn->connect_errno==0){
//Connected.
$connection = $conn;
}
else{
//Connection error.
echo $conn->connect_error;exit;
}
} catch (Exception $e) {
//throw $e->getMessage();
echo "Unable to connect database.";exit;
}
}
return $connection;
}
public function __destruct(){
//Close Database connection
if($this->dbconn){
$this->dbconn->close();//Connection closed.
}
//Close Database connection
if($this->dbconn2){
$this->dbconn2->close();//Connection closed.
}
}
}
}

how to group the functions in class

i am new to PHP how to group functions inside a class and use it in other pages to reduce typing this is for single page what if i use multiple pages with pageination
this is my coding
<?php
include ('conn.php');
class sel
{
function sell()
{
if(isset($_POST['submit']))
{
$id=$_POST['id'];
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$result = $myDBObject -> select('*', 'admin', 'username = "'.$username.'" and
password ="'.$password.'"');
$x = $rdata['id'];
echo $x;
$_SESSION['username'] =$id;
echo $_SESSION['username'];
if(! $rdata)
{
echo "Enter your username and password correctly";
}
else
{
echo '<script type="text/javascript">
document.location="list.php";
</script>';
}
}
}
}
$myDBObject = new sel();
$myDBObject->sell();
?>
and my connection.php code is
<?php
class DBConnect
{
private $host = 'localhost';
private $user = 'root';
private $pass = '';
private $db = 'enquiry';
public function __construct(){
$conn = mysql_connect($this -> host, $this -> user, $this -> pass);
$sql = mysql_select_db($this -> db, $conn) or die(mysql_error());
}
private function select($select, $table, $where){
$sql = "select ".$select." from ".$table." where ".$where;
$result = mysql_query($sql);
return $rdata = mysql_fetch_array($result);
}
}
$myDBObject = new DBConnect();
$myDBObject->__construct();
$myDBObject->select($select, $table, $where);
?>
if i did like this i get this error what did i do wrong in code
Fatal error: Call to private method DBConnect::select() from context '' in C:\xampp\htdocs
\Raj\cform\conn.php on line 23
You can use database class as mentioned below
class DBConnect
{
private $host = 'localhost';
private $user = 'user';
private $pass = 'pass';
private $db = 'mydb';
public function __construct(){
$conn = mysql_connect($this -> host, $this -> user, $this -> pass);
$sql = mysql_select_db($this -> db, $conn) or die(mysql_error());
}
// select query
private function select($select, $table, $where){
$sql = "select ".$select." from ".$table." where ".$where;
$result = mysql_query($sql);
return $rdata = mysql_fetch_array($result);
}
// update query
private function update($update, $table, $where){
// code here
}
}
When required, create object of the class and call functions as below
require 'dbConnect.php'; // assuming, you have included the database class in this file
$myDBObject = new DBConnect();
$username = mysql_real_escape_string($_POST['username']); // mysql escaping
$password = mysql_real_escape_string($_POST['password']); // mysql escaping
// select required data
$result = $myDBObject -> select('*', 'admin', 'username = "'.$username.'" and password = "'.$password.'"');
The function described in the class above are for demonstration purpose. You can include other functions in the class along with data escaping functionality.
FYI: mysql is deprecrated. Use mysqli or PDO instead. The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
// Hi,
class ClassName {
static function funcName1(){
funcBody1;
}
static function funcName2(){
funcBody2;
}
}
// to use functions juste do :
ClasseName::funcName1();
ClasseName::funcName2();

PDO query failure

I have a problem with my PDO class. I just have started learning OOP and I don't really know where I made a mistake
My class code:
<?php
class admin
{
private $host = 'mysql:host=localhost;dbname=db501865';
private $username = 'root';
private $password = 'root';
private $conn;
public function connect() {
try {
$conn = new PDO($this->host, $this->username, $this->password);
} catch ( PDOException $e ) {
die( 'Connection failed: ' . $e->getMessage() );
}
return $conn;
}
public function disconnect( $conn ) {
$conn = '';
}
public function listReal()
{
$this ->connect();
$real = $conn->query('SELECT * FROM `real`');
echo '<ul>';
foreach ($real as $row)
{
echo'<li><img src="'.$row['image'].'"></li>';
}
$real -> closeCursor();
echo'</ul>';
}
}
?>
and after executing following code I have 500 error in my browser.
$db = new admin;
$db -> listReal();
Where I made a mistake?
You have to use $this->var_name for your member variables.
Also there is no need to connect if you are already connected.
class admin
{
private $host = 'mysql:host=127.0.0.1;dbname=test';
private $username = 'root';
private $password = 'local#pass';
private $conn;
public function connect() {
if($this->conn) return;
$this->conn = new PDO($this->host, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function disconnect( $conn ) {
$conn = '';
}
public function listReal()
{
$this ->connect();
$real = $this->conn->query('SELECT * FROM `real`');
echo '<ul>';
foreach ($real as $row)
{
echo'<li><img src="'.$row['user_id'].'"></li>';
}
$real -> closeCursor();
echo'</ul>';
}
}
try{
$db = new admin;
$db -> listReal();
} catch(Exception $e) {
echo 'error: '.$e->getMessage();
}

unserialize pdo mysql error - invalid data source name

I have these classes below for my online store.
This super class holds all common methods used by the child classes.
class grandpa
{
public function test1($string)
{
return $string;
}
}
So do the PDO connection,
class database_pdo extends grandpa
{
protected $connection = null;
protected $dsn,$username,$password;
public function __construct($dsn,$username,$password)
{
$this->dsn = $dsn;
$this->username = $username;
$this->password = $password;
$this->get_connection();
}
public function get_connection()
{
try
{
$this->connection = new PDO($this->dsn, $this->username, $this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
$this->get_error($e);
}
}
public function __sleep()
{
return array('dsn', 'username', 'password');
}
public function __wakeup()
{
$this->get_connection();
}
public function get_error($e)
{
$this->connection = null;
die($e->getMessage());
}
public function __destruct()
{
$this->connection = null;
}
}
I have this class extend from pdo for other common methods that require pdo connection,
class papa extends database_pdo
{
protected $connection = null;
public function __construct($connection)
{
$this->connection = $connection;
}
public function test2($string)
{
return $string;
}
}
The child classes,
class kido_1 extends papa
{
public function __construct($connection)
{
parent::__construct($connection);
}
public function test3($string)
{
return $string;
}
}
How it use the classes above,
# Host used to access DB.
define('DB_HOST', 'localhost');
# Username used to access DB.
define('DB_USER', 'xxx');
# Password for the username.
define('DB_PASS', 'xxx');
# Name of your databse.
define('DB_NAME', 'xxx');
# Data source name.
define('DSN', 'mysql:host='.DB_HOST.';dbname='.DB_NAME);
$connection = new database_pdo(DSN,DB_USER,DB_PASS);
$kido = new kido($connection);
$_SESSION['cart'] = serialize($kido);
$kido = unserialize($_SESSION['cart']);
print_r($kido->test3('hello'));
I get this error,
invalid data source name
It is caused by unserialize() that I need it for my cart data...
How can I fix this? Or a better way of rewrite these classes?
Your papa::connection is a PDO object. Therefore, when you are trying to serialize $kido, you are trying to serialize a resource, which is not possible.
Try adding a $this->connection = null; in your database_pdo::__sleep() method.
a solution I think...
class papa extends grandpa
{
protected $connection = null;
public function __construct($connection)
{
$this->connection = $connection;
}
public function test2($string)
{
return $string;
}
}

mysql_close(): supplied argument is not a valid MySQL-Link resource

Here's what I'm trying to do: I've got a db.php file that does all the db manipulation.
It has 2 static methods, connect and deconnect.
In my other file i simply use db::connect() and db::deconnect(). The mysql_close($con) in the deconnect method just doesn't know who $con is.
Since I don't want to instantiate my class static is the only way to go.
Declaring 'private $con' in class db doesn't seem to have an effect.
Any ideas?
class db {
public static function connect() {
$dbData = parse_ini_file($_SERVER['DOCUMENT_ROOT'].'/config.ini');
$con = mysql_connect($dbData['host'],$dbData['user'],$dbData['pass']);
$db = mysql_select_db($dbData['db']);
if ((!$con) || (!$db))
return 0;
else return 1;
}
public static function deconnect() {
mysql_close($con);
}
}
In deconnect, $con is out of scope.
You should make it a static member, like this:
class db {
static $con;
public static function connect() {
$dbData = parse_ini_file($_SERVER['DOCUMENT_ROOT'].'/config.ini');
self::$con = mysql_connect($dbData['host'],$dbData['user'],$dbData['pass']);
$db = mysql_select_db($dbData['db']);
if ((!self::$con) || (!$db))
return 0;
else return 1;
}
public static function deconnect() {
if( !isset( self::$con ) ) return;
mysql_close( self::$con );
}
}
The message makes sense as $con is out of scope in your deconnect() method (deconnect...?).
Use a static data member
class db {
static $con;
}
Access it through self::$con.
Well, it seems to me that $con is a local variable (local to the method connect). Thus, when you call mysql_close, most likely $con is undefined. Try declaring $con as a private variable in your class. Look here for more info on how to do that.