把來(lái)自表單的數(shù)據(jù)插入數(shù)據(jù)庫(kù)

成都網(wǎng)絡(luò)公司-成都網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián)建站十多年經(jīng)驗(yàn)成就非凡,專業(yè)從事網(wǎng)站建設(shè)、成都做網(wǎng)站,成都網(wǎng)頁(yè)設(shè)計(jì),成都網(wǎng)頁(yè)制作,軟文發(fā)稿,廣告投放平臺(tái)等。十多年來(lái)已成功提供全面的成都網(wǎng)站建設(shè)方案,打造行業(yè)特色的成都網(wǎng)站建設(shè)案例,建站熱線:18980820575,我們期待您的來(lái)電!
現(xiàn)在,我們創(chuàng)建一個(gè) HTML 表單,這個(gè)表單可把新記錄插入 "Persons" 表。
這是這個(gè) HTML 表單:
1
2
3
4
5
6
7
8
9
10
11
12
html
body
form action="insert.php" method="post"
Firstname: input type="text" name="firstname" /
Lastname: input type="text" name="lastname" /
Age: input type="text" name="age" /
input type="submit" /
/form
/body
/html
當(dāng)用戶點(diǎn)擊上例中 HTML 表單中的提交按鈕時(shí),表單數(shù)據(jù)被發(fā)送到 "insert.php"。"insert.php" 文件連接數(shù)據(jù)庫(kù),并通過(guò) $_POST 變量從表單取回值。然后,mysql_query() 函數(shù)執(zhí)行 INSERT INTO 語(yǔ)句,一條新的記錄會(huì)添加到數(shù)據(jù)庫(kù)表中。
下面是 "insert.php" 頁(yè)面的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?
"是不是把數(shù)據(jù)庫(kù)建好然后導(dǎo)出.sql文件放在默認(rèn)的根目錄D:/www文件夾中?然后在php文件中直接用啊",你這么說(shuō),你是不是沒(méi)學(xué)過(guò)php?什么專業(yè)的。$db=new mysqli('localhost','root','root','users') 中,mysqli是一個(gè)類。你需要檢查一下這個(gè)類有沒(méi)有問(wèn)題。有沒(méi)有什么錯(cuò)誤提示呢??(謝謝采納)
serial_number.txt的示例內(nèi)容:
serial_number.txt:
DM00001A11 0116,
SN00002A11 0116,
AB00003A11 0116,
PV00004A11 0116,
OC00005A11 0116,
IX00006A11 0116,
創(chuàng)建數(shù)據(jù)表:
create table serial_number(
id int primary key auto_increment not null,
serial_number varchar(50) not null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
php代碼如下:
$conn = mysql_connect('127.0.0.1','root','') or die("Invalid query: " . mysql_error());
mysql_select_db('test', $conn) or die("Invalid query: " . mysql_error());
$content = file_get_contents("serial_number.txt");
$contents= explode(",",$content);//explode()函數(shù)以","為標(biāo)識(shí)符進(jìn)行拆分
foreach ($contents as $k = $v)//遍歷循環(huán)
{
$id = $k;
$serial_number = $v;
mysql_query("insert into serial_number (`id`,`serial_number`)
VALUES('$id','$serial_number')");
}
備注:方法有很多種,我這里是在拆分txt文件為數(shù)組后,然后遍歷循環(huán)得到的數(shù)組,每循環(huán)一次,往數(shù)據(jù)庫(kù)中插入一次。
再給大家分享一個(gè)支持大文件導(dǎo)入的
?php
/**
* $splitChar 字段分隔符
* $file 數(shù)據(jù)文件文件名
* $table 數(shù)據(jù)庫(kù)表名
* $conn 數(shù)據(jù)庫(kù)連接
* $fields 數(shù)據(jù)對(duì)應(yīng)的列名
* $insertType 插入操作類型,包括INSERT,REPLACE
*/
function loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields=array(),$insertType='INSERT'){
if(empty($fields)) $head = "{$insertType} INTO `{$table}` VALUES('";
else $head = "{$insertType} INTO `{$table}`(`".implode('`,`',$fields)."`) VALUES('"; //數(shù)據(jù)頭
$end = "')";
$sqldata = trim(file_get_contents($file));
if(preg_replace('/\s*/i','',$splitChar) == '') {
$splitChar = '/(\w+)(\s+)/i';
$replace = "$1','";
$specialFunc = 'preg_replace';
}else {
$splitChar = $splitChar;
$replace = "','";
$specialFunc = 'str_replace';
}
//處理數(shù)據(jù)體,二者順序不可換,否則空格或Tab分隔符時(shí)出錯(cuò)
$sqldata = preg_replace('/(\s*)(\n+)(\s*)/i','\'),(\'',$sqldata); //替換換行
$sqldata = $specialFunc($splitChar,$replace,$sqldata); //替換分隔符
$query = $head.$sqldata.$end; //數(shù)據(jù)拼接
if(mysql_query($query,$conn)) return array(true);
else {
return array(false,mysql_error($conn),mysql_errno($conn));
}
}
//調(diào)用示例1
require 'db.php';
$splitChar = '|'; //豎線
$file = 'sqldata1.txt';
$fields = array('id','parentid','name');
$table = 'cengji';
$result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields);
if (array_shift($result)){
echo 'Success!br/';
}else {
echo 'Failed!--Error:'.array_shift($result).'br/';
}
/*sqlda ta1.txt
1|0|A
2|1|B
3|1|C
4|2|D
-- cengji
CREATE TABLE `cengji` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parentid` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `parentid_name_unique` (`parentid`,`name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1602 DEFAULT CHARSET=utf8
*/
//調(diào)用示例2
require 'db.php';
$splitChar = ' '; //空格
$file = 'sqldata2.txt';
$fields = array('id','make','model','year');
$table = 'cars';
$result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields);
if (array_shift($result)){
echo 'Success!br/';
}else {
echo 'Failed!--Error:'.array_shift($result).'br/';
}
/* sqldata2.txt
11 Aston DB19 2009
12 Aston DB29 2009
13 Aston DB39 2009
-- cars
CREATE TABLE `cars` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`make` varchar(16) NOT NULL,
`model` varchar(16) DEFAULT NULL,
`year` varchar(16) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8
*/
//調(diào)用示例3
require 'db.php';
$splitChar = ' '; //Tab
$file = 'sqldata3.txt';
$fields = array('id','make','model','year');
$table = 'cars';
$insertType = 'REPLACE';
$result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields,$insertType);
if (array_shift($result)){
echo 'Success!br/';
}else {
echo 'Failed!--Error:'.array_shift($result).'br/';
}
/* sqldata3.txt
11 Aston DB19 2009
12 Aston DB29 2009
13 Aston DB39 2009
*/
//調(diào)用示例3
require 'db.php';
$splitChar = ' '; //Tab
$file = 'sqldata3.txt';
$fields = array('id','value');
$table = 'notExist'; //不存在表
$result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields);
if (array_shift($result)){
echo 'Success!br/';
}else {
echo 'Failed!--Error:'.array_shift($result).'br/';
}
//附:db.php
/* //注釋這一行可全部釋放
?
?php
static $connect = null;
static $table = 'jilian';
if(!isset($connect)) {
$connect = mysql_connect("localhost","root","");
if(!$connect) {
$connect = mysql_connect("localhost","Zjmainstay","");
}
if(!$connect) {
die('Can not connect to database.Fatal error handle by /test/db.php');
}
mysql_select_db("test",$connect);
mysql_query("SET NAMES utf8",$connect);
$conn = $connect;
$db = $connect;
}
?
//*/
.
-- 數(shù)據(jù)表結(jié)構(gòu):
-- 100000_insert,1000000_insert
CREATE TABLE `100000_insert` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parentid` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
100000 (10萬(wàn))行插入:Insert 100000_line_data use 2.5534288883209 seconds
1000000(100萬(wàn))行插入:Insert 1000000_line_data use 19.677318811417 seconds
//可能報(bào)錯(cuò):MySQL server has gone away
//解決:修改my.ini/my.cnf max_allowed_packet=20M
可以下載phpmyadmin軟件,用這個(gè)軟件,會(huì)直接顯示你的數(shù)據(jù)庫(kù),不用使用insert等sql語(yǔ)句,在軟件里有相應(yīng)的點(diǎn)擊符號(hào),通過(guò)對(duì)這些符號(hào)的使用點(diǎn)擊,就可以對(duì)任何表進(jìn)行增刪改查操作。存儲(chǔ)數(shù)據(jù)的數(shù)據(jù)庫(kù),如果是mysql的,在mysql中的data目錄下。其他數(shù)據(jù)庫(kù)的各異。
首先創(chuàng)建 一個(gè)HTML頁(yè)面userinfo_add.php,在里面輸入表單,文本框,輸入需要提交的到數(shù)據(jù)庫(kù)的信息:
賬號(hào) 姓名 年齡
頁(yè)面運(yùn)行結(jié)果:
創(chuàng)建一個(gè)PHP文件(userinfo_insert.php),用來(lái)處理頁(yè)面請(qǐng)求的,就是具體往數(shù)據(jù)庫(kù)添加數(shù)據(jù)的代碼:
先獲取頁(yè)面數(shù)據(jù)
//通過(guò)post獲取頁(yè)面提交數(shù)據(jù)信息 $userId = $_POST[userId];
$userName = $_POST[userName];
$userAge = $_POST[userAge];
接下來(lái),在連接數(shù)據(jù)庫(kù) ‘test’
//地址
$url = "127.0.0.1";
//賬號(hào)
$user = "root";
//密碼
$password = "root";
//連接
$con = mysql_connect($url,$user,$password);
//設(shè)置編碼機(jī)
mysql_query("set names 'utf8'");
//連接數(shù)據(jù)庫(kù)
mysql_select_db("test");
編寫SQL,執(zhí)行SQL添加數(shù)據(jù)
$sql = "insert into user_info (user_id,user_name,user_age) values('$userId','$userName','$userAge')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "添加一條記錄";
//關(guān)閉連接
mysql_close($con)
運(yùn)行結(jié)果前:
運(yùn)行結(jié)果后:
完整代碼:
$content = file_get_contents("filename.txt");
$contents = explode("br",$content);
這個(gè)$contents就是你要的數(shù)組,然后進(jìn)行數(shù)據(jù)庫(kù)插入操作!
$content = file_get_contents($p);
$contents = explode("\r\n",$content);
$ini_array = parse_ini_file("config.ini");
print_r($ini_array);
$con=mysql_connect($ini_array[host],$ini_array[name],$ini_array[pwd]);
if(!$con){
echo "數(shù)據(jù)庫(kù)連接失敗";
}
$db = mysql_select_db("jingcai", $con);
if(!$db){
echo "數(shù)據(jù)庫(kù)選擇失敗";
}
$sql =mysql_query('set names gb2312');
mysql_query($sql);
$sql="insert into user(tel,money,name) values('"$contents[1]"','"$contents[2]"', '"$contents[3]"')";
if (!mysql_query($sql,$con))
{
die('Error:'.mysql_error());
}
echo "scriptalert('ok');/script";
}
按這份代碼去執(zhí)行,你就知道錯(cuò)誤在哪一步了!
你別一起執(zhí)行,先執(zhí)行前面幾句,沒(méi)問(wèn)題在添加一個(gè)代碼塊~
新聞名稱:php向文件中追加數(shù)據(jù)庫(kù),php數(shù)據(jù)庫(kù)添加數(shù)據(jù)語(yǔ)句
網(wǎng)站網(wǎng)址:http://chinadenli.net/article14/pheoge.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供標(biāo)簽優(yōu)化、云服務(wù)器、品牌網(wǎng)站建設(shè)、電子商務(wù)、Google、
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)