实例
namespace Test;
use PDO;
if (!interface_exists(__NAMESPACE__.'\iDbParam')) //判断命名空间是否存在不存在返回true 不存在才需要声明所以加!取反
{
interface iDbParam
{
const TYPE = 'mysql';
const HOST = 'localhost';
const USER_NAME = 'root';
const PASSWORD = 'root';
const DBNAME = 'php';
public static function connection();
}
}
//基本类继承接口用到命名空间继承
class Connection implements namespace\iDbParam
{
// 初始化连接参数 值时引用的命名空间接口内的属性
private static $type = iDbParam::TYPE;
private static $host = iDbParam::HOST;
private static $userName = iDbParam::USER_NAME;
private static $password = iDbParam::PASSWORD;
private static $dbName = iDbParam::DBNAME;
private static $pdo = null;
// 连接数据库
public static function Connection()
{
// TODO: Implement connection() method.
$dsn = self::TYPE.':host='.self::HOST.';dbname='.self::DBNAME;
$user = self::USER_NAME;
$password = self::PASSWORD;
$pd = new PDO($dsn,$user,$password);
self::$pdo = $pd;
return $pd;//这里返回时方便外部自己写操作代码
}
// 查询代码
public static function select($table,$field='',$where='',$limit=0,$offset=0)
{
$field = empty($field) ? '*' : $field;
$where = empty($where) ? '' : ' WHERE ' .$where;
$limit = empty($limit) ? '' : ' LIMIT ' .$limit;
$offset = empty($offset) ? '' : ' OFFSET '.$offset;
$sql = 'select '.$field.' from '.$table.$where.$limit.$offset;
$stmt = self::$pdo->prepare($sql);
$stmt->execute();
$stmt->debugDumpParams();die;
return $stmt->fetchall(PDO::FETCH_ASSOC);
}
}
//以后连接数据库只需要这个静态方法即可,注意命名空间
$link = Connection::Connection();
//执行一个查询
//$stmt = $link->prepare('select * from movies limit 5');
//$stmt->execute();
$stmt->debugDumpParams();die;
//echo '
'.print_r($stmt->fetchAll(PDO::FETCH_ASSOC),true);
//调用select()
echo '
'.print_r(Connection::select('movies','name,image','name=\'情书\'',5),true);
运行实例 »
点击 "运行实例" 按钮查看在线实例