i want to retrieve information 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 :))
A:
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;
}
pingpong
2010-09-23 08:47:05
-1 That's just asking for SQL injection, unless all of your input data is sanitised before anything uses it.
Cez
2010-09-23 08:50:49
i was asking for code, not references!! thanks
getaway
2010-09-23 08:58:04
cheers for the code worked perfectly, thanks @cez for leeting know about security, i have escaped the statment before i pass on to the function!! :))
getaway
2010-09-23 09:01:16
if you your escaping all GPC such as recursive variables then you have issues with your application down the line.
RobertPitt
2010-09-23 15:35:25
can you clarify what u mean, the $username variable, is sanitised before its pass on to the function, to do anything else
pingpong
2010-09-24 08:27:53
A:
- 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.
Tomasz Kowalczyk
2010-09-23 08:47:44
A:
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.
RobertPitt
2010-09-23 09:03:36
RobertPitt
2010-09-23 15:21:49
Also, answers that you find useful you should up vote them using the ^ arrow to the left of the post.
RobertPitt
2010-09-23 15:22:27