Friday, 30 August 2013

How do I create a prepared statement?

How do I create a prepared statement?

I cannot find any documentation that adequately explains how to use them.
How to you retrieve variables from a query and use them and what do the
parameters mean to the queries? I want to make my website safe from sql
injection and I don't have a clue how to get the following code optimized
for safety. I understand how sql injection works, I just don't know how to
create the prepared statements or retrieve queries.
<?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","ashlyn","studyBuddy");
$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";
}
?>

No comments:

Post a Comment