導航:首頁 > 編程語言 > php資料庫插入語句

php資料庫插入語句

發布時間:2022-05-12 07:56:04

⑴ 如何利用php讀取txt文件再將數據插入到資料庫

serial_number.txt的示例內容:

serial_number.txt:

DM00001A11 0116,
SN00002A11 0116,
AB00003A11 0116,
PV00004A11 0116,
OC00005A11 0116,
IX00006A11 0116,

創建數據表:

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()函數以","為標識符進行拆分

foreach ($contents as $k => $v)//遍歷循環
{
$id = $k;
$serial_number = $v;
mysql_query("insert into serial_number (`id`,`serial_number`)
VALUES('$id','$serial_number')");
}

備註:方法有很多種,我這里是在拆分txt文件為數組後,然後遍歷循環得到的數組,每循環一次,往資料庫中插入一次。

再給大家分享一個支持大文件導入的

<?php
/**
* $splitChar 欄位分隔符
* $file 數據文件文件名
* $table 資料庫表名
* $conn 資料庫連接
* $fields 數據對應的列名
* $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('"; //數據頭
$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';
}
//處理數據體,二者順序不可換,否則空格或Tab分隔符時出錯
$sqldata = preg_replace('/(\s*)(\n+)(\s*)/i','\'),(\'',$sqldata); //替換換行
$sqldata = $specialFunc($splitChar,$replace,$sqldata); //替換分隔符
$query = $head.$sqldata.$end; //數據拼接
if(mysql_query($query,$conn)) return array(true);
else {
return array(false,mysql_error($conn),mysql_errno($conn));
}
}

//調用示例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
*/

//調用示例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
*/

//調用示例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
*/

//調用示例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;
}
?>

//*/
.
-- 數據表結構:

-- 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

//可能報錯:MySQL server has gone away

//解決:修改my.ini/my.cnf max_allowed_packet=20M

⑵ PHP插入MYSQL語句

$sql="INSERT
INTO
table2(user,title,content,lastdate)
values('$_POST[user]','$_POST[title]','$_POST[content]',now())";
你的ID如果是自動生存的,那麼就要把ID這個欄位去掉,不然肯定插入不進去的

⑶ php 如何把一條sql語句寫入資料庫

<?php
$dbhost = 'localhost:3306'; // mysql伺服器主機地址
$dbuser = 'root'; // mysql用戶名
$dbpass = '123456'; // mysql用戶名密碼
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn ){
die('連接失敗: ' . mysqli_error($conn))
;}
echo '連接成功<br />'; // 設置編碼,防止中文亂碼mysqli_query($conn , "set names utf8");
$runoob_title = '學習 Python';
$runoob_author = 'RUNOOB.COM';
$submission_date = '2016-03-06';
$sql = "INSERT INTO runoob_tbl ".
"(runoob_title,runoob_author, submission_date) ".

"VALUES ".

"('$runoob_title','$runoob_author','$submission_date')";

mysqli_select_db( $conn, 'RUNOOB' );$retval = mysqli_query( $conn, $sql );
if(! $retval ){
die('無法插入數據: ' . mysqli_error($conn))
;}
echo "數據插入成功\n";
mysqli_close($conn);
?>
按照步驟開始,多看PHP手冊。

⑷ php 資料庫插入數據,有兩個插入語句,第一個成功,第二個不成功

1.我們應該在每一個mysql_query之後檢測是否成功,不成功要輸出錯誤原因,這樣才便於分析,例如你可以這么寫代碼:

$out='';//總的結果
$sql="insertintousersvalues(null,'$userid','$pwd1')";
if(!mysql_query($sql))$out.="插入用戶表失敗,SQL:$sql<br>錯誤:".mysql_error();
$s_sql="select*....";//真心不明白你這個的意思
$sql="insertintouser_rolevalues(null,$role_id,'$s_sql')";
if(!mysql_query($sql))$out.="插入xx表失敗,SQL:$sql<br>錯誤:".mysql_error();
if($out=='')echo'<script>alert("添加成功");</script>';
elseecho"<script>alert('$out');location.href='login.php';</script>";

2.看你的代碼,好像$role_id沒有賦值,這可能是導致失敗的原因,希望你用上面的方法調試觀察。

⑸ php的sql插入語句問題

頁面文件修改為GB2312,瀏覽器的頁面編碼也要修改為GB2312,資料庫裡面的字元集要設置為GB2312(建時指定、PHPMYADMIN可以修改),這些你都做好了,那就剩下一步:

設置MYSQL連接的會話為GB2312,語句是:
mysql_query("set names gb2312"):

⑹ php中插入MySQL資料庫的語句怎麼寫

顯示資料庫或表:
showdatabases;//然後可以usedatabase_name;
showtables;
更改表名:
altertabletable_namerenamenew_t;
添加列:
altertabletable_nameaddcolumnc_ncolumnattributes;
刪除列:
altertabletable_namedropcolumnc_n;
創建索引:
altertablec_tableaddindex(c_n1,c_n2);
altertablec_tableadniqueindex_name(c_n);
altertablec_tableaddprimarykey(sid);
刪除索引:
altertablec_tabledropindexc_n1;
更改列信息:
altertablet_tablechangec_1c_1varchar(200);
altertablet_tablemodify1c_1varchar(200);
insert插入語句:
insertintotable_name(c_1,c_2)
values('x1',1);
update語句:
updatetable_namesetc_1=1wherec_2=3;
刪除資料庫或者表:
droptabletable_name;
dropdatabasedatabase_name;//使用mysql_drop_db()可以刪除的.

⑺ php資料庫添加、刪除、修改數據(mysql)

一、PHP操作MySql資料庫
新增數據
?php
$query
=
"INSERT
INTO
grade
(name,email,point,regdate)
VALUE
('
李三','[email protected]',,NOW())"
;
@mysql_query($query)
or
die(
'添加數據出錯:'
.mysql_error());
?
修改數據
?php
$query
=
"UPDATE
grade
SET
name='小可愛'
WHERE
id=6"
;
@mysql_query($query)
or
die(
'修改出錯:'
.mysql_error());
?
刪除數據
?php
$query
=
"DELETE
FROM
grade
WHERE
id=6";
@mysql_query($query)
or
die(
'刪除錯誤:'
.mysql_error());
?
顯示數據
?php
$query
=
"SELECT
id,name,email,point
FROM
grade";
$result
=
@mysql_query($query)
or
die(
'查詢語句出錯:'
.mysql_error());
while
(!!
$row
=
mysql_fetch_array($result))
{
echo
$row[
'id'
].
'----'
.$row['name'
].'----'
.$row
['email'
].
'----'
.$row['point'
];
echo
'<br
/
';
}
?>
二、其他常用函數
mysql_f
etch_row()
:從結果集中取得一行作為枚舉數組
mysql_f
etch_assoc()

從結果集中取得一行作為關聯數組
mysql_f
etch_array()

從結果集中取得一行作為關聯數組,或數字數組,或二者兼有
mysql_f
etch_lengths
()

取得結果集中每個輸出的長度
mysql_f
ield_name():
取得結果中指定欄位的欄位名
mysql_num_rows():
取得結果集中行的數目
mysql_num_f
ields():取得結果集中欄位的數目
mysql_get_client_inf
o()

取得
MySQL
客戶端信息
mysql_get_host_info():
取得
MySQL
主機信息
mysql_get_proto_info():
取得
MySQL
協議信息
mysql_get_server_inf
o()

取得
MySQL
伺服器信息

⑻ php 插入語句

php一般都是和mysql結合的,而mysql的sql插入語句為:
insert into tablename (cols1,cols2...) values (val1,val2...);

⑼ PHP+MYSQL如何插入記錄到資料庫

「INSERT INTO」語句的作用是:向一個資料庫的表中插入一條新的記錄。向一個資料庫表中插入數據「INSERT INTO」的作用是:向一個資料庫的表中插入一條新的記錄。語法INSERT INTO table_name
VALUES (value1, value2,....) 你可以在指定的列中插入數據,具體如下:INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....) 注意:SQL語句是「字母大小寫不敏感」的語句(它不區分字母的大小寫),即:「INSERT INTO」和「insert into」是一樣的。在PHP內創建資料庫,我們需要在mysql_query()函數內使用上述語句。這個函數是用來發送MySQL資料庫連接建立的請求和指令的。案例在前一章里,我們建立了一張名為「Person」的表,其中包含三個縱列:"Firstname", "Lastname" 和 "Age"。在下面的案例當中,我們還會用到同一張表,並在其中加入兩條新的記錄:<?php
$con = mysql_connect("localhost","peter","abc123");if (!$con){die('Could not connect: ' . mysql_error());
}mysql_select_db("my_db", $con);mysql_query("INSERT INTO person (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");mysql_query("INSERT INTO person (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");mysql_close($con);
>把一張表中的數據插入資料庫中現在,我們將建立一個HTML表單;通過它我們可以向「Person」表中加入新的記錄。下面演示這個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> 在上述案例中,當一個用戶點擊HTML表單中的「提交submit」按鈕後,表單中的數據會發送到「insert.php」。「insert.php」文件與資料庫建立連接,並通過PHP $_POST變數獲取表單中的數據;此時,mysql_query()函數執行「INSERT INTO」語句,這樣,一條新的記錄就被添加到資料庫的表單當中了。下面試「insert.php」頁面的代碼:<?php

⑽ PHP向資料庫中插入數據

你的代碼沒了?
你光寫出個sql語句
不執行
他怎麼可能插入成功?
mysql_query($sql);
寫上。。
$query
=
mysql_query($sql);
if($query){
echo
'數據插入成功。';
}else{
echo
'數據插入失敗。';
}

閱讀全文

與php資料庫插入語句相關的資料

熱點內容
手機號碼如何加密 瀏覽:424
沈陽程序員培訓學校 瀏覽:538
一般伺服器如何配置 瀏覽:895
圖片怎樣加密發郵件 瀏覽:619
萬虹電腦文件夾密碼忘記了怎麼辦 瀏覽:631
rc108單片機 瀏覽:867
戰雷如何改變伺服器 瀏覽:674
mactelnet命令 瀏覽:51
壓縮袋壓縮了拿出來 瀏覽:401
安卓手機相機怎麼設置許可權 瀏覽:121
美女程序員轉行做主播 瀏覽:671
辦理解壓房產 瀏覽:575
道路工程概論pdf 瀏覽:388
超棒數學速演算法大全 瀏覽:937
小米易語言登錄源碼 瀏覽:31
磚牆內加密鋼筋 瀏覽:992
鄉關何處pdf 瀏覽:84
小豬領贊小程序源碼 瀏覽:336
python曲線如何原路返回 瀏覽:431
pdf快速看圖破解版 瀏覽:294