whats the best way to write a php mysql function?
i want to retrieve i开发者_如何学运维nformation from my database quite a lot throughout my app, i was thinking it would be easier to write function, so i can access it anytime, what is the best way to write one! thanks :))
hope this helps, you have to pass variables to a function, then use that variable to retrieve something from your database! i.e.
function getUserInfo($username) {
$query = "SELECT * FROM user WHERE username = '$username'";
$result = mysql_query($query);
if (!mysql_num_rows($result)) return false;
$row = mysql_fetch_array($result);
return $row;
}
- mysql_query() - simple, function interface
- PDO - OOP, statement preparation, simple to learn and good to use
- ORM - Doctrine, Propel, hard for beginners but powerful at later stage.
Integrate a class into PDO then integrate your methods into the Database Object
Examples:
class Database extends PDO
{
//Override __construct for PDO
function __construct()
{
Here you assembly your PDO Constructor
parent::__construct($dsn,$username,$password,$driver_options);
}
}
Based on that you can simple do:
$Database = new Database(); //Where as your Database class is now combined with PDO:
As a follow up you can do classes like so now:
class DB_Table_Users extends Database
{
public function getByLocation($location)
{
$statement = $this->prepare("SELECT * FROM users WHERE location = :location");
$statement->bindValue(':location',$location);
$statement->execute();
return $statement;
}
public function getByDate($int_date)
{
$statement = $this->prepare("SELECT * FROM users WHERE reg_date > :int_date");
$statement->bindValue(':int_date',$int_date);
$statement->execute();
return $statement;
}
}
and use like so:
$Users = new DB_Table_Users;
$statement = $Users->getByLocation('uk');
foreach($row as $statement->fetchObject())
{
//..
}
This has some more structure to the database relations and will keep your tables specific to a class.
Tip: you can also use __get
and __set
within your DB_Table_XXXX
so that within your methods you can fetch as an object to your own table.
精彩评论