สร้าง database
CREATE DATABASE `myweb` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; USE `myweb`; CREATE TABLE `tb_dept` ( `dept_id` int(10) NOT NULL auto_increment, `dept_name` varchar(100) NOT NULL, PRIMARY KEY (`dept_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; CREATE TABLE `tb_member` ( `mid` int(10) NOT NULL auto_increment, `fname` varchar(100) NOT NULL, `lname` varchar(100) NOT NULL, `phone` varchar(20) NOT NULL, PRIMARY KEY (`mid`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
ไฟล์เชื่อมต่อกับ database
<?php $con= mysqli_connect("localhost","root","password","myweb") or die("Error: " . mysqli_error($con)); mysqli_query($con, "SET NAMES 'utf8' "); ?>
ฟอร์มเพิ่มข้อมูลแบบง่ายๆ
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title></title> </head> <body> <form id="formRegister" name="formRegister" method="post" action="form_db.php"> <p><br /> <br /> </p> <table width="700" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td height="40" colspan="2" align="center" bgcolor="#D6D5D6"><b>add data</b></td> </tr> <tr> <td align="right"> </td> <td> </td> </tr> <tr> <td width="117" align="right">ชื่อ :</td> <td width="583"><input name="fname" type="text" id="fname" size="30" required="required"/></td> </tr> <tr> <td align="right"> </td> <td> </td> </tr> <tr> <td align="right">สกุล <label> :</label></td> <td><input name="lname" type="text" id="lname" size="30" required="required"/></td> </tr> <tr> <td align="right"> </td> <td> </td> </tr> <tr> <td align="right">เบอร์โทร :</td> <td><input type="text" name="phone" id="phone" required="required"/></td> </tr> <tr> <td align="right"> </td> <td> </td> </tr> <tr> <td align="right">ชื่อหน่วยงาน : <label> </label></td> <td><input type="text" name="dept_name" id="dept_name" required="required"/></td> </tr> <tr> <td> </td> <td> <input type="submit" name="Register" id="Register" value="SAVE" /></td> </tr> </table> </form> </body> </html>
ไฟล์นำข้อมูลเข้าไปใน database
<?php include('condb.php'); $fname = $_REQUEST["fname"]; $lname = $_REQUEST["lname"]; $phone = $_REQUEST["phone"]; $dept_name = $_REQUEST["dept_name"]; //table1 $sql = "INSERT INTO tb_member(fname, lname, phone) VALUES('$fname', '$lname', '$phone')"; $result = mysqli_query($con, $sql) or die ("Error in query: $sql " . mysqli_error()); //table2 $sql = "INSERT INTO tb_dept(dept_name) VALUES('$dept_name')"; $result = mysqli_query($con, $sql) or die ("Error in query: $sql " . mysqli_error()); //ปิดการเชื่อมต่อ database mysqli_close($con); //จาวาสคริปแสดงข้อความเมื่อบันทึกเสร็จและกระโดดกลับไปหน้าฟอร์ม if($result){ echo "<script type='text/javascript'>"; echo "alert('Save Succesfuly');"; echo "window.location = 'form.php'; "; echo "</script>"; } else{ echo "<script type='text/javascript'>"; echo "alert('Error!!');"; echo "</script>"; } ?>
http://devbanban.com/?p=527