?php
為洛川等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計(jì)制作服務(wù),及洛川網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作、洛川網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長期合作。這樣,我們也可以走得更遠(yuǎn)!
$title = $_POST['title'];
$name = $_POST['author'];
$message = $_POST['my_message'];
$dbhost = '127.0.0.1';
$dbuser = 'root'; //我的用戶名
$dbpass = ''; //我的密碼
$dbname = 'exer'; //我的mysql庫名
$connect = mysql_connect($dbhost,$dbuser,$dbpass,$dbname);
mysql_query("set names 'utf8" );
mysql_query("INSERT INTO message VALUES (null,'".$title."','".$name."','".$message."',null)")or die("query error");
echo "留言成功";
echo "script type='text/javascript' alert('留言成功')";
echo "window.location='allmessage.php';/script";
?
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)識符進(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ù)庫中插入一次。
再給大家分享一個(gè)支持大文件導(dǎo)入的
?php
/**
* $splitChar 字段分隔符
* $file 數(shù)據(jù)文件文件名
* $table 數(shù)據(jù)庫表名
* $conn 數(shù)據(jù)庫連接
* $fields 數(shù)據(jù)對應(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萬)行插入:Insert 100000_line_data use 2.5534288883209 seconds
1000000(100萬)行插入:Insert 1000000_line_data use 19.677318811417 seconds
//可能報(bào)錯(cuò):MySQL server has gone away
//解決:修改my.ini/my.cnf max_allowed_packet=20M
一、PHP操作MySql數(shù)據(jù)庫
新增數(shù)據(jù)
?php
$query
=
"INSERT
INTO
grade
(name,email,point,regdate)
VALUE
('
李三','yc60.com@gmail.com',,NOW())"
;
@mysql_query($query)
or
die(
'添加數(shù)據(jù)出錯(cuò):'
.mysql_error());
?
修改數(shù)據(jù)
?php
$query
=
"UPDATE
grade
SET
name='小可愛'
WHERE
id=6"
;
@mysql_query($query)
or
die(
'修改出錯(cuò):'
.mysql_error());
?
刪除數(shù)據(jù)
?php
$query
=
"DELETE
FROM
grade
WHERE
id=6";
@mysql_query($query)
or
die(
'刪除錯(cuò)誤:'
.mysql_error());
?
顯示數(shù)據(jù)
?php
$query
=
"SELECT
id,name,email,point
FROM
grade";
$result
=
@mysql_query($query)
or
die(
'查詢語句出錯(cuò):'
.mysql_error());
while
(!!
$row
=
mysql_fetch_array($result))
{
echo
$row[
'id'
].
'----'
.$row['name'
].'----'
.$row
['email'
].
'----'
.$row['point'
];
echo
'br
/
';
}
?
二、其他常用函數(shù)
mysql_f
etch_row()
:從結(jié)果集中取得一行作為枚舉數(shù)組
mysql_f
etch_assoc()
:
從結(jié)果集中取得一行作為關(guān)聯(lián)數(shù)組
mysql_f
etch_array()
:
從結(jié)果集中取得一行作為關(guān)聯(lián)數(shù)組,或數(shù)字?jǐn)?shù)組,或二者兼有
mysql_f
etch_lengths
()
:
取得結(jié)果集中每個(gè)輸出的長度
mysql_f
ield_name():
取得結(jié)果中指定字段的字段名
mysql_num_rows():
取得結(jié)果集中行的數(shù)目
mysql_num_f
ields():取得結(jié)果集中字段的數(shù)目
mysql_get_client_inf
o()
:
取得
MySQL
客戶端信息
mysql_get_host_info():
取得
MySQL
主機(jī)信息
mysql_get_proto_info():
取得
MySQL
協(xié)議信息
mysql_get_server_inf
o()
:
取得
MySQL
服務(wù)器信息
把來自表單的數(shù)據(jù)插入數(shù)據(jù)庫
現(xiàn)在,我們創(chuàng)建一個(gè) HTML 表單,這個(gè)表單可把新記錄插入 "Persons" 表。
這是這個(gè) HTML 表單:
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ù)庫,并通過 $_POST 變量從表單取回值。然后,mysql_query() 函數(shù)執(zhí)行 INSERT INTO 語句,一條新的記錄會(huì)添加到數(shù)據(jù)庫表中。
下面是 "insert.php" 頁面的代碼:
?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)
?