[PHP] - mysql 資料庫操作

來源:互聯網
上載者:User

標籤:

使用PHP操作資料庫有兩種方式

  1. 使用mysql_XXXX()方法
    1. 使用這種方式,需要先把php.ini裡的extension=php_mysql.dll去掉注釋
  2. 使用PDO
    1. 使用這種試,需要把php.ini裡的extension=php_pdo_mysql.dll去掉注釋

 

下面示範使用第一種方式:

<!doctype html><html>    <head>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    </head>    <body>       <?php           $conn = mysql_connect("localhost", "root", "zxbbugu");           if(!$conn) {               die("Could not connect:" . mysql_error());           }                      mysql_select_db("test", $conn);           //mysql_query("SET NAMES utf8");                      $result = mysql_query("INSERT INTO mytable(headline, create_time) VALUES(‘中國‘, ‘" . date("Y-m-d h:i:s") . "‘);");           if( $result < 1) {               echo "insert error!";           }                      $query = mysql_query("SELECT * FROM mytable LIMIT 100 OFFSET 0;");           while ($row = mysql_fetch_array($query, MYSQL_BOTH)) {               echo "<p>", $row["id"], " - " , $row["headline"], " - ", $row["create_time"], "</p>";           }                      mysql_close();       ?>    </body></html>

 

下面是使用PDO方式:

<!doctype html><html>    <head>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    </head>    <body>       <?php           $pdo = new PDO("mysql:host=localhost;dbname=test", "root", "zxbbugu");           $stmt = $pdo->prepare(‘SELECT * FROM mytable WHERE id = :id‘);           $stmt->execute(array(":id"=>1));           foreach ($stmt as $row) {               echo $row["headline"];           }                      $result = $pdo->exec("INSERT INTO mytable(headline, create_time) VALUES(‘中國‘, ‘" . date("Y-m-d h:i:s") . "‘);");           if($result) {               $str = sprintf("add data completed, lastupdateid=%s", $pdo->lastInsertId());               echo $str;           }                      $rs = $pdo->query("SELECT * FROM mytable");           while ($row = $rs->fetch()) {               echo "<p>", $row["id"], " - " , $row["headline"], " - ", $row["create_time"], "</p>";           }       ?>    </body></html>

 

 

建議使用PDO方式,這樣可以減少SQL注入安全性問題。(php5以上建議使用PDO方式做資料庫操作)

[PHP] - mysql 資料庫操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.