php學習之簡單的CRUD操作

來源:互聯網
上載者:User

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!

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.