当前位置: 动力学知识库 > 问答 > 编程问答 >

PHP and MySQL - Constants, Function, Best Practices?

问题描述:

I've been using PHP and MySQL for years now, but never in a formal setting. I use it to streamline things at my work, and have programmed a lot of my own commercial websites, but I'm not employed as a programmer, and never have been. I'm looking to start doing some freelance work though, and I'm wondering about what some of the best practices are.

I always use a getter class to retrieve data from mysql, and setter class to enter data into mysql, to which I pass the connection class. Every mySQL table and field name has its own constant defined in a constants include file. What I usually do though, is enter the constant directly into the setter or getter classes, rather than passing them as a variable. It makes life easier and quicker to do it this way, but it does defy my understanding of a function within a class as being something that should be independent.

Just to be clear, this is an example of what I usually do:

constants.inc.php

define('TABLE_NAME','table_name');

dbase_getters.class.php

public function get_data($connection){

$query = "SELECT * FROM " . TABLE_NAME;

$result = $connection etc...

}

or should I be doing it like this?

dbase_getters.class.php

public function get_data($connection, $table_name){

$query = "SELECT * FROM " . $table_name;

result = $connection etc...

}

It just seems like a lot more hassle to do it by passing the variable, especially because if I want to change the parameters of the function by adding a new field to search, I have to find every instance of the function calls and change them, whereas if I use constants, I just need to add them to the function.

Also, when it comes to things like declaring constants, I've always used single-quotes. But when I create strings, I always use double-quotes. Is this being inconsistent, and should I just use one type of quote all the time?

Thanks!

网友答案:

You can, of course, do it both ways and I think both are about equally undesirable. Dynamically creating SQL strings is both difficult to secure and also error prone.

I suggest you try one of the many readily available libraries out there, as for example:

http://www.doctrine-project.org/

http://propelorm.org/

Those are so called "ORM" - object relational mappers. Those will help you in achieving what you - so I believe - are trying to do.

There are other approaches to this out there, I once used Pear DB (MDB2 now, http://pear.php.net/package/MDB2) which isn't as high level as an ORM. This will also help you with your design problems.

Database access is a common problem to solve and many people have done it before, use what they already found out and don't reinvent the wheel! Try using an ORM. It's very satisfying and comes much more naturally than handling SQL, rows, resultsets and connection objects.

网友答案:

To use MVC terms... Your model, which contains all your business logic, should have one clearly defined function somewhere which gets some specific kind of data from the database. Say, something like this:

function getUserByUsername($username) {
    $query = 'SELECT ... FROM users WHERE name = :username';
    ...
    return $user;
}

Retrieving the user by username from the database is one specific, unique action your app can do. Make a function for it. It makes your app a lot more structured. Don't make a general SQL wrapper and pass it a ton of different variables, that just diffuses your database logic throughout your app unnecessarily.

网友答案:

For defining Constants, I use the same method as the OP.

I suggest you look into these patterns for your persistence layer:

DAO (Data Access Object) pattern

Factory pattern

And next to this there is also the possibility of using ORM frameworks

As far as I see it, you are doing it right. (just keep in mind that there are such things like prepared statements for php queries)

网友答案:

Using Own frame work is limited to own line of knowledge, i will recommend to use mvc frameworks most host and demanded frameworks are :

  1. CAKEPHP
  2. Codeigniter
  3. ZEND

for cakephp here is how works :

Core Definition Constants

Global Functions

if you are used to use one mvc then not others are bar for you.

网友答案:

The best practice I prefer is to create a database class with methods to perform the database query.. These are bunch of function I use which are easy way to implement basic insert select and update. This is example with PDO.

    public function select($table, $fields, $where = ""){
    try{
        $fields = implode(",", $fields);
        $stmt = $this->connection->prepare("SELECT {$fields} from {$table} {$where}");
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $result;
    }catch(PDOException $p){
        Error::PDOError($p->getCode(), $p->getMessage());
    }
}
public function insert($table, $data) {
    $fields = implode(",", array_keys($data));
    $values = implode(",", array_values($data));
    $stmt = $this->prepare("INSERT INTO " . $table . "({$fields}) VALUES ({$values})");
    return $stmt->execute();
}

public function update($table, $data, $where) {
    $fieldValues = NULL;
    foreach ($data as $key => $value) {
        $fieldValues .= "$key = :$key,";
    }
    $fieldValues = rtrim($fieldValues, ",");
    $stmt = $this->prepare("UPDATE {$table} SET {$fieldValues} WHERE {$where}");
    foreach ($data as $key => $value) {
        $stmt->bindValue(":$key", $value);
    }
    return $stmt->execute();
}

or you can always use Active record library

分享给朋友:
您可能感兴趣的文章:
随机阅读: