使用PDO将数据插入数据库 - 避免从其他人插入数据

时间:2014-07-07 18:26:10

标签: php sql database pdo insert

我正在使用PDO将数据插入我的数据库。我已经得到了以下代码可以正常工作,但问题是我应该是唯一允许将数据插入数据库的人。每个人都可以找到example.com/blog.html,任何人都可以在我的网站上添加博客文章。我应该如何避免这种情况?

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

?>

1 个答案:

答案 0 :(得分:1)

像@David建议的那样,它不必太复杂,你只需要识别机制,例如你可以添加一个字段,只为你输入一个密钥。并且仅在密钥匹配时运行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');