这是我的代码。我想阻止这个脚本将数据提交到没有数据的数据库
请有人帮我改进这个脚本吗?
<?php
session_start();
if( $_SESSION['auth'] != 1 ) {
header('Location: ../../admin/index.php');
}
?>
<?php include 'webconfig.php';?>
<?
$objConnect = mysql_connect($db_hostname,$db_username,$db_password) or die("Error Connect to Database");
$objDB = mysql_select_db($db_database);
mysql_query("SET NAMES 'utf8' COLLATE 'utf8_general_ci';");
$strSQL = "INSERT INTO editorschoice ";
$strSQL .="(post_head,post_date,post_data,post_link) ";
$strSQL .="VALUES ";
$strSQL .="('".$_POST["post_head"]."','".$_POST["post_date"]."','".$_POST["post_data"]."','".$_POST["post_link"]."') ";
$objQuery = mysql_query($strSQL);
if($objQuery)
{
echo "<center><h3>Save Done.</h3></center>";
}
else
{
echo "<center><h3>Save Failed. Try again</h3><br />[".$strSQL."]</center>";
}
mysql_close($objConnect);
?>
<head>
<meta http-equiv="Refresh" content="1; url=../../admin/index.php">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
答案 0 :(得分:0)
使用PDO将使查询更安全,您可以使用array_key_exists检查是否设置了某些内容。 e.g。
if(array_key_exists('post_head', $_POST))
{
$pdo = new \PDO('mysql:host=' . $db_hostname . ';dbname=' . $db_database, $db_username, $db_password);
$sql = "INSERT INTO editorschoice (post_head,post_date,post_data,post_link) VALUES (:head, :date, :data, :link)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':head', $_POST['post_head'], PDO::PARAM_STR);
$stmt->bindParam(':date', $_POST['post_date'], PDO::PARAM_STR);
$stmt->bindParam(':data', $_POST['post_data'], PDO::PARAM_STR);
$stmt->bindParam(':link', $_POST['post_link'], PDO::PARAM_STR);
$result = $stmt->execute();
}
else
{
//no post_head
}
答案 1 :(得分:0)
您可以在执行数据库查询之前向POST数据添加验证功能。通常,在保存到DB之前,有必要进行一些表单验证或参数验证以获得有效的数据格式。如果您只想要空数据,请参阅以下代码:
$required_fields = array('post_head', 'post_date', 'post_data', 'post_link');
function validation()
{
foreach($required_fields as $field)
{
if( ! isset($_POST[$field]))
//you can use empty($_POST[$field]) as well if no empty string allowed
{
//generate error
return false;
}
}
return true;
}