5
\$\begingroup\$

I started learning PHP and MySQL, was using MySQL_ functions. Then I learned they are deprecated, had to choose between PDO and MySQL. I chose MySQL and started using it.

As I learn OOP PHP, I thought I should change my code to OOP style, since it's cleaner. I was wondering whether this block of my code is secure or not. I use mysqli_real_escape_string() and htmlspecialchars() above.

Old code

$result = "INSERT INTO book(book_original_name, book_turkish_name, book_publication_date, book_synopsis) VALUES (?,?,?,?)";
$stmt = mysqli_prepare($sqli, $result);
mysqli_stmt_bind_param($stmt, "ssss", $_POST['book_original_name'], $_POST['book_tr_name'], $_POST['book_year'], $_POST['book_synopsis']);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);

New code ($sqli is my connection variable.)

$stmt = $sqli->prepare("INSERT INTO book(book_original_name, book_turkish_name, book_publication_date, book_synopsis) VALUES (?,?,?,?)");
$stmt->bind_param("ssss", $_POST['book_original_name'], $_POST['book_tr_name'], $_POST['book_year'], $_POST['book_synopsis']);
$stmt->execute();
$stmt->close();
echo "Mission has been completed, sir!";
\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

There doesn't seem much wrong with your code, but it is difficult to judge a small piece of code in isolation.

One thing I must urge you to do is to check the $_POST parameters before you put them into the database. Do not rely solely on the checks you do before the form is submitted. For instance, make sure you've actually got some content, and that the year is really four digits long. This way you can stop rougue data getting into your database.

In some cases you will have to try to prevent robots from posting to your database. This is especially true for registration forms.

See: http://www.ultramegatech.com/2009/08/5-basic-php-security-tips

Or: http://www.dreamhost.com/dreamscape/2013/05/22/php-security-user-validation-and-sanitization-for-the-beginner

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.