使用参数化查询/准备语句

时间:2017-09-02 19:39:26

标签: php mysqli wamp

我是php编码的新手,其他人告诉我,我需要为我的php脚本和MySQL数据库使用参数化查询/预处理语句。我已经查看了编写这些预处理语句的其他脚本示例,它们通常是指用户登录函数。我的查询只是一个Web表单,用于捕获用户输入的数据并存储在数据库中(SQL插入而不是SQL select)。我希望有人可以帮助我如何脚本php以防止SQL注入。也希望有人能告诉我这些准备好的语句是否也应该用在php SQL Select脚本中,我只在表单上显示数据库记录。提前谢谢!

以下是我使用的两个php文件,第一个是我的数据库连接脚本:

<?php

DEFINE ('DB_USER', 'fakeuser');
DEFINE ("DB_PSWD", 'fakepassword');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'newspaper');

$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);

?>

Web表单PHP脚本:

<!DOCTYPE HTML>  
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>  

<?php

$errors = "false";

// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["Name"])) {
    $nameErr = "Name is required";
    $errors = "true";
  } else {
    $name = test_input($_POST["Name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $nameErr = "Only letters and white space allowed"; 
      $errors = "true";
    }
  }

  if (empty($_POST["Email"])) {
    $emailErr = "Email is required";
    $errors = "true";
  } else {
    $email = test_input($_POST["Email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
      $errors = "true";
    }
  }

  if (empty($_POST["Website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["Website"]);
    // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
      $websiteErr = "Invalid URL"; 
    }
  }

  if (empty($_POST["Comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["Comment"]);
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
    $errors = "true";
  } else {
    $gender = test_input($_POST["gender"]);
  }

if (empty($_POST["Subscription"])) {
    $subErr = "Subscription is required";
    $errors = "true";
    }
 else {
    $sub = test_input($_POST["Subscription"]);
    }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>

<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
    <p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
 <legend>Newspaper Subscription Request</legend>  
  Name: <input type="text" name="Name" value="<?php echo $name;?>">
  <span class="error">* <?php echo $nameErr;?></span>
  <br><br>
  E-mail: <input type="text" name="Email" value="<?php echo $email;?>">
  <span class="error">* <?php echo $emailErr;?></span>
  <br><br>
  Website: <input type="text" name="Website" value="<?php echo $website;?>">
  <span class="error"><?php echo $websiteErr;?></span>
  <br><br>
  Comment: <textarea name="Comment" rows="5" cols="40"><?php echo $comment;?></textarea>
  <br><br>
  Gender:
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
  <span class="error">* <?php echo $genderErr;?></span>
    <br><br>
  Subscription:
   <select name="Subscription">
       <option value=""></option>
   <option value="Daily">Daily</option>
   <option value="Evening">Evening</option>
   <option value="Weekly">Weekly</option>
   <option value="Monthly">Monthly</option>
</select> 
  <span class="error">* <?php echo $subErr;?></span>

  <br><br>
  <input type="submit" name="submit" value="Submit"> 
<br><br>
<a href="https://www.google.com/">Visit Admin Page</a>
 </fieldset>
</form>



<?php

if (isset($_POST['submitted']) && $errors == "false") 
    {
    include('connect-mysql.php');



$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO subscriptions (Name, Email, Comment, Subscription) VALUES ('$fname',
'$femail', '$fcomment', '$fsubsciption')";

      if (!mysqli_query($dbcon, $sqlinsert))  {
           die(mysqli_error($dbcon));  //and die('error inserting new record') ;       

  }     // end of nested if statement

  // else
        $newrecord = "1 record added to the database";

}  // end of main if statement

?>

<?php

echo $newrecord

?>

</body>
</html>

更新后的代码与准备好的声明9/3/17:请参阅脚本底部(如果您发现任何问题,请告诉我)另外我已经按照我的想法在预备声明下面注释了!mysqli_query IF语句现在这已经过时了,但请告诉我是否还需要它。

<!DOCTYPE HTML>  
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>  

<?php

$errors = "false";

// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["Name"])) {
    $nameErr = "Name is required";
    $errors = "true";
  } else {
    $name = test_input($_POST["Name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $nameErr = "Only letters and white space allowed"; 
      $errors = "true";
    }
  }

  if (empty($_POST["Email"])) {
    $emailErr = "Email is required";
    $errors = "true";
  } else {
    $email = test_input($_POST["Email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
      $errors = "true";
    }
  }

  if (empty($_POST["Website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["Website"]);
    // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
      $websiteErr = "Invalid URL"; 
    }
  }

  if (empty($_POST["Comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["Comment"]);
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
    $errors = "true";
  } else {
    $gender = test_input($_POST["gender"]);
  }

if (empty($_POST["Subscription"])) {
    $subErr = "Subscription is required";
    $errors = "true";
    }
 else {
    $sub = test_input($_POST["Subscription"]);
    }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>

<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
    <p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
 <legend>Newspaper Subscription Request</legend>  
  Name: <input type="text" name="Name" value="<?php echo $name;?>">
  <span class="error">* <?php echo $nameErr;?></span>
  <br><br>
  E-mail: <input type="text" name="Email" value="<?php echo $email;?>">
  <span class="error">* <?php echo $emailErr;?></span>
  <br><br>
  Website: <input type="text" name="Website" value="<?php echo $website;?>">
  <span class="error"><?php echo $websiteErr;?></span>
  <br><br>
  Comment: <textarea name="Comment" rows="5" cols="40"><?php echo $comment;?></textarea>
  <br><br>
  Gender:
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
  <span class="error">* <?php echo $genderErr;?></span>
    <br><br>
  Subscription:
   <select name="Subscription">
       <option value=""></option>
   <option value="Daily">Daily</option>
   <option value="Evening">Evening</option>
   <option value="Weekly">Weekly</option>
   <option value="Monthly">Monthly</option>
</select> 
  <span class="error">* <?php echo $subErr;?></span>

  <br><br>
  <input type="submit" name="submit" value="Submit"> 
<br><br>
<a href="https://www.google.com/">Visit Admin Page</a>
 </fieldset>
</form>



<?php

if (isset($_POST['submitted']) && $errors == "false") 
    {
    include('connect-mysql.php');


$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO subscriptions (Name, Email, Comment, Subscription) VALUES (?,?,?,?)";

$stmt = mysqli_stmt_init($dbcon);
if (!mysqli_stmt_prepare($stmt,$sqlinsert)) {
echo "SQL error"; }
else {
    mysqli_stmt_bind_param($stmt,"ssss",$fname, $femail, $fcomment, $fsubsciption);
    mysqli_stmt_execute($stmt);

    echo '1 record added to the database';

      //if (!mysqli_query($dbcon, $sqlinsert))  {
           //die(mysqli_error($dbcon));        

  }     // end of nested IF statement

  // else
        //$newrecord = "1 record added to the database";

}  // end of main if statement

?>

<?php

echo $newrecord

?>



</body>
</html>

0 个答案:

没有答案