php中數(shù)組插入mysql表的方法
下面為您介紹的數(shù)組插入mysql表的方法用于PHP開發(fā),如果您之前在使用mysql表時(shí)遇到過類似的方面,不妨一看。
環(huán)境:PHP 5.0 + MYSQL
第一步:我們先來創(chuàng)建一個(gè)表格來存儲(chǔ)數(shù)組變量的值,就是用mysql自帶的test數(shù)據(jù)庫吧
- Use test;
- Creat table ‘NEIL’ ( ‘ID’ int(20) primary key not null,
- ‘Major’ varchar(25) not null);
第二步:我們來建立一個(gè)復(fù)選框頁面用來模擬一個(gè)實(shí)例PHP數(shù)組 index.html
- <body>
- <form method="post" action="show.php">
- ID: <input type=”text” name=”id”><br>
- <input type="checkbox" name="teach[0]" value="online">Online<br>
- <input type="checkbox" name="teach[1]" value="video">video<br>
- <input type="checkbox" name="teach[2]" value="face">Face-to-Face<br>
- <input type="submit" value="submit">
- </form>
第三步:我們來描述show.php
Index.html通過post 將變量提交給show.php來處理,我們先來寫show.php代碼
- <?php
- $db_name=”test”;
- $table_name=”neil”;
- $connection= @mysql_connect(“localhost”,”root”,”root”) or die(mysql_error());
- $db= @mysql_select_db($db_name,$connection) or die (mysql_error());
- /*這里我們來進(jìn)行數(shù)組變量的處理*/
- $value=’’; //定義一個(gè)變量value初始化為空
- Foreach($_POST[“teach”] as $key)
- { $value.=$key.’,’;} /*將數(shù)組值傳遞給中間變量key, 由key 將值傳依次遞給變量value */
- /*插入語句*/
- $sql=”insert into neil values (‘$_POST[id]’,’$value’)”;
- $query= @mysql_query($sql,$connection) or die(mysql_error());
- ?>
到這里這個(gè)php中數(shù)組插入mysql表的方法就結(jié)束了。
【編輯推薦】