/    Sign up×
Community /Pin to ProfileBookmark

PHP class MVC issue

hey guys,

im trying to implement a MVC structure to a website but having a little difficulty.

i have a class thats responsible for adding/deleting/retrieving data from a table. as there will be a class for every table in the database the connection script is held in a separate page and is included at the beginning of every class. this connection script uses the PEAR DB system.

but even though the script is included its connection variable cannot be accessed within the class? the connection script is def working as i have tested it. any ideas? included is an example of some of my code.

[CODE]

#connection script.

<?php

require_once(‘DB.php’);

[COLOR=”Red”]removed the real values here for obvious reasons:)[/COLOR]
$user = ‘blank’;
$pass = ‘blank’; // use password given in practical
$host = ‘blank’; // MySQL DBMS is running on student.cs.ucc.ie as well
$db_name = ‘blank’;

// Data Source Name: This is the universal connection string
$dsn = “mysql://$user:$pass@$host/$db_name”;

$db = DB::connect($dsn);

if (DB::isError($db))
{
echo “failed <br/>”;
die ($db->getMessage()); // terminate the script with an error message
}

?>

#class file.

<?
//the connection to the database.
require_once ‘connection.php’;

/*
* Class test, allows the user to add, edit, delete, list data.
*/

class test
{
$conn = “”;

/*
* adds data to the test table.
*
* data1:
*
* return: true or false, if the insert query was successful or not.
*/
function add($data1)
{
$query_add = “insert into test(test_data) values(‘$data1’)”;

[COLOR=”Red”]$db isnt seen???[/COLOR]
$result = $db->query($query_add);

if($result)
return TRUE;
else
return FALSE;
}

/*
* set a reference to the database connection so an instance of the class can use it.
*
*/
function setConn($db_connection)
{
[COLOR=”Red”]this doesnt work either?![/COLOR]
$conn = $db_connection;
}
}

#controller script.

<?php
require ‘class_test.php’;

$test = new $test();

[COLOR=”Red”]fails :([/COLOR]
$test->add(‘some data’);

?>

[/CODE]

thanks for any advice

to post a comment
PHP

0Be the first to comment 😎

×

Success!

Help @bennythemink 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.18,
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,
)...