php向Mysql資料庫儲存資料程式碼範例

來源:互聯網
上載者:User

PHP向MySQL資料庫中寫入資料有三個步驟:

1,PHP和MySQL建立串連關係
2,開啟MySQL資料庫
3,接受頁面資料,PHP錄入到指定的表中
1、2兩步可直接使用一個資料庫連結檔案即可:conn.php

 代碼如下 複製代碼

<?php
mysql_connect("localhost","root","");//串連MySQL
mysql_select_db("mythroad");//選擇資料庫
?>

當然,前提是已經安裝WEB伺服器、PHP和MySQL,並且建立MySQL表“mythroad”
mysql_connect()中三個參數分別為MySQL地址、MySQL使用者名稱和MySQL密碼
然後就是通過WEB頁面傳遞資料,讓PHP通過SQL語句將資料寫入MySQL資料庫指定的表中,比如建立檔案
post.php

 代碼如下 複製代碼

<?php
require_once("conn.php");//引用資料庫連結檔案
$uname = $_GET['n'];//GET方法為URL參數傳遞
$pwd = $_GET['p'];
$pwd =md5($pwd );//直接使用MD5加密
$sql = "insert into mythroad(username,password) values ('$uname','$pwd')";
mysql_query($sql);//借SQL語句插入資料
mysql_close();//關閉MySQL串連
echo "成功錄入資料";
?>

測試頁面: http://127.0.0.1/post.php?n=mythroad&p=mythroad
即可向MySQL資料庫hello的members表中插入新的資料“mythroad”到username欄位、“mythroad”到password欄位

如果使用表單post 我們可以利用post接受,下面看update更新資料

例子:

 代碼如下 複製代碼

<?php
$conn = @mysql_connect("localhost","root","root123");
if (!$conn){
    die("串連資料庫失敗:" . mysql_error());
}

mysql_select_db("test", $conn);
mysql_query("set names 'gbk'");

$sql = "UPDATE user SET email = 'xiaoming@163.com' WHERE username = '小明'";
if(mysql_query($sql,$conn)){
    echo "更新資料成功!";
} else {
    echo "更新資料失敗:".mysql_error();
}
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.