next up previous contents
Next: 查詢資料表 Up: PHP Query 紀錄詢問 Previous: PHP Query 紀錄詢問   Contents   DYWANG_HOME

新增紀錄

  1. 撰寫 insertentry.php,從網頁上輸入一筆紀錄,新增到資料表 tblphp。 $_POST 抓取網頁上輸入的資料,不同於 $_GET 抓取網址問號後的變數。
    [root@kvm8 ~]# vim /var/www/html/insertentry.php
    [root@kvm8 ~]# cat /var/www/html/insertentry.php
    <html>
    <head>
    <title>Add New Record in MariaDB Database</title>
    </head>
    <body>
    <?php
    if(isset($_POST['add'])) {
    	$dbhost = 'localhost:3306';
    	$dbuser = 'root';
    	$dbpass = '123qwe';
    	$conn = mysqli_connect($dbhost, $dbuser, $dbpass) 
    		or die(mysqli_connect_error().PHP_EOL);
    	$title = $_POST['title'];
    	$author = $_POST['author'];
    	$submission_date = $_POST['submission_date'];
    	mysqli_select_db( $conn, 'dywphp' )
    		or die('Error: '.mysqli_error($conn).PHP_EOL);
    	$sql = "insert into tblphp (title,author,submission_date)".
    		"values ('$title','$author','$submission_date')";
    	mysqli_query( $conn, $sql )
    		or die('Error: '.mysqli_error($conn).PHP_EOL);
    	mysqli_close($conn); 
    }
    else {
    	?>
    	<form method="post" action="<?php $_PHP_SELF ?>">
    	<table width="600" border="0" cellspacing="1" cellpadding="2">
    	<tr>
    	<td width="250">Dywphp Title</td>
    	<td>
    	<input name="title" type="text" id="title">
    	</td>
    	</tr>
    	<tr>
    	<td width="250">Dywphp Author</td>
    	<td>
    	<input name="author" type="text" id="author">
    	</td>
    	</tr>
    	<tr>
    	<td width="250">Submission Date [yyyy-mm-dd]</td>
    	<td>
    	<input name="submission_date" type="text" id="submission_date">
    	</td>
    	</tr>
    	<tr>
    	<td width="250"> </td>
    	<td> </td>
    	</tr>
    	<tr>
    	<td width="250"> </td>
    	<td>
    	<input name="add" type="submit" id="add" value="Add Dywphp">
    	</td>
    	</tr>
    	</table>
    	</form>
    	<?php
    }
    ?>
    </body>
    </html>
    
  2. 開啟瀏覽器,連上網址 http://kvm8.deyu.wang/insertentry.php,輸入一筆紀錄。
    Image insertentry
  3. 按下「Add Dywphp」按鈕,會將網頁上輸入的資料寫入資料表 tblphp,並回傳寫入成功。
    Image insertentry1



De-Yu Wang 2020-04-07