如何创建预准备声明?

时间:2013-08-31 03:00:53

标签: php mysql sql prepared-statement

我找不到任何充分说明如何使用它们的文档。如何从查询中检索变量并使用它们以及参数对查询意味着什么?我想让我的网站安全从sql注入,我不知道如何获得以下代码优化安全性。我理解sql注入是如何工作的,我只是不知道如何创建预处理语句或检索查询。

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

$tempProf = $_POST["professor"];
$tempProfArray = explode("=",$tempProf);
$prof = $tempProfArray[1];

$tempName = $_POST["name"];
$tempNameArray = explode("=",$tempName);
$name = $tempNameArray[1];

$tempNum = $_POST["number"];
$tempNumArray = explode("=",$tempNum);
$num = $tempNumArray[1];

$tempSec = $_POST["section"];
$tempSecArray = explode("=",$tempSec);
$section = $tempSecArray[1];

$tempCat = $_POST["category"];
$tempCatArray = explode("=",$tempCat);
$category = $tempCatArray[1];

$con=mysqli_connect("localhost","root","*******","******");

$result = mysqli_query($con,"SELECT * FROM professors where id='$prof'");
$row = mysqli_fetch_array($result);



if(empty($prof) || empty($name) || empty($num) || empty($section) || empty($category))
{
    echo "emptyField";
}
elseif(!is_numeric($num)  || !is_numeric($section))
{
    echo "NaN";
}
elseif(empty($row))
{
    mysqli_query($con,"INSERT INTO classes (className, classNumber, section, classCategory)
    VALUES ('$name','$num','$section','$category')");

    $classTemp = mysqli_query($con,"SELECT id FROM classes where className='$name' and classNumber='$num' and section ='$section'");
    $classTempArray = mysqli_fetch_array($classTemp);
    $classId = $classTempArray['id'];

    mysqli_query($con,"INSERT INTO professors (name, classes) VALUES ('$prof','$classId')");

    $profTemp = mysqli_query($con,"SELECT id FROM professors where name='$prof'");
    $profTempArray = mysqli_fetch_array($profTemp);
    $profId = $profTempArray['id'];
    mysqli_query($con,"UPDATE classes SET professor = '$profId' WHERE id = '$classId'");
    echo "success";
}
else
{
    $profName = $row['id'];
    mysqli_query($con,"INSERT INTO classes (professor, className, classNumber, section, classCategory)
    VALUES ('$prof', '$name','$num','$section','$category')");
    echo "success";
}

?>

2 个答案:

答案 0 :(得分:1)

一般来说,这样的东西就足够了(注意我使用面向对象的方式来访问连接,而不是像你这样的程序)

$stmt = $con->prepare( 'INSERT INTO classes (professor, className, classNumber, section, classCategory) VALUES (?, ?, ?, ?, ?)' )
$stmt->bind_param( 'ssiss', $prof, $name, $num, $section, $category );
$stmt->execute();

在这种情况下,我假设除$ num之外的所有内容都是字符串,而$ num是一个整数。

以下是绑定参数的相关文档:http://www.php.net/manual/en/mysqli-stmt.bind-param.php

答案 1 :(得分:-1)

$sql="SELECT id FROM classes WEHERE className=? AND classNumber=? AND section =?";

$stmt =$con->prepare($sql);

$stmt->execute(array($name,$num,$ection));

//you can apply this for other queries