PHP刚刚开始上手学习 刚刚进行了个最基本的CRUD操作,并以此记录
数据表
creater table userinfo
{
id int auto_Increment promary key,
userName varchar(30),
pwd varchar(30),
int age(int)
}
<?php
class UserDAO {
var $pdo;
function __construct()
{
$this->pdo=new PDO("mysql:host=localhost;dbname=demo", "root", "sa");
}
//本来想用这个方法获得PDO对象 但是获得不到 所以直接写在构造函数里面了
function GetPDO() {
if ($this->pdo == null)
$this->pdo = new PDO ( "mysql:host=localhost;dbname=demo", "root", "sa" );
return $this->pdo;
}
//添加用户
function addUser($arr) {
try {
$this->pdo->exec("insert into userinfo(username,pwd,age) values('".$arr[0]."','".$arr[1]."',".$arr[2].")");
}catch(Exception $e)
{
echo "error:".$e->getMessage();
}
}
//修改用户
function modifUser($arr) {
$this->pdo->exec("update userinfo set username='".$arr[0]."',pwd='".$arr[1]."',age=".$arr[2]." where id=".$arr[3]);
}
//删除用户
function deleteUser($id) {
$this->pdo->exec("delete from userinfo where id=".$id);
}
//查询所有用户
public function queryUserList() {
$rs = $this->pdo->query ( "select * from userInfo" );
$rs->setFetchMode ( PDO::FETCH_ASSOC );
$result_arr = $rs->fetchAll ();
return $result_arr;
}
//根据用户ID 查询该ID用户
function queryUserById($id) {
}
}
$user = new UserDAO ();
/*用户查询
$arr = $user->queryUserList ();
echo "<center><h3>用户列表</h3><table border=1><tr><th>用户名</th><th>密码</th><th>年龄</th></tr>";
foreach ( $arr as $value ) {
echo "<tr><td>" . $value ['userName'] . "</td><td>" . $value ['pwd'] . "</td><td>" . $value ['userName'] . "</td></tr>";
};
*/
/*用户添加
$userAdd=array("dongguang","1232323",40);
$user->addUser($userAdd);
echo "添加成功!";
**/
/*用户修改
$userModif=array("liudehua","gggggg",40,2,);
$user->modifUser($userModif);
echo "修改成功!";
*/
/**
用户删除
$user->deleteUser(3);
echo "删除成功!";
* */
?>
其操作主要运用PDO对象的两个方法exec和query!