使用PHP和MySQL尝试PDO插入的方式出了什么问题?
MySQL数据库使用与($ _POST)变量相同的名称。
<?php
if (!empty($_POST)) {
//Declare Database Variables Here
$dblist = ($_POST);
$keys = array_keys($data);
$dbcols = join(', ', array_values($keys));
$data = join(', ',array_values($dblist));
$dbtype = "mysql";
$dbhost = '127.0.0.1';
$dbname = 'bpstalent';
$dbuser = 'root';
$psword = 'root';
$portno = 3306;
// if table_name is submitted, display dynamic table with another form request for table name
$pdo = new PDO('mysql:host=' . $dbhost . ';port=' . $portno . 'dbname=' . $dbname . ';' . $dbuser . ';' . $psword . ';' );
echo "form submitted";
$sql = "INSERT INTO 'applicants'($dbcols) VALUES ($data)";
$stmt = $pdo->prepare($sql);
$stmt->execute();
}
else {
?>
html表格
<?
;}
?>
答案 0 :(得分:0)
另外,我认为你很容易成为SQL注入的目标。我会改变
$sql = "INSERT INTO 'applicants'($dbcols) VALUES ($data)";
并将$ dbcols的值替换为硬编码列列表(它们也可以来自数组,而不是用户发送的)
对于$ data,我将用params替换为bindValue()处理的内容。您可以通过替换&#34;,&#34;来实现这一目标。与&#34;,:&#34;将名字转换为副占位符。如果回显您的最终查询将如下所示:
$sql = "INSERT INTO applicants (col1, col2, col3) VALUES (:col1, :col2, :col3)";
在PHP文档中查看此示例,您将值得花时间来保护此表单:
http://www.php.net/manual/en/pdostatement.bindvalue.php
下面是一个经过重新设计的脚本示例,未经测试,但应该让您了解如何使事情更安全:
<?php
if ($_POST) {
//HARDCODE COLUMNS, DO NOT RELY ON USER INPUT, BAD THINGS WILL HAPPEN IF YOU DO
$keys = array("col1", "col2", "col3");
$dbcols = '`'.join('`, `', $keys).'`';
$placeholders = ':'.join(', :', $keys);
//RUN THROUGH POST DATA LOOKING FOR YOUR KEYS, ONLY PASS TO DATABASE DATA YOU ARE EXPECTING TO SEE
$data = array();
foreach ($keys as $k)
{
$data[$k] = $_POST[$k];
}
//CONSIDER REPLACING THIS WITH require_once() FILE
$dbtype = "mysql";
$dbhost = '127.0.0.1';
$dbname = 'bpstalent';
$dbuser = 'root';
$psword = 'root';
$portno = 3306;
$pdo = new PDO("$dbtype:host=$dbhost;port=$portno;dbname=$dbname", $dbuser, $psword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO applicants ($dbcols) VALUES ($placeholders)";
$stmt = $pdo->prepare($sql);
$stmt->execute($data);
}