PHP SQL Server Add/Insert Data Record (PDO)       | 
   
 
			  
			  
                PHP SQL Server Add/Insert Data Record (PDO) บทความนี้จะเป็นตัวอย่างของ PDO กับ sqlsrv  การเขียน PHP เพื่อ Insert หรือเพิ่ม Add ข้อมูลลงใน Database ของ SQL Server  โดยใช้ function ต่าง ๆ ของ PDO กับ sqlsrv โดยในตัวอย่างนี้จะใช้การ Insert แบบ Parameters Query ซึ่งนี่นคือจะมีความปลอดภัย และลดข้อผิดพลาดที่อาจจะเกิดจากการรับข้อมูลใรูปแบบต่าง ๆ ได้ 
 
Syntax รูปแบบการใช้งาน 
$sql = "INSERT INTO table_name (Col1,Col2) VALUES (?, ?)";
$params = array('Value1','Value2');
$stmt = $conn->prepare($sql);
$stmt->execute($params);
 
 
  
 
ฐานข้อมูลและตารางของ SQL Server Database 
 
Example ตัวอย่างการเขียน PHP กับ SQL Server เพื่อ Insert หรือเพิ่มข้อมูล 
 
add.php 
<html>
<head>
<title>ThaiCreate.Com PHP & SQL Server (PDO)</title>
</head>
<body>
<form action="save.php" name="frmAdd" method="post">
<table width="284" border="1">
  <tr>
    <th width="120">CustomerID</th>
    <td width="238"><input type="text" name="txtCustomerID" size="5"></td>
    </tr>
  <tr>
    <th width="120">Name</th>
    <td><input type="text" name="txtName" size="20"></td>
    </tr>
  <tr>
    <th width="120">Email</th>
    <td><input type="text" name="txtEmail" size="20"></td>
    </tr>
  <tr>
    <th width="120">CountryCode</th>
    <td><input type="text" name="txtCountryCode" size="2"></td>
    </tr>
  <tr>
    <th width="120">Budget</th>
    <td><input type="text" name="txtBudget" size="5"></td>
    </tr>
  <tr>
    <th width="120">Used</th>
    <td><input type="text" name="txtUsed" size="5"></td>
    </tr>
  </table>
  <input type="submit" name="submit" value="submit">
</form>
</body>
</html>
 
 
save.php 
<html>
<head>
<title>ThaiCreate.Com PHP & SQL Server (PDO)</title>
</head>
<body>
<?php
	ini_set('display_errors', 1);
	error_reporting(~0);
   $serverName = "localhost";
   $userName = "sa";
   $userPassword = "";
   $dbName = "mydatabase";
  
   $conn = new PDO("sqlsrv:server=$serverName ; Database = $dbName", $userName, $userPassword);
	$sql = "INSERT INTO customer (CustomerID, Name, Email, CountryCode, Budget, Used) 
		VALUES (?, ?, ?, ?, ?, ?)";
   $params = array($_POST["txtCustomerID"], $_POST["txtName"], $_POST["txtEmail"], $_POST["txtCountryCode"], $_POST["txtBudget"], $_POST["txtUsed"]);
	$stmt = $conn->prepare($sql);
	$stmt->execute($params);
	
	if( $stmt->rowCount() ) {
		 echo "Record add successfully";
	}
	$conn = null;
?>
</body>
</html>
 
 
 
 
Screenshot 
 
  
 
แบบ Form รับข้อมูล 
 
  
 
แสดงสถาณะการ Insert ข้อมูล 
 
  
 
ข้อมูลบนตารางของ SQL Server ที่ถูก Insert               
  
              			
			  
								  
			  
  
                          
  |