Read

讀取資料 

2019/10/29 (調整內容)

2019/11/03 (增補說明)

讀取資料

要先新增一個practice的資料庫(schema),編碼請選擇utf8_unicode_ci。然後,利用SQL產生以下的資料表:

CREATE TABLE `practice`.`job` ( 

 `postid` INT NOT NULL AUTO_INCREMENT ,

 `company` VARCHAR(45) NOT NULL ,

 `content` TEXT NOT NULL ,

 `pdate` DATE NOT NULL ,

 PRIMARY KEY (`postid`));

標準的SQL語法:

CREATE TABLE practice.job ( 

 postid INT NOT NULL AUTO_INCREMENT ,

 company VARCHAR(45) NOT NULL ,

 content TEXT NOT NULL ,

 pdate DATE NOT NULL ,

 PRIMARY KEY (postid));

連接資料庫的方法很多,建議利用PDO (詳參: PHP Data Objects),主要的好處是可以連接MySQL以外的資料庫,這邊的帳號、密碼跟學校機房的設定一樣。(詳參: PHP 7 Connect to MySQL)  這裡用到try catch的語法跟java很像 (詳參: PHP Exception Handling)。也可以使用較簡單的mysqli

先利用PDO產生一個connection的物件:

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

利用setAttribute()進行設定,setAttribute()接受兩個參數,第一個參數是指定要設定的參數類型,「PDO::ATTR_ERRORMODE」(詳參: Predefined Constants ) 是指接下來要設定錯誤的處理方式,在PHP裡取得類別常數是利用「::」(詳參: Class Constants)。第二個參數就是設定錯誤的處理方式,設為「PDO::ERRMODE_EXCEPTION」是要求PDO在有錯誤時會回傳Exception,在PHP裡,如同Java,是可以利用try.. catch處理PDO回傳的錯誤 (詳參: Errors and error handlingExceptions)。

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

若產生PDOException ,會執行catch ,在這個例子裡我們使用了getMessage() (詳參: The PDOException class)。

echo "Connection failed: " . $e->getMessage();

完整的程式: testdb.php

<?php

$servername = "localhost";

$dbname = "practice";

$username = "root";

$password = "12345678";


try {

    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

    // set the PDO error mode to exception

    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    echo "Connected successfully"; 

    }

catch(PDOException $e)

    {

    echo "Connection failed: " . $e->getMessage();

    }

?>

Fetch with Associative Array

讀取資料可以利用associative array (詳參: PHP 7 Select Data From MySQL)

先改fetchAll,fetchAll()接受一個參數,「PDO::FETCH_ASSOC」,在PHP裡取得類別常數是利用「::」(詳參: Class Constants),也就是,「FETCH_ASSOC」是「PDO」類別裡的常數 (詳參: Predefined Constants),這個常數會讓fetchAll()以Associative Array的方式回傳結果。

  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

顯示的部分:

 foreach($rows as $job){

   echo $job["company"];

   echo $job["content"];

   echo $job["pdate"];

 }

完整的query.php:

<?php

  require 'db.php';


  $sql="select * from job";

  $stmt = $conn->prepare($sql);

  $stmt->execute();

  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>


<table width='85%' style='float:center'>

 <tr style='text-align:center'>

  <td>求才廠商</td>

  <td>求才內容</td>

  <td>日期</td>

 </tr>

 <?php

 foreach($rows as $job){ ?>

 <tr style='text-align:center'>

  <td><?=$job["company"]?></td>

  <td><?=$job["content"]?></td>

  <td><?=$job["pdate"]?></td>

 </tr>

 <?php

  }

  $conn = null; 

  ?>

</table>

Fetch with Class

讀取資料 利用fetch及Job class (詳參: PHP 7 Select Data From MySQL)

db.php

<?php

  $servername = "localhost";

  $dbname = "practice";

  $username = "root";

  $password = "12345678";

  //echo "test";

  try {

    $conn = new PDO("mysql:host=$servername;dbname=$dbname;", $username, $password);

    // set the PDO error mode to exception

    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  }

  catch(PDOException $e){

    echo "Connection failed: " . $e->getMessage();

  }

?>

利用require引用db.php (詳參: PHP Include Files)

  require 'db.php';

由job資料表讀取所有資料的sql:

  $sql="select * from job";

利用prepare去設定sql statement:

  $stmt = $conn->prepare($sql);

執行sql statement

  $stmt->execute();

取得執行後的結果,並將結果利用Job類別產生物件,並將所有物件儲存到$rows陣列。

在這裡fetchAll()接受兩個參數,第一個參數是「PDO::FETCH_CLASS」,在PHP裡取得類別常數是利用「::」(詳參: Class Constants),也就是,「FETCH_CLASS」是「PDO」類別裡的常數(詳參: Predefined Constants),這個常數會讓fetchAll()以Class的方式回傳結果。第二個參數則是Class的名稱。

  $rows = $stmt->fetchAll(PDO::FETCH_CLASS, 'Job');

query.php

<?php

  require 'job.php';

  require 'db.php';


  $sql="select * from job";

  $stmt = $conn->prepare($sql);

  $stmt->execute();

  $rows = $stmt->fetchAll(PDO::FETCH_CLASS, 'Job');

?>


<table width='85%' style='float:center'>

 <tr style='text-align:center'>

  <td>求才廠商</td>

  <td>求才內容</td>

  <td>日期</td>

 </tr>

 <?php

 foreach($rows as $job){ ?>

 <tr style='text-align:center'>

  <td><?=$job->company?></td>

  <td><?=$job->content?></td>

  <td><?=$job->pdate?></td>

 </tr>

 <?php

  }

  $conn = null; 

  ?>

</table>

job.php (細節可參考: ObjectPDO::FETCH_CLASS)

<?php

class Job {

  /* Member variables */

  /* make them private for encapsulation */

   

  private $postid;

  private $company;

  private $content;

  private $pdate;


  //https://phpdelusions.net/pdo/fetch_modes#FETCH_CLASS

  //only private variables were set

  function __set($variable, $value){}

  

  //https://culttt.com/2014/04/16/php-magic-methods/

  //https://www.tutorialdocs.com/article/16-php-magic-methods.html

  function __get($variable){  

    return $this->$variable;

  }


  /* constructor */


  function __construct(){

  //__set is called before __construt

  //this should be modified to prevent PDO reset variables

    $arguments = func_get_args();

    if (sizeof(func_get_args())==4){

      $this->postid = $arguments["postid"];

      $this->company = $arguments["company"];

      $this->content = $arguments["content"];

      $this->pdate = $arguments["pdate"];

    }



  }

   

}

?>

** check sizeof是不是必要....

** 作業 **

參考資料