Some simple PHP Connection database example detailed explanation

Source: Internet
Author: User
Tags odbc php database mysql database

Two ways to connect to a MySQL database :

(1) Using PHP database function to connect

This is one of the most common ways.
Four database functions are used here:
Mysql_connect () establishes a connection to the MySQL server.
mysql_select_db (): Select the database in the MySQL server for later data query Operation query processing.
mysql_query (): Send query string to help MySQL do related processing or execution.
Mysql_fetch_row (): Used to move the query result order line to the array variable. The index of an array is a number
Index, the first index value is 0.


(2) Connect via ODBC

PHP to connect to the MySQL database through ODBC main use of four functions:
Odbc_connect (): Used to establish a connection with an ODBC data source.
ODBC_DO (): Used to execute a database query after a connection has been established.
Odbc_result (): Used to get the value of a field in the current record row.
Odbc_fetch_row (): Used to save query results to an array, each array element corresponding to a record.

Let's take a look at the PHP database function Join method instance

Connect to a MySQL database

Before you can access and process data in a database, you must create a connection to the database.

In PHP, this task is done through the mysql_connect () function.

Grammar

Mysql_connect (Servername,username,password); parameter description
ServerName Optional. Specify the server to connect to. The default is "localhost:3306".
Username Optional. Specify the user name to use for the login. The default value is the name of the user who owns the server process.
Password optional. Specify the password used for the login. The default is "".

The code is as follows Copy Code

<?php
$con = mysql_connect ("localhost", "root", "");
if (! $con)
{
Die (' Could not connect: '. Mysql_error ());
}
Mysql_close ($con);
?>

Object-oriented mysqli (detailed tutorial)

The code is as follows Copy Code


<?php
$mysqli = new mysqli (' localhost ', ' root ', ' ', ' volunteer ');
if (Mysqli_connect_errno ()) {
Die (' Unable to connect! '). Mysqli_connect_error ();
}
?>

PDO connection MySQL (detailed tutorial)

The code is as follows Copy Code


<?php

$db = new PDO (' Mysql:host=localhost;dbname=test ', ' root ', ');
try {
foreach ($db->query (' select * from user ') as $row) {
Print_r ($row);
}
$DB = null; Close Database
catch (Pdoexception $e) {
echo $e->getmessage ();
}
?>


Then we can also use ODBC to connect to the database

The code is as follows Copy Code


<?php
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 Data connection class

The code is as follows Copy Code


<?php
//------------------------------------------------------------------------------------------
※database () constructor, database initial parameters
※select () query
※getrows () returns the total number of records in the query
※insert () Insert Record
※update () Update
※delete () Delete
※halt () Interrupt and display error message * *
//------------------------------------------------------------------------------------------
Define ("DatabaseType", "1"); Defines the database type: 1 for mysql;2 SQL server;3 for Oracle;4 for ODBC
Define ("SERVER", "localhost"); Host name or IP address of the database server
Define ("DATABASE", "dbname"); The name of the database to connect to
Define ("USER", "TableName"); User name used to connect to the database
Define ("PASSWORD", "paswd"); Password used to connect to the database

Class Database {
var $dbLink; Connection handle
var $result; Query handle
var $insId; Insert () successfully returns the value of the Auto_increment column
var $rows; Returns an array of data
var $numRows; Number of returned data
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 () return to False no result * *

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 () returns the total number of records for the query * *

    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 (" <b>database Query Error:</b>%s<br>n ", $msg);
            printf ("<b>mysql error:</b>%s <br>n ", mysql_error ());
       }else
             echo "<meta Http-equiv=refresh content= ' 0; Url=.. /include/error.htm ' > '; A custom error prompt file
        return false;
   }
}

Switch ($db->dbtype) {
Case 1:
@mysql_close ();
Break
Case 2:
Break
}
$db = new Database ();
?>

Friendly Tips

If there is a connection to the MySQL database Chinese garbled we can connect the database query before adding mysql_query ("Set names UTF8"); If you're GBK, you're using GBK coding.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.