【问题标题】:Using PDO to insert data into database - avoid data insert from other people使用 PDO 将数据插入数据库 - 避免从其他人插入数据
【发布时间】:2014-08-28 07:53:49
【问题描述】:

我正在使用 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

?>

【问题讨论】:

  • 通过在您的网站上使用某种身份验证机制,以便只有有效的登录用户才能调用此操作。它与您的数据库访问无关,只是您的页面没有任何类型的用户名/密码保护。
  • 所以基本上我需要在 PHP 和 Mysql 中创建一个安全的登录脚本,然后授予某些用户向数据库插入数据的权限?工作量很大,但我想没有其他办法了吗?

标签: php sql database pdo insert


【解决方案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');

【讨论】:

  • 感谢分享此代码。我自己没有想到这样的事情。效果很好!
猜你喜欢
  • 2014-08-28
  • 1970-01-01
  • 2014-04-17
  • 2012-10-06
  • 2012-03-28
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多