PHP全棧學習筆記5

PHP全棧學習筆記5

php與mysql數據庫,PHP支持不少數據庫,與mysql爲牛逼組合,mysql數據庫的基礎知識的掌握是由必要的,要了解如何操做mysql數據庫,數據表的方法。javascript

什麼是數據庫,數據庫能作什麼,數據庫有什麼好處,數據庫的基礎必備技術,備份和恢復的方法。php

image.png

image.png

mysql的好處,功能強大,支持跨平臺,運行速度快,支持面向對象,成本低,支持各類開發語言,數據庫存儲容量大,支持強大的內置函數。css

啓動MySQL服務器html

net start mysql

鏈接數據庫:java

mysql  –u root   –h127.0.0.1   –p password

斷開MySQL服務器:mysql

quit;

中止MySQL服務器:sql

net stop mysql;

mysqladmin –uroot shutdown –proot

數據庫的操做:數據庫

image.png

image.png

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] 數據表名
[(create_definition,…)][table_options] [select_statement]
temporary 表示建立一個臨時表
if not exists 表示表是否已經存在
create_definition 表的一些特性
select_statement 快速建立表
col_name  type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]
           [PRIMARY KEY ] [reference_definition]

create table table_name (列名1 屬性,列名2 屬性…);
col_name 字段名
type 字段類型
not null | null 指出該列是否容許控制
default 表示默認值
auto_increment 表示是否自動編號
primary key 表示是否爲主鍵
一個表只能有一個主鍵,若是表中沒有主鍵,mysql會返回第一個沒有任何null列的unique鍵,做爲主鍵。
reference_definition 爲字段添加註解
create table tb_admin (
id int auto_increment primary key,
user varchar(30) not null,
password varchar(30) not null,
createtime datetime
);

查看錶結構:數組

SHOW  [FULL] COLUMNS  FROM 數據表名 [FROM 數據庫名];

DESCRIBE 數據表名;

修改表結構:服務器

ALTER[IGNORE] TABLE 數據表名 alter_spec[,alter_spec]…

image.png

重命名錶:

RENAME TABLE 數據表名1 To 數據表名2

刪除表:

DROP TABLE 數據表名;
drop table if exists 數據表名;

數據庫的操做:插入已解決insert,查詢select,修改update,刪除記錄delete。

插入記錄insert

insert  into 數據表名(column_name,column_name2, … ) values (value1, value2, … )

查詢數據庫:

select selection_llist from 數據表名 where primary_constraint group by grouping_columns order by sorting_columns having secondary_constraint limit count
表1.字段=表2.字段 and 其餘查詢條件

select 字段名 from 表1,表2…… where 表1.字段=表2.字段 and 其餘查詢條件

update 數據表名set column_name = new_value1,column_name2 = new_value2, …where condition

delete from 數據表名 where condition

數據庫備份和恢復:

使用MYSQLDUMP命令,進行數據的備份。

mysql -uroot –proot db_database <F:\db_database.txt」

image.png

image.png

image.png

image.png

image.png

image.png

php操做數據庫

mysql_connect()函數鏈接mysql服務器

mysql_select_db()函數選擇數據庫

mysql_query()函數執行sql語句

mysql_fetch_array()函數從數組結果集中獲取信息

mysql_fetch_row()函數逐行獲取結果集中的每條記錄

mysql_num_rows()函數獲取查詢結果集中的記錄數

insert動態添加

select語句查詢

update動態修改

delete動態刪除

MySQL是一款廣受歡迎的數據庫
開源的半商業軟件
市場佔有率高
PHP具備強大的數據庫支持能力

image.png

查詢,顯示,插入,更新,刪除

關閉MySQL服務器
每使用一次mysql_connect()或mysql_query()函數,都會消耗系統資源。
使用mysql_close()函數關閉與MySQL服務器的鏈接,以節省系統資源。

mysql_close($Link);

image.png

<?php
$link = mysql_connect("localhost", "root", "root") or die("用戶名密碼有誤!".mysql_error());   //鏈接Mysql服務器
if($link){ 
echo "數據源鏈接成功!";
}
?>

// mysql_connect('hostname','username','password');
<?php
$link = mysql_connect("localhost", "root", "root") or die("用戶名密碼有誤!".mysql_error());   //鏈接Mysql服務器
$db_selected=mysql_select_db("db_database1",$link);
//$db_selected=mysql_query("use db_database1",$link);
if($db_selected){
echo "數據庫選擇成功!";
}
?>

// mysql_select_db ( string數據庫名[,resource link_identifier] ) 

// mysql_query("use數據庫名"[,resource link_identifier]);
<?php
$db = array (
        'server' => 'localhost',
        'port' => '3306',
        'username' => 'root',
        'password' => 'root',
        'database' => 'dashu' 
);
$conn = @mysql_connect($db['server'].':'.$db['port'],$db['username'],$db['password']);
if (! $conn) {
    echo "服務器不能連!" . mysql_error();
} else {
    // 聲明字符集
    mysql_set_charset('utf8', $conn);
    // 選擇數據庫
    mysql_select_db($db['database'], $conn);
}
<?php
$link = mysql_connect("localhost", "root", "root") or die("數據庫鏈接失敗".mysql_error());
mysql_select_db("db_database",$link);
mysql_query("set names gb2312");
$sql=mysql_query("select * from tb_book");
$info= mysql_fetch_array($sql);

if($_POST[Submit] == "查詢"){
 $tet_book = $POST[txt_book];
 $sql = mysql_query("select * from tb_book where bookname like '%".trim($txt_book)."%' ");
 $info=mysql_fetch_array($sql);
}

mysql_fetch_array()函數從數組結果集中獲取信息:

array mysql_fetch_array ( resource result [, int result_type] )

mysql_fetch_object()函數從結果集中獲取一行做爲對象

object  mysql_fetch_object ( resource result )
對象
<?php echo $info -> id; ?></td>
<?php echo $info -> issuDate; ?></td>
<?php echo $info -> first_name; ?></td>

數組
<?php echo $info[id]; ?></td>

do{

}while($info=mysql_fetch_array($sql));

mysql_fetch_row()函數逐行獲取結果集中的每條記錄

array mysql_fetch_row ( resource result )

image.png

mysql_num_rows()函數獲取查詢結果集中的記錄數

int mysql_num_rows ( resource result )
<?php $nums = mysql_num_rows($sql); echo $nums; ?>

PHP操做MySQL數據庫

<?php
 function chinesesubstr($str,$start,$len) { 
    $strlen=$start+$len; 
    for($i=0;$i<$strlen;$i++) { 
        if(ord(substr($str,$i,1))>0xa0) { 
            $tmpstr.=substr($str,$i,2); 
            $i++; 
         } 
        else 
            $tmpstr.=substr($str,$i,1); 
    } 
    return $tmpstr; 
}
?>

實例:

onClick="return check(form1);"

<script language="javascript">
function check(form){
    if(form.txt_title.value==""){
        alert("請輸入公告標題!");form.txt_title.focus();return false;
    }
    if(form.txt_content.value==""){
        alert("請輸入公告內容!");form.txt_content.focus();return false;
    }
form.submit();
}
</script>
<?php
    $conn=mysql_connect("localhost","root","root") or die("數據庫服務器鏈接錯誤".mysql_error());
    mysql_select_db("db_database18",$conn) or die("數據庫訪問錯誤".mysql_error());
    mysql_query("set names gb2312");
    $title=$_POST[txt_title];
    $content=$_POST[txt_content];
    $createtime=date("Y-m-d H:i:s");
    $sql=mysql_query("insert into tb_affiche(title,content,createtime)values('$title','$content','$createtime')");
    echo "<script>alert('公告信息添加成功!');window.location.href='add_affiche.php';</script>";
    mysql_free_result($sql);
    mysql_close($conn);
?>

image.png

<script language="javascript">
function check(form){
    if(form.txt_keyword.value==""){
        alert("請輸入查詢關鍵字!");form.txt_keyword.focus();return false;
    }
form.submit();
}
</script>

image.png

<?php
 function chinesesubstr($str,$start,$len) { 
    $strlen=$start+$len; 
    for($i=0;$i<$strlen;$i++) { 
        if(ord(substr($str,$i,1))>0xa0) { 
            $tmpstr.=substr($str,$i,2); 
            $i++; 
         } 
        else 
            $tmpstr.=substr($str,$i,1); 
    } 
    return $tmpstr; 
}
?>

update語句動態

<script language="javascript">
function check(form){
    if(form.txt_title.value==""){
        alert("公告標題不能爲空!");form.txt_title.focus();return false;
    }
    if(form.txt_content.value==""){
        alert("公告內容不能爲空!");form.txt_content.focus();return false;
    }
form.submit();
}
</script>

<?php 
$conn=mysql_connect("localhost","root","root") or die("數據庫服務器鏈接錯誤".mysql_error());
mysql_select_db("db_database18",$conn) or die("數據庫訪問錯誤".mysql_error());
mysql_query("set names gb2312");
$id=$_GET[id];
$sql=mysql_query("select * from tb_affiche where id=$id");
$row=mysql_fetch_object($sql);
?>

<form name="form1" method="post" action="check_modify_ok.php">
                              <table width="520" height="212"  border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
                                <tr>
                                  <td width="87" align="center">公告主題:</td>
                                  <td width="433" height="31"><input name="txt_title" type="text" id="txt_title" size="40" value="<?php echo $row->title;?>">
                                  <input name="id" type="hidden" value="<?php echo $row->id;?>"></td>
                                </tr>
                                <tr>
                                  <td height="124" align="center">公告內容:</td>
                                  <td><textarea name="txt_content" cols="50" rows="8" id="txt_content"><?php echo $row->content;?></textarea></td>
                                </tr>
                                <tr>
                                  <td height="40" colspan="2" align="center"><input name="Submit" type="submit" class="btn_grey" value="修改" onClick="return check(form1);">                                    &nbsp;                                    <input type="reset" name="Submit2" value="重置"></td></tr>
                              </table>
                          </form>

<?php
$conn=mysql_connect("localhost","root","root") or die("數據庫服務器鏈接錯誤".mysql_error());
mysql_select_db("db_database18",$conn) or die("數據庫訪問錯誤".mysql_error());
mysql_query("set names gb2312");
$title=$_POST[txt_title];
$content=$_POST[txt_content];
$id=$_POST[id];
$sql=mysql_query("update tb_affiche set title='$title',content='$content' where id=$id");
if($sql){
    echo "<script>alert('公告信息編輯成功!');history.back();window.location.href='modify.php?id=$id';</script>";
}else{
    echo "<script>alert('公告信息編輯失敗!');history.back();window.location.href='modify.php?id=$id';</script>";
}
?>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">

image.png

image.png

image.png

<!--  翻頁條 -->
                            <td width="37%">&nbsp;&nbsp;頁次:<?php echo $_GET[page];?>/<?php echo $page_count;?>頁&nbsp;記錄:<?php echo $message_count;?> 條&nbsp; </td>
                            <td width="63%" align="right">
                            <?php
                            /*  若是當前頁不是首頁  */
                            if($_GET[page]!=1){
                            /*  顯示「首頁」超連接  */
                            echo  "<a href=page_affiche.php?page=1>首頁</a>&nbsp;";
                            /*  顯示「上一頁」超連接  */
                            echo "<a href=page_affiche.php?page=".($_GET[page]-1).">上一頁</a>&nbsp;";
                            }
                            /*  若是當前頁不是尾頁  */
                            if($_GET[page]<$page_count){
                            /*  顯示「下一頁」超連接  */
                            echo "<a href=page_affiche.php?page=".($_GET[page]+1).">下一頁</a>&nbsp;";
                            /*  顯示「尾頁」超連接  */
                            echo  "<a href=page_affiche.php?page=".$page_count.">尾頁</a>";
                            }
                            mysql_free_result($sql);
                            mysql_close($conn);
                            ?>

編輯:

<?php
$conn=mysql_connect("localhost","root","root") or die("數據庫服務器鏈接錯誤".mysql_error());
mysql_select_db("db_database18",$conn) or die("數據庫訪問錯誤".mysql_error());
mysql_query("set names gb2312");
$title=$_POST[txt_title];
$content=$_POST[txt_content];
$id=$_POST[id];
$sql=mysql_query("update tb_affiche set title='$title',content='$content' where id=$id");
if($sql){
    echo "<script>alert('公告信息編輯成功!');history.back();window.location.href='modify.php?id=$id';</script>";
}else{
    echo "<script>alert('公告信息編輯失敗!');history.back();window.location.href='modify.php?id=$id';</script>";
}
?>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<?php
$conn=mysql_connect("localhost","root","root") or die("數據庫服務器鏈接錯誤".mysql_error());
mysql_select_db("db_database18",$conn) or die("數據庫訪問錯誤".mysql_error());
mysql_query("set names gb2312");
$title=$_POST[txt_title];
$content=$_POST[txt_content];
$id=$_POST[id];
$sql=mysql_query("update tb_affiche set title='$title',content='$content' where id=$id");
if($sql){
    echo "<script>alert('公告信息編輯成功!');history.back();window.location.href='modify.php?id=$id';</script>";
}else{
    echo "<script>alert('公告信息編輯失敗!');history.back();window.location.href='modify.php?id=$id';</script>";
}
?>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">

練習:

<html>
<head>
<title>新聞</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<?php
 function chinesesubstr($str,$start,$len) { 
    $strlen=$start+$len; 
    for($i=0;$i<$strlen;$i++) { 
        if(ord(substr($str,$i,1))>0xa0) { 
            $tmpstr.=substr($str,$i,2); 
            $i++; 
         } 
        else 
            $tmpstr.=substr($str,$i,1); 
    } 
    return $tmpstr; 
}
?>
<table width="600" height="100" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFCC">
  <tr>
    <td width="600" height="257" align="center" valign="top" background="images/image_08.gif"><table width="579" height="271"  border="0" cellpadding="0" cellspacing="0">
        <tr>
          <td width="579" height="50" align="center" class="word_orange"><span class="style1">熱焦新聞</span></td>
        </tr>
        <tr>
          <td height="249" align="center" valign="top">              <table width="460"  border="1" align="center" cellpadding="1" cellspacing="1" bordercolor="#FFFFCC" bgcolor="#DFDFDF">
                <?php
                    $conn=mysql_connect("localhost","root","root") or die("數據庫服務器鏈接錯誤".mysql_error());
                    mysql_select_db("db_database18",$conn) or die("數據庫訪問錯誤".mysql_error());
                    mysql_query("set names gb2312");
                    $sql=mysql_query("select * from tb_affiche order by createtime desc limit 0,10");
                    $info=mysql_fetch_array($sql);
                    if($info==false){
                      echo "本站暫無公告信息!";
                     }
                    else{
                    $i=0;
                      do{ 
                  ?>
                <tr bgcolor="#E3E3E3">
                  <td height="24" align="left" bgcolor="#FFFFFF">&nbsp;&nbsp;
                      <?php 
                                $i=$i+1;    
                                echo $i."、".chinesesubstr($info[title],0,40);
                                  if(strlen($info[title])>40){
                                    echo "...";

                                  } 
                               ?>
                      <em>&nbsp;[<?php echo $info[createtime];?>]</em> </td>
                </tr>
                <?php
                      }while($info=mysql_fetch_array($sql));
                   }
                    mysql_free_result($sql);                                //關閉記錄集
                    mysql_close($conn);                                 //關閉MySQL數據庫服務器
                  ?>
            </table></td>
        </tr>
    </table></td>
  </tr>
</table>
</body>
</html>

封裝類數據庫鏈接,操做,分頁,字符串截取

<?php
//數據庫鏈接類
class ConnDB{
    var $dbtype;
    var $host;
    var $user;
    var $pwd;
    var $dbname;
    var $conn;    
    function ConnDB($dbtype,$host,$user,$pwd,$dbname){      //構造方法,爲成員變量賦值
        $this->dbtype=$dbtype;
        $this->host=$host;
        $this->user=$user;
        $this->pwd=$pwd;
        $this->dbname=$dbname;
    }
    function GetConnId(){                                   //實現與數據庫的鏈接並返回鏈接對象
        $this->conn=mysql_connect($this->host,$this->user,$this->pwd) or die("數據庫服務器鏈接錯誤".mysql_error());
        mysql_select_db($this->dbname,$this->conn) or die("數據庫訪問錯誤".mysql_error());
        mysql_query("set names gb2312");                    //設置數據庫的編碼格式
        return $this->conn;                                 //返回鏈接對象
    }
    function CloseConnId(){                                 //定義關閉數據庫的方法
            $this->conn->Disconnect();                  //執行關閉的操做
    }
}   

//數據庫管理類
class AdminDB{
    function ExecSQL($sqlstr,$conn){                    //定義方法,參數爲SQl語句和鏈接數據庫返回的對象
        $sqltype=strtolower(substr(trim($sqlstr),0,6)); //截取SQL中的前6個字符串,並轉換成小寫
        $rs=mysql_query($sqlstr);                   //執行SQL語句
        if($sqltype=="select"){                     //判斷若是SQL語句的類型爲SELECT
            $array=mysql_fetch_array($rs);              //執行該語句,獲取查詢結果
            if(count($array)==0 || $rs==false)          //判斷語句是否執行成功
                return false;                   //若是查詢結果爲0,或者執行失敗,則返回false
            else
                return $array;                  //不然返回查詢結果的數組
        }elseif ($sqltype=="update" || $sqltype=="insert" || $sqltype=="delete"){
            //判斷若是SQL語句類型不爲select、則執行以下操做
            if($rs)
                return true;                        //執行成功返回true
            else 
                return false;                       //是否返回false
        }
    }
}


//分頁類
class SepPage{
    var $rs;
    var $pagesize;                  //定義每頁顯示的記錄數
    var $nowpage;                   //當前頁碼
    var $array;
    var $conn;
    var $sqlstr;                    //執行的SQL語句
    var $total;
    var $pagecount;                 //總的記錄數
    function ShowDate($sqlstr,$conn,$pagesize,$nowpage){    //定義方法
        $arrays=array();
        $array_title=array();
        $array_content=array();
        if(!isset($nowpage) || $nowpage=="" || $nowpage==0)         //判斷當前頁變量值是否爲空
            $this->nowpage=1;                       //定義當前頁的值
        else
            $this->nowpage=$nowpage;                //獲取當前頁的值
        
        $this->pagesize=$pagesize;                  //定義每頁輸出的記錄數
        $this->conn=$conn;                          //鏈接數據庫返回的標識
        $this->sqlstr=$sqlstr;                      //執行的查詢語句
        $this->pagecount=$pagecount;                //總的記錄數
        $this->total=$total;                        //總的記錄數
        
        $this->rs=mysql_query($this->sqlstr."limit ".$this->pagesize*($this->nowpage-1).",$this->pagesize",$this->conn);
        $this->total=mysql_num_rows($this->rs);         //獲取記錄數
        if($this->total==0){                                    //判斷若是查詢結果爲0,則輸出以下內容
            return false;     
       }else{                               //不然
            if(($this->total % $this->pagesize)==0){            //判斷若是總的記錄數除以每頁顯示的記錄數等於0
                $this->pagecount=intval($this->total/$this->pagesize);  //則爲變量pagecount賦值
            }else if($this->total<=$this->pagesize){
                $this->pagecount=1;//若是查詢結果小於等於每頁記錄數,那麼爲變量賦值爲1  
            }else{
                $this->pagecount=ceil($this->total/$this->pagesize);    //不然輸出變量值
            }
            while($this->array=mysql_fetch_array($this->rs)){
                array_push($array_title,$this->array[title]);
                array_push($array_content,$this->array[content]);
            }           
            array_push($arrays,$array_title,$array_content);
            return $arrays;
        }
    }
    function ShowPage($contentname,$utits,$anothersearchstr,$class){
        $allrs=mysql_query($this->sqlstr,$this->conn);      //執行查詢語句
        $record=mysql_num_rows($allrs);
        $pagecount=ceil($record/$this->pagesize);       //計算共有幾頁
        $str.="共有".$contentname."&nbsp;".$record."&nbsp;".$utits."&nbsp;每頁顯示&nbsp;".$this->pagesize."&nbsp;".$utits."&nbsp;第&nbsp;".$this->nowpage."&nbsp;頁/共&nbsp;".$pagecount."&nbsp;頁";
        $str.="&nbsp;&nbsp;&nbsp;&nbsp;";
        $str.="<a href=".$_SERVER['PHP_SELF']."?page=1".$anothersearchstr." class=".$class.">首頁</a>";
        $str.="&nbsp;";
        if(($this->nowpage-1)<=0){ 
            $str.="<a href=".$_SERVER['PHP_SELF']."?page=1".$anothersearchstr." class=".$class.">上一頁</a>";
        }else{
            $str.="<a href=".$_SERVER['PHP_SELF']."?page=".($this->nowpage-1).$anothersearchstr." class=".$class.">上一頁</a>";
        }
        $str.="&nbsp;"; 
        if(($this->nowpage+1)>=$pagecount){
            $str.="<a href=".$_SERVER['PHP_SELF']."?page=".$pagecount.$anothersearchstr." class=".$class.">下一頁</a>";
        }else{
            $str.="<a href=".$_SERVER['PHP_SELF']."?page=".($this->nowpage+1).$anothersearchstr." class=".$class.">下一頁</a>";
        }
        $str.="&nbsp;";
            $str.="<a href=".$_SERVER['PHP_SELF']."?page=".$pagecount.$anothersearchstr." class=".$class.">尾頁</a>";
        if(count($this->array)==0 || $this->rs==false)          
            return "";
        else
            return $str;    
    }
}
//系統經常使用方法
class UseFun{
    
    function chinesesubstr($str,$start,$len) { 
    $strlen=$start+$len; 
    for($i=0;$i<$strlen;$i++) { 
        if(ord(substr($str,$i,1))>0xa0) { 
            $tmpstr.=substr($str,$i,2); 
            $i++; 
         } 
        else 
            $tmpstr.=substr($str,$i,1); 
    } 
    return $tmpstr; 
}
    
}

?>
<?php
require("system..php");
//數據庫鏈接類實例化
$connobj=new ConnDB("mysql","localhost","root","root","db_database");
$conn=$connobj->GetConnId();
//數據庫操做類實例化
$admindb=new AdminDB();
//分頁類實例化
$seppage=new SepPage();
//字符串截取類
$unhtml=new UseFun();

?>

結言

好了,歡迎在留言區留言,與你們分享你的經驗和心得。

感謝你學習今天的內容,若是你以爲這篇文章對你有幫助的話,也歡迎把它分享給更多的朋友,感謝。

感謝!承蒙關照!您真誠的讚揚是我前進的最大動力!

image

image