2014-07-07 35 views
0

我正在使用PDO將數據插入到我的數據庫中。我已經得到了以下代碼工作正常,但問題是,我應該是唯一允許將數據插入數據庫的人。由於每個人都可以找到example.com/blog.html,任何人都可以添加博客文章到我的網站。我應該如何避免這種情況?使用PDO將數據插入數據庫 - 避免從其他人插入數據

blog.html(我的表單)

<html> 
<body> 

<form name="blog post" action="insert.php" method="post"> 

<label for "id">Id: </label> 
<input type="text" name="id"> 
<br>  
<label for "title">Title: </label> 
<input type="text" name="title"> 
<br>  
<label for "year">Year: </label> 
<input type="text" name="year"> 
<br> 
<label for "text">Text: </label> 
<textarea rows="10" cols="50" name="text"></textarea> 
<br>  
<button type="submit">Submit</button> 
</form> 

</body> 
</html> 

insert.php(我的PHP代碼)

<?php 

$pdo = new PDO('mysql:host=localhost;dbname=dbexample', 'userexample', 'passwexample', array(\PDO::MYSQL_ATTR_INIT_COMMAND =>"SET NAMES utf8;SET time_zone = 'Europe/London'")); 

$sql = "INSERT INTO `tableexample` (id, title, year, text) 
             VALUES (:id, :title, :year, :text)"; 
$stmt = $pdo->prepare($sql); 
$stmt->bindParam(":id", $id); 
$stmt->bindParam(":title", $title); 
$stmt->bindParam(":year", $year); 
$stmt->bindParam(":text", $text); 

$form = $_POST; 
$id = $form[ 'id' ];      
$titel = $form[ 'title' ];     
$jaar = $form[ 'year' ];     
$tekst = $form[ 'text' ];     


$result = $stmt->execute(); 

if($result) { 
    echo "Your message has been posted"; 

    }// end if 
else { 
    echo '0 results'; 
    }// end else 

?> 
+2

包括通過使用一些一種授權誘導機制,以便只有有效的登錄用戶才能調用此操作。它與你的數據庫訪問無關,你只是沒有任何對你的頁面的用戶名/密碼保護。 – David

+0

所以基本上我需要在PHP和Mysql中創建一個安全的登錄腳本,然後授予一些用戶將數據插入數據庫的權限?這是很多工作,但我想這沒有其他辦法? – Stan

回答

1

做它作爲@大衛建議,它並沒有被如此複雜,您只需要認證機制,例如您可以爲您添加一個字段以輸入密鑰。只有在密鑰匹配時才運行pdo代碼。

HTML

<label for "key">Enter key: </label> 
<input type="text" name="key"> 
<br> 

PHP

if(isset($_POST['key']) && $_POST['key'] === MY_KEY){ 
    //PDO code here ... 
}else{ 
    echo "Incorrect Key , you are not authorized to add blog entries"; 
} 

MY_KEY僅僅是一個常數,你可以在配置文件定義了您在腳本

define('MY_KEY' , 'HDIhdihfsiX872**e72!!{dsdsf'); 
+0

感謝您分享此代碼。我自己並沒有想到這樣的事情。它工作正常! – Stan

+0

歡迎您和您的項目祝你好運 – meda