/    Sign up×
Community /Pin to ProfileBookmark

relatively new to OOP passing VARs MySQL problem

I am fairly new to OOP with php and i’m having a problem with my SQL connection im getting this error:

Warning: mysql_connect() [function.mysql-connect]: Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2) in /home/.mantra/uername/myurl.com/includes/class_database.php on line 30

class database:

[code=php]
<?php
class database
{
public $host;
public $username;
public $password;
public $database;

function __construct($config)
{
$this->host = $config[‘db’][‘host’];
$this->username = $config[‘db’][‘username’];
$this->password = $config[‘db’][‘password’];
$this->dbname = $config[‘db’][‘database’];
}

function write()
{
echo $this->host.'<br/>’;
echo $this->dbname;
}

//connect to the database
function connect()
{
$conn = mysql_connect($this->host, $this->username, $this->password) or die(mysql_error());
$SelDB = mysql_select_db($this->dbname);
return $conn;
}
//run a mysql command
function execute($strSQL)
{
$result = mysql_query($strSQL) or mysql_error();
return $result;
}
//count the number of rows
function row_count($result)
{
$row = mysql_num_rows($result);
return $row;
}
}
?>
[/code]

[code=php]
<?php
class blog extends database
{
public $title;
public $body;
public $meta;
//construct the
function __construct($title=NULL, $body=NULL, $meta=NULL)
{
$this->connect();
$this->title = $title;
$this->body = $body;
$this->meta = $meta;
}

//add a new item to the blog
function insert_blog($_POST)
{
foreach ($_POST as $name=>$value)
{
$name = mysql_real_escape_string(htmlspecialchars($value));
}
$query = “INSERT INTO `blog` (title, text, meta, author)
VALUES (‘$title’, ‘$body’, ‘$meta’, ‘John Knowles’)”;
mysql_query($query) or die(mysql_error());
return ‘New Blog Created’.”nr”;
}

//update an item in the blog
function edit_blog($_POST)
{
foreach ($_POST as $name=>$value)
{
$name = mysql_real_escape_string(htmlspecialchars($value));
}
$query = “UPDATE `blog` (title, text, meta, author)
VALUES ($title, $body, $meta, ‘John Knowles’) WHERE id=’$id'”;
}

//display the blog on a page
function display_blog($num, $id=”, $search=”)
{
if (!empty($id))
{
$id = “WHERE id=’$id'”;
}
if (!empty($search))
{
$id = “WHERE text=’$search'”;
}
$query = “SELECT * FROM `blog` $id ORDER BY ‘date’ DESC LIMIT $num”;
$result = mysql_query($query) or die(mysql_error());
return $result;
}
}
?>
[/code]

please be aware this was just a list of functions so it is not in any OOP state atm its a slow work in progress.

any help will be greatly appreciated (including links to external ooPHP/MySQL resources if anyone has any)

to post a comment
PHP

8 Comments(s)

Copy linkTweet thisAlerts:
@NogDogJul 13.2007 — If you want to set the database connection values via the constructor of your database class, then the blog class will have to call its parent's constructor with the desired values.
[code=php]
//construct the
function __construct($config, $title=NULL, $body=NULL, $meta=NULL)
{
parent::__construct($config);
$this->connect();
$this->title = $title;
$this->body = $body;
$this->meta = $meta;
}
[/code]

Therefore, if you use this technique, you'll need to pass the $config array to your blog class when you instantiate it (along with the other parameters).
Copy linkTweet thisAlerts:
@jasonahouleJul 13.2007 — I would make a few other changes. You are returning your connection but never using it. I would create a $conn instance variable. This way you can also clean up your connections in the __destruct() method.

Another thing you can do is call your connect() method from your constructor since you are already passing the $config variable to the parent class.

Also, you have the execute() method in the parent class but you aren't using it.
[code=php]
<?php
class database
{
public $host;
public $username;
public $password;
public $database;
private $conn;

function __construct($config)
{
$this->host = $config['db']['host'];
$this->username = $config['db']['username'];
$this->password = $config['db']['password'];
$this->dbname = $config['db']['database'];
$this->connect();
}

function write()
{
echo $this->host.'<br/>';
echo $this->dbname;
}

//connect to the database
function connect()
{
$this->$conn = mysql_connect($this->host, $this->username, $this->password) or die(mysql_error());
$SelDB = mysql_select_db($this->dbname);
}

//run a mysql command
function execute($strSQL)
{
$result = mysql_query($strSQL) or mysql_error();
return $result;
}

//count the number of rows
function row_count($result)
{
$row = mysql_num_rows($result);
return $row;
}

function __destruct() {
mysql_close($this->conn);
}
}
?>
[/code]
Copy linkTweet thisAlerts:
@knowjauthorJul 14.2007 — Am I better calling the connect function from within the database class as is included on all the pages that it is needed?

also does anyone know of any good resources which demonstrate a OOPHP/MySQL system that i can reference to when trying to build this as i am sure im going about a lot of things in the wrong way with this being my first OO system.

thanks for the help so far.
Copy linkTweet thisAlerts:
@knowjauthorJul 14.2007 — I have decided to move everything into the database class rather than call it from the blog class after nogs explanation but for some reason im still getting the Can't connect to local MySQL server through socket.
[code=php]
<?php
class database
{
private $host;
private $username;
private $password;
private $database;
private $conn;

//Construct the objects
function __construct($config)
{
$this->host = $config['db']['host'];
$this->username = $config['db']['username'];
$this->password = $config['db']['password'];
$this->dbname = $config['db']['database'];
$this->connect();
}

//connect to the database
function connect()
{
$conn = mysql_connect($this->host, $this->username, $this->password) or die(mysql_error());
mysql_select_db($this->dbname);
$this->conn = $conn;
return $this->conn;
}
//run a mysql command
function execute($strSQL)
{
$result = mysql_query($strSQL) or mysql_error();
return $result;
}
//count the number of rows
function row_count($result)
{
$row = mysql_num_rows($result);
return $row;
}
//close the mysql link
function __destruct()
{
mysql_close($this->conn);
}
}
?>
[/code]



do i need to create a new database object when i want to call the constructor or is there an easy way to stat the connection of every page the database class is included?

basically all i want to do at the moment is create a connection to display my blog on the index.php
Copy linkTweet thisAlerts:
@knowjauthorJul 14.2007 — I have managed to get the database to connect but i'm having to put in

$database = new database($config);

to get the connection this just seems really messy to me isn't there a way of doing all of this processing outside of the display page?
[code=php]
<?php
$blog = new blog();
$database = new database($config);
$row = mysql_fetch_assoc($blog->display_blog(1));
echo '<h2>'.$row['title'].'</h2>'."nr";
echo '<i>Post by: John Knowles On '.$row['date'].'</i>'."nr";
echo auto_typography(substr($row['text'], 0, 700).'...')."nr";
?>
[/code]

Also what would be the best way to do this

while ($row = mysql_fetch_assoc($this->result))

within the database class?
Copy linkTweet thisAlerts:
@NogDogJul 14.2007 — What I do is instantiate my database class once in my main script. Then for any other class that needs to use it, I pass the object to its constructor:
[code=php]
class MyClass
{
private $db;

function __construct($db)
{
if(is_object($db))
{
$this->db = $db;
}
else
{
throw new Exception("Non-object parameter supplied to constructor");
}
}

function myMethod()
{
$result = $this->db->query("SELECT * FROM table");
}

}
[/code]

Then the main script would be something like:
[code=php]
require_once "Database.class.php";
require_once "MyClass.class.php";

$db = new Database();
$mc = new MyClass($db);
[/code]

I don't know if this is considered an OOP "best practice", but it works, and it keeps me from getting too confused. ?
Copy linkTweet thisAlerts:
@knowjauthorJul 14.2007 — well trying to find out best practice on web programming topics is like trying to find the meaning of life.

thanks for the help nog.

anyone know of any SQL query building resources as i would be interested to see how most are constructed as even tho i'm using OO i am still having to write individual SQL scripts which seems to defy the point of re-usability

Also what would be the best way to do this

while ($row = mysql_fetch_assoc($this->result))

within the database class?
Copy linkTweet thisAlerts:
@NogDogJul 14.2007 — I have a query result class, and when you use the select method from my db class, it returns an instance of that result class, with the MySQL result resource ID as an attribute. That result class has a number of different methods for accessing the result rows, such as:
[code=php]
// returns one specified result row as an associative array:
function getRow($row = NULL)
{
if($row !== NULL and is_numeric($row))
{
mysql_data_seek($this->result, (int) abs($row));
}
return(mysql_fetch_assoc($this->result));
} // end getRow()

// returns entire result set as 2-dim array: dim 1 = row number, dim 2 = field name:
function getArray()
{
mysql_data_seek($this->result, 0);
$data = array();
while($row = mysql_fetch_assoc($this->result))
{
$data[] = $row;
}
return($data);
}
[/code]
×

Success!

Help @knowj spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...