Jump to content

Recommended Posts

I just began coding in PHP to learn the language and expand what I know. I have been trying to get something working based off a book that I thought was a beginners book as well as googling things, but I just can't figure out what I am doing wrong.

 

I have done a lot of testing different steps to see what works and doesn't to try to figure it out. I am trying to Practice OOP with php. What I am doing is simple. I have a page that lets you add a new room to the database (So an insert) I have a config class for the database information, a database class for the connection and a function library for the inserts, updates deletes etc.

 

The following code works:

<?php>
require_once('class.Database.php');
$db = new Database();
$db->connect();
$sql = "INSERT INTO Rooms (Room_Id, Room_Name) VALUES ('','" .$roomname."')";
echo $sql;
mysql_query($sql) or die(mysql_error());
/*$DataManager = new DataManager();
$insert=$DataManager->addRoom($roomname);*/

echo "<p>";
echo "1 record added";
echo "<p><a href='CreateRooms.php'>Add Another Room</a>";
echo "<br><a href='maintenance.php'>Home</a>";

?>

 

But this is without my function library. If I modify the code to make the insert page to go through the function library (Which I will truncate for length) I get the following error:

 

 

Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /home/.balderdash/wozer/public_html/class_lib.php on line 89

 

I change my insert page to be this:

<?php

$roomname = $_POST['RoomName'];

include_once('class_lib.php');

$DataManager = new DataManager();
$DataManager->addRoom($roomname);

echo "<p>";
echo "1 record added";
echo "<p><a href='CreateRooms.php'>Add Another Room</a>";
echo "<br><a href='maintenance.php'>Home</a>";

?>

 

and my function library looks like this:

 

<?php

require_once('class.Database.php');

class DataManager
{
    public function addRoom($roomname)
    {
         $db = new Database();
         $db->connect();
         $sql = "INSERT INTO Rooms (Room_Id, Room_Name) VALUES ('','" .$roomname."')";
         mysql_query($sql) or die(mysql_error());
    }
}

%>

 

 

I am probably making some really obvious mistake, but I have spent weeks trying different ways of doing this and cannot figure it out.

 

Thanks for your help

 

Woz

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/175366-php-beginner-needing-help/
Share on other sites

 

1.

 

Line 89 is the following line in the DataManager Class

 

mysql_query($sql) or die(mysql_error());

 

As above it is in the DataManager Class

 

 

2.

 

Just to be sure, I copied the code again. went to the page, inserted a room and refreshed the database, the new Rooms are showing up (did it a few times to be sure)

 

 

3.

 

My Database class looks like this:

 

<?php

require_once('config.php');

class Database
{
function db()
{
	$connection = NULL;
	$connected	= FALSE;
	$result		= NULL;
	$query_error =NULL;
}

function connect()
{

	global $cfg;

	$this->connection = mysql_connect($cfg['db_host'], $cfg['db_user'], $cfg['db_pass']);

	if(!is_resource($this->connection) || !mysql_select_db($cfg["db_name"], $this->connection))
	{
		$this->query_error('Unable to connect to MySQL database.');
		return FALSE;
	}
	else
	{
		$this->connected = TRUE;
		return TRUE;
	}
}

function disconnect()
{
	@mysql_free_result($this->result);
	@mysql_close($this->connection);
	$this->result = $this->connection = NULL;
	$this->connected = FALSE;
}

}
}
?>

 

Okay, let's start with your database class, as that needs some work.

 

Rule #1: Never use 'global'.  Regardless of whether you're coding procedurally or using OOP, 'global' is bad.  Argument lists exist for a reason.

 

Rule #2: Classes have data members and constructors for a reason as well.  Use them.  Don't fight against convention.

 

So, here's a re-imagined Database class:

 

class Database
{
   private $conn;
   private $isConnected = false;
   
   public function __construct($configData)
   {
      $this->conn = mysql_connect($configData['db_host'], $configData['db_user'], $configData['db_pass']);

      if (!isResource($this->conn) || !mysql_select_db($configData['db_name'], $this->conn))
      {
         $isConnected = false;
         echo "Could not connect to the database.";
      }
      else
      {
         $isConnected = true;
      }
   }

   public function query($sql)
   {
      if ($this->isConnected)
      {
         $result = mysql_query($sql);
         return $result;
      }
      else
      {
         echo "Could not execute query";
      }
   }
}

 

Now, for the DataManager:

 

class DataManager
{
   private $dbc;

   public function __construct($configData)
   {
      $this->dbc = new Database($configData);
   }

   public function addRoom($id = null, $roomName)
   {
      $sql = "INSERT INTO Rooms (Room_Id, Room_Name) VALUES ('$id', '$roomName')";
      $result = $this->dbc->query($sql);

      return $result;
   }
}

 

Then, in the client code:

 

require_once('config.php');

$DataManager = new DataManger($cfg);

/* etc. */

 

Try that as a first step.

Thanks for your help so far Nightslyr.

 

I was not aware that global was bad. I will make sure not to use it again.

 

I had read briefly about constructors, but did not understand them too well. I was going to try getting the basics working then go back and start improving stuff. I used the code that you gave me to see if it will work, but I can't tell if it is going to or not. When I tried entering a new Room in I got the exact same error as I was getting before with my code. I then deleted my all the files (Config Database class and the DataManager class) tried inserting a room again (expecting to see an error because the files don't exist) but instead I got the same mysql_query error as before.

 

I'm going to try to figure out what is going on with this and see what happens with the code you gave me and let you know what happens.

 

Thanks again for your help

I figured it out. I had inadvertently copied the Database and Datamanager file into a different place, and it was running off of that (really old code) instead of the place I had been storing the correct code, which probably explains why when I made changes I was still getting that error, even though my test code was working.

 

I am working through some debugging stuff. I will let you know what happens

Ok,

 

When I first ran the code I got the following Error:

 

Fatal Error: Call to undefined function isresource()

 

I did some research and found that there is an is_resource() function so I tried that and the error went away. But when I do the insert it reports back "Could not Execute Query" If I try putting in echo mysql_error(); instead, the page comes back blank

 

This makes me think that the $this-> connected is equal to false and the fact that I changed isResource() to is_Resource(); is what is causing this to happen. Is isresource() correct? Is there something that needs to be done to define it?

Ok,

 

When I first ran the code I got the following Error:

 

Fatal Error: Call to undefined function isresource()

 

I did some research and found that there is an is_resource() function so I tried that and the error went away. But when I do the insert it reports back "Could not Execute Query" If I try putting in echo mysql_error(); instead, the page comes back blank

 

This makes me think that the $this-> connected is equal to false and the fact that I changed isResource() to is_Resource(); is what is causing this to happen. Is isresource() correct? Is there something that needs to be done to define it?

 

No, it's is_resource().  I rushed while typing.

 

Can I see how you're calling the function?

Here is the code where I am calling the function:

 

$DataManager = new DataManager($cfg);

$DataManager->addRoom($id, $roomName);

 

After the else-clause in the Database class' constructor, write the following line:

 

echo "The database is connected: {$this->isConnected}";

 

Actually, wait...is the id column of your rooms table set to NOT NULL?

simple mistake in the constructor

public function __construct($configData)
   {
      $this->conn = mysql_connect($configData['db_host'], $configData['db_user'], $configData['db_pass']);

      if (!isResource($this->conn) || !mysql_select_db($configData['db_name'], $this->conn))
      {
         $isConnected = false;//this line
         echo "Could not connect to the database.";
      }
      else
      {
         $isConnected = true;//and this line
      }
   }

 

assuming you want to access the data member isConnected, you need to use the $this keyword.

 

public function __construct($configData)
   {
      $this->conn = mysql_connect($configData['db_host'], $configData['db_user'], $configData['db_pass']);

      if (!isResource($this->conn) || !mysql_select_db($configData['db_name'], $this->conn))
      {
         $this->isConnected = false;
         echo "Could not connect to the database.";
      }
      else
      {
         $this->isConnected = true;
      }
   }

 

try that

That fixed it, Thanks!

 

The Room_ID is a unique Identifier that auto increments so I took out the $id. It still works.

 

Thanks a lot for both of your help. Now I have a basis for how to write some good php code.

 

Woz

 

Edit: How do I mark this as solved?

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.