Home php教程 php手册 一些简单的PHP连接数据库例子详解

一些简单的PHP连接数据库例子详解

Jun 13, 2016 am 10:09 AM
php example getting Started about database article of Simple detailed Detailed explanation connect

本文章来给各位php入门者详细关于php连接数据库的实例代码,这里主要讲到了入门级的mysql连接代码到高级的封装数据库连接类,希望此文章对各位朋友所有帮助。

连接MySQL数据库的两种方法:

(1)利用PHP的数据库函数连接

此方式是最常用的一种方式.
这里主要用到四个数据库函数:
mysql_connect () 建立与MySQL服务器的连接。
mysql_select_db ():选择MySQL服务器中的数据库供以后的数据查询操作query处理。
mysql_query ():送出query字符串以帮助MySQL做相关的处理或执行。
mysql_fetch_row ():用来将查询结果result单行移到数组变量中。数组的索引是数字
索引,第一个索引值是0。


(2)通过ODBC连接

PHP通过ODBC连接MySQL数据库主要用到四个函数:
Odbc_connect ():用来同ODBC数据源建立连接。
Odbc_do ():用来在建立连接之后执行数据库查询。
Odbc_result():用于取得当前记录行中某个字段的值。
Odbc_fetch_row ():用来把查询结果保存到数组,每个数组元素对应一条记录。

我们先来看PHP的数据库函数连接 方法实例

连接到一个 MySQL 数据库

在您能够访问并处理数据库中的数据之前,您必须创建到达数据库的连接。

在 PHP 中,这个任务通过 mysql_connect() 函数完成。

语法

mysql_connect(servername,username,password);参数 描述
servername 可选。规定要连接的服务器。默认是 "localhost:3306"。
username 可选。规定登录所使用的用户名。默认值是拥有服务器进程的用户的名称。
password 可选。规定登录所用的密码。默认是 ""。

 代码如下 复制代码

$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_close($con);
?>

面向对象mysqli(详细教程)

 代码如下 复制代码


$mysqli = new mysqli('localhost','root','','volunteer');
if (mysqli_connect_errno()){
 die('Unable to connect!'). mysqli_connect_error();
}
?>

pdo连接mysql(详细教程)

 代码如下 复制代码


 
$db = new PDO('mysql:host=localhost;dbname=test', 'root', '');
try {
 foreach ($db->query('select * from user') as $row){
  print_r($row);
 }
 $db = null;  //关闭数据库
} catch (PDOException $e) {
 echo $e->getMessage();
}
?>


然后我们还可以使用ODBC连接数据库

 代码如下 复制代码


require_once './adodb5/adodb.inc.php';
$conn = &ADONewConnection('mysql');
$conn->connect('localhost','root','','test');
$conn->Execute("set names utf8");
$res = $conn->Execute("select * from user");
if (!$res){
 echo $conn->ErrorMsg();
}else{
 var_dump($res);
}
?>

mysql数据连接类

 代码如下 复制代码


//------------------------------------------------------------------------------------------
// ※Database()                   构造函数,数据库初始参数
// ※Select()                     查询
// ※GetRows()                    返回查询的记录总数
// ※Insert()                     插入记录
// ※Update()                     更新
// ※Delete()                     删除
// ※Halt()                       中断并显示错误信息*/
//------------------------------------------------------------------------------------------
define("DATABASETYPE", "1");       //定义数据库类型:1为MySql;2为SQL Server;3为Oracle;4为Odbc
define("SERVER", "localhost");     //Host name or IP address of the database server
define("DATABASE", "dbName");   //要连接的数据库名
define("USER", "tableName");     //用于连接数据库的用户名
define("PASSWORD", "paswd");    //用于连接数据库的密码 

class Database {
    var $dbLink;                      //连接句柄
    var $result;                      //查询句柄
    var $insId;                       //Insert()成功返回AUTO_INCREMENT列的值
    var $rows;                        //返回数据数组
    var $numRows;                     //返回数据数目
    var $dbHost, $dbUser, $userPassword, $database;
    var $dbType = DATABASETYPE;
    var $msgFlag = "yes";            //yes:show the Mysql message ; no: die by show "Halted."

    function Database($dbHost = SERVER, $dbUser = USER, $userPassword = PASSWORD, $database = DATABASE) {
        switch ($this->dbType) {
            case 1:
                $this->dbLink = @mysql_pconnect($dbHost, $dbUser, $userPassword); // or die("Can't Connect to Remote Host!");
                @mysql_select_db($database, $this->dbLink); // or die ("Can't Connect to Remote Host!");
                break;
            case 2:
                break;
        }
        return true;
    }

    /* SQL:Select() 返回为false无结果 */

    function Select($table, $columns, $condition = 1) {
        $sql = "select $columns from $table where $condition ";
        $this->result = @mysql_query($sql, $this->dbLink);
        unset($this->rows);
        if ($this->result) {
            $i = 0;
            if (!($this->rows = array("$i" => @mysql_fetch_array($this->result))))
                return false;
            if (($this->numRows = @mysql_num_rows($this->result)) == 0)
                return false;
            while ($tempRows = @mysql_fetch_array($this->result)) {
                array_push($this->rows, $tempRows);
            }
        } else {
            $this->Halt($sql);
            return false;
        }
        return true;
    }

    /* SQL:GetRows() 返回查询的记录总数 */

    function GetRows($table, $condition = 1) {
        $sql = "select count(1) as count from $table where $condition";
        $this->result = @mysql_query($sql, $this->dbLink);
        if ($this->result) {
            $temp = @mysql_fetch_array($this->result);
            $this->numRows = $temp[count];
        } else {
            $this->Halt($sql);
            return false;
        }
        return $this->numRows;
    }

    /* SQL:Insert() */

    function Insert($table, $columns, $values) {
        $sql = "insert into $table ($columns) values ($values)";
        $this->result = @mysql_query($sql, $this->dbLink);
        if ($this->result)
            $this->insId = @mysql_insert_id($this->dbLink);
        else {
            $this->Halt($sql);
            return false;
        }
        return true;
    }

    /* SQL:Update() */

    function Update($table, $setings, $condition) {
        $sql = "update $table set $setings where $condition";
        $this->result = @mysql_query($sql, $this->dbLink);
        if ($this->result)
            $this->numRows = @mysql_affected_rows($this->result);
        else {
            $this->Halt($sql);
            return false;
        }
        return true;
    }

    /* SQL:Delete */

    function Delete($table, $condition) {
        $sql = "delete from $table where $condition";
        $this->result = @mysql_query($sql, $this->dbLink);
        if ($this->result)
            $this->numRows = @mysql_affected_rows($this->result);
        else {
            $this->Halt($sql);
            return false;
        }
        return true;
    }

    /* Halt():error message */

    function Halt($msg) {
        if ($this->msgFlag == "yes") {
            printf("Database Query Error: %s
n", $msg);
            printf("MySql Error: %s
n", mysql_error());
        }else
            echo ""; //自定一个出错提示文件
        return false;
    }
}

switch ($db->dbType) {
    case 1:
        @mysql_close();
        break;
    case 2:
        break;
}
$db = new Database();
?>

友情提示

如果出现连接mysql数据库中文乱码我们可以在连接数据库查询之前加上mysql_query("set names utf8"); 如果你是gbk就使用gbk编编码了

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

Oracle's Role in the Business World Oracle's Role in the Business World Apr 23, 2025 am 12:01 AM

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

MySQL: Structured Data and Relational Databases MySQL: Structured Data and Relational Databases Apr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

See all articles