Nini Vanini Nini Vanini - 4 months ago 18
MySQL Question

Insert into DB with inject attack protection

please help me, I try to insert into DB with inject attack protection and I've found some example on w3schools, but it doesn't work for me. The connection is right and works. As I'm new in SQL and programming at all, I don't know what is wrong with that Insert. Please, can anybody help? thanks a lot.

My php for inserting:

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "<p>Connected successfully</p>";

$From = $_GET['From'];
$To = $_GET['To'];
$Type = $_GET['Type'];
$text = $_GET['text'];


$stmt = $conn->prepare("INSERT INTO orders (from_lang, to_lang, tex)
VALUES (:fr, :to, :tex)");

$stmt->bindParam(':fr', $From);
$stmt->bindParam(':to', $To);
$stmt->bindParam(':tex', $text);
$stmt->execute();


?>

Answer

You're mixing database API's. If you want to use MySQLi your code would look like this:

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "<p>Connected successfully</p>";

$From = $_GET['From'];
$To = $_GET['To'];
$Type = $_GET['Type'];
$text = $_GET['text'];


$stmt = $conn->prepare("INSERT INTO orders (from_lang, to_lang, tex)  
VALUES (?,?,?)");
$stmt->bind_param('sss', $From,$To,$text);
$stmt->execute();


?>

Notice I have changed the placeholder for each parameter to ? and changed to the bind_param() function where, instead of a separate call for each parameter (which you can do) I have used a single function call in which I specify the type of variable to be inserted and then a variable for each placeholder.

Comments