Mysql數據庫連接、查詢、記錄集操作代碼


Mysql數據庫鏈接代碼

function dbConnect($hostname,$username,$pass,$db_name,$pconnect	=0)	
{
    $func=empty($pconnect) ? 'mysql_connect':'mysql_pconnect';
   
    if(!$connect){
        $connect=@$func($hostname,$username,$pass) or die("<font size='2'>Mysql_Error : ".mysql_error()."<br>Mysql Error Num : ".mysql_errno()."</font>");
                 }
   
    @mysql_select_db($db_name,$connect) or die("<font size='2'> Mysql_Error : ".mysql_error()."<br>Mysql Error Num : ".mysql_errno()."</font>");

    return $connect;
}

 

注釋

參 數$hostname,$username,$pass,$db_name分別代表Mysql數據庫服務器地址,用戶名,密碼,以及連接的數據庫名,通常 情況下hostname一般都是localhost或者127.0.0.1。參數$pconnect默認為0,表示通常情況下是以 mysql_connect函數連接Mysql數據庫。

 

知識點

mysql_connect與mysql_pconnect的區別: 當執行完當前PHP程序后,PHP自動關閉mysql_connect建立的數據庫連接,而mysql_pconnect返回一個持久穩固的數據庫連接, 在一定時間內有下一個連接請求時可以被復用,節省了反復連接Mysql數據庫的時間,使得訪問速度加快,其適用於並發訪問量不大的情況,如並發訪問量比較 大,則可能會因為Mysql已達到最大連接數, 使之后的請求得不到滿足。

mysql_error函數:返回上一個Mysql操作產生的文本錯誤信息。mysql_errno函數返回上一個Mysql操作中的錯誤號碼,如果沒有出錯則返回0。

 Mysql數據庫查詢代碼

function query_error($query)
{
    global	$connect;
    $temp_bar	=	"<br>=============================================================================<br>";
    $result	=	mysql_query($query,	$connect) or die("DB ERROR <br>".$temp_bar."<font size='2'> Mysql_Query : ".$query."<br> Mysql_Error : ".mysql_error()."<br> Mysql Error Num : ".mysql_errno()."</font>".$temp_bar);
    return	$result;
}

 

注釋:此函數為Mysql數據庫查詢函數,等於同mysql_query函數的功能,如果出錯則輸出出錯信息(SQL語句),其實為了防止暴露網站數據庫的結構,正式商用時,最好不要輸出SQL執行語句。

Mysql記錄集操作函數代碼(mysql_fetch_array)

function fetch_array($result,$result_type	= MYSQL_ASSOC,$records	=	"one")
{
    if	($records	==	"one")	{
        return	@mysql_fetch_array($result,$result_type);
    }
    else	{
        for	($i=0;num_rows($result);$i++)
        {
            $info[$i]	=	@mysql_fetch_array($result,$result_type);
        }
       
        free_result($result);
       
        return	$info;
    }
}

 

注釋:此函數的功能由mysql_fetch_array函數延生而來,在此基礎上我增加了對Mysql數據庫記錄集的讀取功能,並以數組形式返回獲取的值。

知識點

mysql_fetch_array函數是mysql_fetch_row函數的擴展版本。第二個參數 result_type有三個值:MYSQL_ASSOC,MYSQL_NUM 和 MYSQL_BOTH。默認值是 MYSQL_BOTH。MYSQL_BOTH:得到一個同時包含關聯和數字索引的數組。MYSQL_ASSOC:只得到關聯索引(如同mysql_fetch_assoc()那樣),MYSQL_NUM :得到數字索引(如同 mysql_fetch_row()那樣)。

報錯信息函數代碼

function error_msg($msg,	$url=	"")
{
    global	$connect;

    if($connect)	{
        mysql_close($connect);
    }

    switch	($url)
    {
        case	"":
            $url	=	"history.go(-1)";
            break;
        case	"close":
            $url	=	"window.close()";
            break;
        default:
            $url	=	"document.location.href = '$url'";
            break; 
    }
   
    if	(!empty($msg))	{
        echo	"<script language='javascript'>alert('$str');$url;</script>";
    }
    else{
        echo	"<script language='javascript'>$url;</script>";
    }
    exit;
}

 

注釋:此函數的功能主要以alert的形式報錯並進行頁面跳轉,是一個通用函數,報錯或跳轉之前其會先將Mysql數據庫連接關閉,用到了mysql_close函數。

調用說明

從上述Mysql數據庫操作的函數代碼中,我們可以看到$connect變量是一個全局變量,首先將上述幾個函數放入一個文件,如mysqlconnect.php中,然后在聲明相關變量並賦值,在dbConnect函數聲明后調用此Mysql數據庫連接函數,即:

$hostname	=	"mysqlserveraddr";
$username	=	"yourusername";
$pass	=	"youruserpass";
$db_name	=	"yourdatabase";

$connect	= dbConnect($hostname,$username,$pass,$db_name);

 總結:

  通過上面幾個Mysql數據庫連接、數據庫查詢、數據庫記錄集操作函數代碼的講解,在PHP網站開發中Mysql數據庫操作的基本函數已包括,根據需要可在此代碼基礎上改成Mysql數據庫類或者利用PHP添加其他的Mysql數據庫操作函數都是可行的

練習建一個簡單的管理頁面

1.管理頁面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
</head>

<body>

<table  style="caption-side:top; width:90%; border:0px; font:normal, Georgia, 'Times New Roman', Times, serif; size:auto"
 cellpadding="0" cellspacing="1" bgcolor="#FF0000" >
 <caption align="center" style="size:+4">管理頁面</caption>
<tr bgcolor="#FFFFFF">
<td>民族代號</td>
<td>民族</td>
<td>操作</td>
</tr>
<?php
  $connect=@mysql_connect("localhost","root","");
  mysql_select_db("1",$connect);
  $a="select * from nation";
  $result=mysql_query($a);
  while($arr=mysql_fetch_row($result))
  {
	  echo "<tr bgcolor='#FFFFFF'>
		  <td>{$arr[0]}</td>
		  <td>{$arr[1]}</td>
		  <td><a onclick=\" return confirm('確定刪除')\" href='shanchu.php?code={$arr[0]}'>刪除</a>&nbsp&nbsp<a href='xiugai.php?code={$arr[0]}'>修改</a></td>
	       </tr>
	       ";
  }
?>
 
</table>

<a href="tianjia.php"><input type="submit"  value="添加"  /></a>   <a href="beifen.php"><input type="submit"  value="備份" /></a>

</body>
</html>

 

2 添加頁面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
</head>

<body>
<form action="tianjia1.php" method="post">
<div>民族代號<input type="text" name="code" /></div>
<div>民族名稱<input type="text" name="name" /></div>
<input type="submit" value="確認"/>
</form>
</body>
</html>

 2.1添加處理頁面

<?php

$a=$_POST["code"];
$b=$_POST["name"];
$connect=@mysql_connect("localhost","root","");
mysql_select_db("1",$connect);
$sql="insert into nation value ('$a','$b') ";
$result=mysql_query($sql);
if($result)
{
	header("location:xianshi.php");
}
else
{
	echo "添加失敗";
}

 3.刪除處理頁

<?php
$code=$_GET["code"];
$connect=@mysql_connect("localhost","root","");
mysql_select_db("1",$connect);
$sql="delete from nation where code='$code'";
$result=mysql_query($sql);
if($result)
{
	header("location:xianshi.php");
}
else
{
	echo "添加失敗";
}
?>

 4備份處理頁

<?php 
// 備份數據庫
$host = "localhost";
$user = "root"; //數據庫賬號
$password = ""; //數據庫密碼
$dbname = "1"; //數據庫名稱
// 這里的賬號、密碼、名稱都是從頁面傳過來的
if (@!mysql_connect($host, $user, $password)) // 連接mysql數據庫
    {
        echo '數據庫連接失敗,請核對后再試';
    exit;
} 
if (@!mysql_select_db($dbname)) // 是否存在該數據庫
    {
        echo '不存在數據庫:' . $dbname . ',請核對后再試';
    exit;
} 
mysql_query("set names 'utf8'");
$mysql = "set charset utf8;\r\n";
$q1 = mysql_query("show tables");
while ($t = mysql_fetch_array($q1))
{
    $table = $t[0];
    $q2 = mysql_query("show create table `$table`");
    $sql = mysql_fetch_array($q2);
    $mysql .= $sql['Create Table'] . ";\r\n";
    $q3 = mysql_query("select * from `$table`");
    while ($data = mysql_fetch_assoc($q3))
    {
        $keys = array_keys($data);
        $keys = array_map('addslashes', $keys);
        $keys = join('`,`', $keys);
        $keys = "`" . $keys . "`";
        $vals = array_values($data);
        $vals = array_map('addslashes', $vals);
        $vals = join("','", $vals);
        $vals = "'" . $vals . "'";
        $mysql .= "insert into `$table`($keys) values($vals);\r\n";
    } 
} 
 
$filename = $dbname . date('Ymjgi') . ".sql"; //存放路徑,默認存放到項目最外層
$fp = fopen($filename, 'w');
fputs($fp, $mysql);
fclose($fp);
echo "備份成功
    <a href=\"xianshi.php\"><input type=\"button\" value=\"返回\"
     /></a> ";
 
?>

 4修改頁

<?php
$a=$_GET["code"];//獲取數據
$connect=@mysql_connect("localhost","root","");//造鏈接
mysql_select_db("1",$connect);//選擇操作的數據庫
$sql="select * from nation where code=\"{$a}\" ";//數據庫需要執行的操作
$result=mysql_query($sql);//執行操作
$b=mysql_fetch_row($result);//轉成數組

echo "<form action=\"xiugai1.php?code={$a}\"method=\"post\">
<div>民族代號<input type=\"text\" name=\"code\" value=\"{$b[0]}\" readonly=\"readonly\"/></div>
<div>民族名稱<input type=\"text\" name=\"name\" value=\"{$b[1]}\"/></div>
<input type=\"submit\" value=\"確認\"/>
</form>";
?>

 

 

4-1修改處理頁

<?php
$code=$_GET["code"];
$a=$_POST["code"];
$b=$_POST["name"];
$connect=@mysql_connect("localhost","root","");
mysql_select_db("1",$connect);
$sql="update nation set name='{$b}' where code='{$code}'";
$result=mysql_query($sql);
if($result)
{
	header("location:xianshi.php");
}
else
{
	echo "修改失敗";
}
?>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM