首页 > 编程技术 > php

php连接mysql ,mssql ,access,pdo等连接数据库代码

发布时间:2016-11-25 15:55

本文章提供了四种数据库连接程序,都针对于php的,像php mysql,与mssql是比较常用的,至于php access数据连接也有不秒人在用,还有就是利用php pdo来连接数据库代码我是在用火车头采集数据时来用的。

 
 //php与mysql数据库连接代码
 

 代码如下 复制代码
 mysql_connect('localhost','root','root') or die( 'mysql server stop or use password error!' );
 mysql_select_db('cshouse') or die( 'datebase error' );
 mysql_query("set Names 'GB2312'");


 
 //php 连接access数据库代码
 
 

 代码如下 复制代码
$conn = @new COM("ADODB.Connection") or die ("ADO Connection faild.");
 $connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . $path;
 $conn->Open($connstr);


 
 //php 利用pdo连接mdb数据库,这个比较适合于火车头采集数据的用户

 代码如下 复制代码
 $path ="F: ontSpiderResult.mdb"; 
 $conn = new PDO("sqlite:$path");
 if( $conn )
 {
  echo ('connection pdo success');
 }
 else
 {
  echo ('cnnection pdo fail ,plase check database server!');
 }


 
 // php与mssql 数据库连接代码
 

 代码如下 复制代码
 $link = mssql_connect("127.0.0.1", "sa", "sa") or die("Can't connect sql server");
    mssql_select_db("frrc", $link) or die("Select database failure");
  
 /*
  
  好了本站原创文章转载注明来源http://www.111cn.net/phper/php.html
 */
在php mysql的web应用中我们经常会碰到上千万级的数据量,为了减轻服务器的负载我们经常会使用第三个工具来减压,下我们为你提供一款Memcache php提高mysql负载有效方法哦。

Memcache的理由:
1.Web Server(Lighttpd、Nginx据说都比Apache效率高好多,大家可以试用下)对CPU要求高,对内存要求低;而Memcached Server是对CPU要求低,对内存要求高,所以可以搭配使用。在对前端的Web Server上安装Memcached Server是可行的。
2.金钱金钱金钱,最少的付出,获得最大的收益。
3.简单简单简单,对于一个架构合理的系统来说,添加Memcache的支持可能只是一个批量处理文件的过程

Discuz!使用Memcache
1.在config.inc.php中增加

 代码如下 复制代码

$memcachehost = '127.0.0.1';
$memcacheport = 11211;
$memcachelife = 60;
2.在include/common.inc.php中

$mem = new Memcache;
$mem->connect($memcachehost, $memcacheport);
3.修改include/db_mysql.class.php中的fetch_array、query这两个方法,并添加query_mysql方法,代码如下:

function fetch_array($query, $result_type = MYSQL_ASSOC) {
return is_resource($query) ? mysql_fetch_array($query, $result_type) : $query[0];
}

function query_memcache($sql, $type = '') {
global $mem,$memcachelife;

$key = md5($sql);
if(!($query = $mem->get($key))) {
$query = $this->query($sql, $type);
while($item = $this->fetch_array($query)) {
$res[] = $item;
}
$query = $res;
$mem->set($key, $query , 0, $memcachelife);
}
return $query;
}

function query($sql, $type = '') {
global $debug, $discuz_starttime, $sqldebug, $sqlspenttimes;

$func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ?
'mysql_unbuffered_query' : 'mysql_query';
if(!($query = $func($sql, $this->link)) && $type != 'SILENT') {
$this->halt('MySQL Query Error', $sql);
}

if(substr($sql, 0, 6) == 'SELECT') {
echo '<font color="red">Cache SQL</font>:<font color="green">'.$sql.'</font><br /><br />';
} else {
echo '<font color="red">Flash SQL</font>:<font color="green">'.$sql.'</font><br /><br />';
}

$this->querynum++;
return $query;
}

4.将需要使用Memcache缓存的SQL查询的代码由

$db->query(
修改为

 代码如下 复制代码
$db->query_memcache(


注意并将

 代码如下 复制代码
while($post = $db->fetch_array($query)) {


修改为

 代码如下 复制代码
foreach($query as $post) {


没有while的$db->fetch_array可以不用修改。

下面代码有用得着的就拿去:

preg_replace("/while([$](w+)s*=s*[$]db->fetch_array([$]query))/is", "foreach($query as $\1)", $file);
回头放出个小工具批量替换下就可以了。
在EditPlus中可以这样替换:while([$](.*) = [$]db->fetch_array([$]query))替换为foreach($query as $)

下面要为各位提供一款PHP mysql的购物车实例程序完整购物代码,从数据库的安装到入库,以及完成商品交易,都一一的举了实例,好了费话不说多了我看看这款码吧。
 代码如下 复制代码

if(!$session && !$scid) {
$session = md5(uniqid(rand()));
SetCookie("scid", "$session", time() + 14400);
} /* last number is expiration time in seconds, 14400 sec = 4 hrs */

class Cart {
function check_item($table, $session, $product) {
$query = "SELECT * FROM $table WHERE session='$session' AND product='$product' ";
$result = mysql_query($query);

if(!$result) {
return 0;
}

$numRows = mysql_num_rows($result);

if($numRows == 0) {
return 0;
} else {
$row = mysql_fetch_object($result);
return $row->quantity;
}
}

function add_item($table, $session, $product, $quantity) {
$qty = $this->check_item($table, $session, $product);
if($qty == 0) {
$query = "INSERT INTO $table (session, product, quantity) VALUES ";
$query .= "('$session', '$product', '$quantity') ";
mysql_query($query);
} else {
$quantity += $qty;
$query = "UPDATE $table SET quantity='$quantity' WHERE session='$session' AND ";
$query .= "product='$product' ";
mysql_query($query);
}
}

function delete_item($table, $session, $product) {
$query = "DELETE FROM $table WHERE session='$session' AND product='$product' ";
mysql_query($query);
}

function modify_quantity($table, $session, $product, $quantity) {
$query = "UPDATE $table SET quantity='$quantity' WHERE session='$session' ";
$query .= "AND product='$product' ";
mysql_query($query);
}

function clear_cart($table, $session) {
$query = "DELETE FROM $table WHERE session='$session' ";
mysql_query($query);
}

function cart_total($table, $session) {
$query = "SELECT * FROM $table WHERE session='$session' ";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
while($row = mysql_fetch_object($result)) {
$query = "SELECT price FROM inventory WHERE product='$row->product' ";
$invResult = mysql_query($query);
$row_price = mysql_fetch_object($invResult);
$total += ($row_price->price * $row->quantity);
}
}
return $total;
}

function display_contents($table, $session) {
$count = 0;
$query = "SELECT * FROM $table WHERE session='$session' ORDER BY id ";
$result = mysql_query($query);
while($row = mysql_fetch_object($result)) {
$query = "SELECT * FROM inventory WHERE product='$row->product' ";
$result_inv = mysql_query($query);
$row_inventory = mysql_fetch_object($result_inv);
$contents["product"][$count] = $row_inventory->product;
$contents["price"][$count] = $row_inventory->price;
$contents["quantity"][$count] = $row->quantity;
$contents["total"][$count] = ($row_inventory->price * $row->quantity);
$contents["description"][$count] = $row_inventory->description;
$count++;
}
$total = $this->cart_total($table, $session);
$contents["final"] = $total;
return $contents;
}

function num_items($table, $session) {
$query = "SELECT * FROM $table WHERE session='$session' ";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
return $num_rows;
}

function quant_items($table, $session) {
$quant = 0;
$query = "SELECT * FROM $table WHERE session='$session' ";
$result = mysql_query($query);
while($row = mysql_fetch_object($result)) {
$quant += $row->quantity;
}
return $quant;
}
}
?>

/*
This part contains a description of how to create the tables on your mysql server.

# MySQL dump 6.0
#
# Host: localhost Database: kmartShopper
#--------------------------------------------------------
# Server version 3.22.25

#
# Table structure for table 'inventory'
#
CREATE TABLE inventory (
product tinytext NOT NULL,
quantity tinytext NOT NULL,
id int(4) DEFAULT '0' NOT NULL auto_increment,
description tinytext NOT NULL,
price float(10,2) DEFAULT '0.00' NOT NULL,
category char(1) DEFAULT '' NOT NULL,
KEY id (id),
PRIMARY KEY (id),
KEY price (price)
);

#
# Table structure for table 'shopping'
#
CREATE TABLE shopping (
session tinytext NOT NULL,
product tinytext NOT NULL,
quantity tinytext NOT NULL,
card tinytext NOT NULL,
id int(4) DEFAULT '0' NOT NULL auto_increment,
KEY id (id),
PRIMARY KEY (id)
);
*/

Example
<?
include("shoppingcart.php教程");
$cart = new Cart;
$mysql_link = mysql_connect("localhost", "wwwrun", "");
$mysql_select_db("kmartShopper", $mysql_link) /* heh, use whatever database name you put the 2 tables under in place of kmartShopper */
?>

<table align=center border=0 cellspacing=0 cellpadding=0>
<?
for ($y=0;$y<16;$y++)
{
echo "<tr height=4>n";

for ($x=0;$x<16;$x++)
{
$abs00=sqrt(($x*$x)+($y*$y));
if ($abs00>16)
$abs00=16;

$abs01=sqrt(($x*$x)+((16-$y)*(16-$y)));
if ($abs01>16)
$abs01=16;

$abs10=sqrt(((16-$x)*(16-$x))+($y*$y));
if ($abs10>16)
$abs10=16;

$red=((16-$abs00)*16)-1;
if ($red<0)
$red=0;

$green=((16-$abs01)*16)-1;
if ($green<0)
$green=0;
$blue= ((16-$abs10)*16)-1;
if ($blue<0)
$blue=0;

$col = sprintf("%02x%02x%02x",$red,$green,$blue);
echo " <td width=4 bgcolor="#$col">($red,$green,$blue=$col)<a href="$PHP_SELF?color=$col"><img" width=100% src=images/blank.gif width=4 height=4 border=0 alt="$col"></a></td>n";
}

echo "</tr>n";
}
?>
</table>
<?php教程
echo "<P><CENTER><font color=$color><U><B>大家好,这个颜色可以了吗?</B></U></font></CENTER>";
?>

<?
/ /原来是Zend.com,由亨特reproducted

/ *
用法:$ new_password = return_password();
示例:生成密码:2X5bjj2z,ERgid62Y,p2sHtDPv
* /

 代码如下 复制代码

function return_password () {

// set password length
$pw_length = 8;
// set ASCII range for random character generation
$low_ascii_bound = 50; // "2"
$upper_ascii_bound = 122; // "z"

// Exclude special characters and some confusing alphanumerics

排除一些特殊字符和字母数字混淆
// o,O,0,I,1,l etc
$notuse = array (58,59,60,61,62,63,64,73,79,91,92,93,94,95,96,108,111);

while ($i < $pw_length) {
mt_srand ((double)microtime() * 1000000);
// random limits within ASCII table
$randnum = mt_rand ($low_ascii_bound, $top_ascii_bound);
if (!in_array ($randnum, $notuse)) {
$password = $password . chr($randnum);
$i++;
}
}

return $password;
}

标签:[!--infotagslink--]

您可能感兴趣的文章: