Jump to content

New to OOP


invision2

Recommended Posts

Hi,

 

I've been doing some really poor PHP for about 3-4 years now and with the new year, I want to do it the better way :)

 

I've been dabbling with some OOP so far this weekend, and happy with the results. Managed to create an 'AddEntry' class and added a record to my table in the database.

 

However, I'm having some issues with an 'Edit Entry' script I'm trying, and wondered if I could get some assistance.

 

// a snippet from my blog class

public function editEntry()
{
	$sql = "UPDATE entries
			SET title=:title
			WHERE id=:id
			LIMIT 1";
  	
		if ($stmt = $this->_db->prepare($sql)) {
			 $stmt->bindParam(':title', $title, PDO::PARAM_STR);
			 $stmt->bindParam(':id', $id, PDO::PARAM_INT);
			 if ($stmt->execute() == false) {
				user_error(print_r($this->_db->errorInfo() , 1));
				return false;
			 }
			 if ($stmt->rowCount() == 0) {
				user_error("No rows updated.");
				error_log(print_r($stmt->debugDumpParams() , 1));
				return 0; // allow client code to differntiate between false & zero

			 }
			 $stmt->closeCursor();
			 return true;
		  }
		  user_error(print_r($stmt->errorInfo() , 1));
		  return false;
}

 

<?php
// my edit_entry.php script
include_once "common/base.php";
$pageTitle = "Edit Entry";
include_once "common/header.php";

if(!empty($_POST['title'])):
	include_once "inc/class.blog.inc.php";
	$entry = new BlogEntries($db);
	/*echo $entry->editEntry();*/

	$result = $entry->editEntry($_POST['id'], $_POST['title']);

else: 	
  	 include_once "inc/class.blog.inc.php";
  	 $entry = new BlogEntries($db);
?>

	<h2>Edit Entry</h2>
	<form method="post" action="editentry.php?id=<?php echo htmlspecialchars($_GET['id']); ?>" id="registerform">
		<div>
			<label for="title">Title:</label>
			<input type="text" name="title" id="title" value="<?php echo $entry->getEntry(); ?>" /><br />
			<input type="submit" name="register" id="register" value="Edit" />
			<input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>" />
			<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>" />
		</div>
	</form>

<?php
endif;
include_once 'common/close.php';
?>

 

Basically, if I make a change to the value in the input field and submit, it always gives me the output:

user_error("No rows updated.");

 

Is there something obvious I'm missing from either of the 2 scripts?

 

I'm just wanting the script to update the table.

 

 

I would really appreciate any pointers with this.

 

 

 

Thank you

Link to comment
Share on other sites

Many thanks for the quick reply.

 

I've updated the function to include the 2 arguments, but now when I submit, it just goes blank.

 

edit: When I submit the form, the header remains, but the rest of the page is blank.

 

Is there anything else you can spot wrong with the script?

Do I need to give values to $title and $id in my editentry.php script?

 

Really appreciate the help.

Link to comment
Share on other sites

It's a good call.

But the UPDATE query doesn't seem to work at all :(

 

When I submit I'd hope to check if any rows were affected. If so, it'd say 'Success' and if not 'Fail', load form.

 

Am I missing something obvious from the script that's stopping it working?

I think I've thought of everything :(

Link to comment
Share on other sites

Hi,

 

I've been doing some really poor PHP for about 3-4 years now and with the new year, I want to do it the better way :)

 

 

What are you talking about? The "better way" has nothing to do with changing perfectly fine functional code into an OOP class. Don't use OOP because you think its advanced. Use it when you need to. Understanding this will make you that much more of a better programmer.

Link to comment
Share on other sites

Thanks for the reply guys.

 

Error reporting doesn't seem to suggest anything is wrong :(

I've really no idea where I've gone wrong.

 

9three, could I possibly email over the files to you to have a closer look, I would really appreciate it.

 

Good point abazoskib. I'm just wanting to improve my coding style, as right now, it's not so hot. I thought OOP would save me a lot of time in the long run too.

Link to comment
Share on other sites

Got it working :D

 

Oh man, so easy too.

 

public function editEntry($title, $id)

 

had to be:

 

public function editEntry($id,$title)

 

because of the way I was bringing in the arguments from my editentry script.

 

 

Thanks for the help guys. I may be back shortly :)

Link to comment
Share on other sites

Just out of interest, the final code I have:

 

public function editEntry($id,$title)
{
	$sql = "UPDATE entries
			SET title=:title
			WHERE id=:id
			LIMIT 1";
  	
		if ($stmt = $this->_db->prepare($sql)) {
			 $stmt->bindParam(':title', $title, PDO::PARAM_STR);
			 $stmt->bindParam(':id', $id, PDO::PARAM_INT);
			 $stmt->execute();
			 $stmt->closeCursor();
			 return true;
		}
			 if ($stmt->execute() == false) {
				user_error(print_r($this->_db->errorInfo() , 1));
				return false;
			 }
			 if ($stmt->rowCount() == 0) {
				user_error("No rows updated.");
				error_log(print_r($stmt->debugDumpParams() , 1));
				return 0; // allow client code to differntiate between false & zero

			 }
			 $stmt->closeCursor();
			 return true;
		  }
		  user_error(print_r($stmt->errorInfo() , 1));
		  return false;
}

how would I tell the user if it was a successful update, or not.

 

Is there anything obvious missing from this script, any holes you can see?

 

Also, is there a way I can validate the text so it must be greater than 5 characters?

Should I do this in my editentry script, or in the function?

 

Really appreciate the help. Many thanks again.

Link to comment
Share on other sites

how would I tell the user if it was a successful update, or not

 

Your code is still to general and you should narrow it down for example a record would resemble an object like:

 

class Blog_Post {
    private $id = 0;
    private $authorId = 0;
    private $title = '';
    private $content = '';
    private $timestamp = 0;
    
    public function getId() { return $this->id; }
    public function setId($id) {
        $id = intval($id);
        if ($id > 0) {
            $this->id = $id;
        }
    }
    
    public function getAuthorId() { return $this->authorId; }
    public function setAuthorId($authorId) {
        $authorId = intval($authorId);
        if ($authorId > 0) {
            $this->authorId = $authorId;
        }
    }
    
    public function getTitle() { return $this->title; }
    public function setTitle($title) {
        $this->title = strval($title);
    }
    
    public function getContent() { return $this->content; }
    public function setContent($content) {
        $this->content = strval($content);
    }
    
    public function getTimestamp($format = '%c') { return strftime($format, $this->timestamp); }
    public function setTimestamp($timestamp) {
        if (is_integer($timestamp)) {
            $this->timestamp = $timestamp;
        } else if (is_string($timestamp)) {
            $this->timestamp = strtotime($timestamp);
        }
    }
}

 

Afterwards:

 

$post = Blog::findPage('slug-title');
//update fields
if (Blog::save($post)) {
    //success
}

 

Internal it would seek which fields have been modified and update only the modified fields instead of all fields using exception's you would do what you now do as user_error() and error_log()

Link to comment
Share on other sites

No but I would remember it for the future. As you can see my class has all variables that your database table has as columns. This allows me to easily modify record data. You should also notice that Blog_Post has no database connection which decouples it from the database. In my example I could have a Blog class that holds a database connection for example:

 

class Blog {
    private $db;
    
    //methods
}

class Blog_Post {
    private $id;
    private $authorId;
    private $title;
    private $content;
    private $timestamp;
    private $comments;
    
    //methods
}

class Blog_Post_Comment {
    private $id;
    private $author;
    private $title;
    private $content;
    private $timestamp;
    
    //methods
}

 

Storing data goes like:

 

$blog->save($post);

 

Or finding data goes like:

 

$blog->find($post);

 

Where a Blog_Post acts as a filter

Link to comment
Share on other sites

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.