简体   繁体   中英

Prevent insert empty data to db

Here is my code . I want to prevent this script submit data into database with out data

does anyone can help me to improve this script please.

<?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>

Using PDO will make the query much safer, and you can use array_key_exists to check if something is set. eg

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
}

You can add validation function to POST data before executing DB query. Usually, it is necessary to do some form validation or parameter validation to have a valid data format before saving to DB. If you only want no empty data, see the code below:

$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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM