PHP直接使用MySQL的具體函數介紹_PHP教程

來源:互聯網
上載者:User
我們在進行清單 1. Access/get.php
 
  1. <?php
  2. function get_user_id( $name )
  3. {
  4.  $db = mysql_connect( 'localhost', 'root', 'password' );
  5.  mysql_select_db( 'users' );
  6.  $res = mysql_query( "SELECT id FROM users WHERE login='".$name."'" );
  7.  while( $row = mysql_fetch_array( $res ) ) { $id = $row[0]; }
  8.  return $id;
  9. }
  10. var_dump( get_user_id( 'jack' ) );
  11. ?>

注意使用了 mysql_connect 函數來實現PHP直接使用MySQL。還要注意查詢,其中使用字串串連來向查詢添加 $name 參數。

該技術有兩個很好的替代方案:PEAR DB 模組和 PHP Data Objects (PDO) 類。兩者都從特定資料庫選擇提供抽象。因此,您的代碼無需太多調整就可以在 IBM? DB2?、MySQL、PostgreSQL 或者您想要串連到的任何其他資料庫上運行。

使用 PEAR DB 模組和 PDO 抽象層的另一個價值在於您可以在 SQL 陳述式中使用 ? 操作符。這樣做可使 SQL 更加易於維護,且可使您的應用程式免受 SQL 插入式攻擊。

使用 PEAR DB 的替代代碼如下所示。

清單 2. Access/get_good.php

 
  1. <?php
  2. require_once("DB.php");
  3. function get_user_id( $name )
  4. {
  5.  $dsn = 'mysql://root:password@localhost/users';
  6.  $db =& DB::Connect( $dsn, array() );
  7.  if (PEAR::isError($db)) { die($db->getMessage()); }
  8.  $res = $db->query( 'SELECT id FROM users WHERE login=?',array( $name ) );
  9.  $id = null;
  10.  while( $res->fetchInto( $row ) ) { $id = $row[0]; }
  11.  return $id;
  12. }
  13. var_dump( get_user_id( 'jack' ) );
  14. ?>

注意,所有PHP直接使用MySQL的地方都消除了,只有 $dsn 中的資料庫連接字串除外。此外,我們通過 ? 操作符在 SQL 中使用 $name 變數。然後,查詢的資料通過 query() 方法末尾的 array 被發送進來。


http://www.bkjia.com/PHPjc/446326.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/446326.htmlTechArticle我們在進行 清單 1. Access/get.php <?php functionget_user_id($name) { $ db = mysql_connect ('localhost','root','password'); mysql_select_db('users'); $ res = mysql_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.