2016-07-22 74 views
-4

請幫助我,我嘗試插入數據庫與注入攻擊保護,我發現了一些w3schools的例子,但它不適用於我。連接是正確的,並工作。由於我是SQL和編程方面的新手,我不知道那個Insert有什麼問題。請,任何人都可以幫忙嗎?非常感謝。插入數據庫與注入攻擊保護

我插入PHP:

<?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(); 


?> 
+2

將mysqli與PDO混合使用。 'bindParam'用於pdo,'bind_param'用於mysqli – Saty

+1

[如果您打算使用PDO,請一路走下去。](http://jayblanchard.net/demystifying_php_pdo.html) –

+0

我想用mysqli的。我將'bindParam'改爲'bind_param',它仍然不起作用。 –

回答

3

你混合數據庫的API。如果你想使用的MySQLi你的代碼應該是這樣的:

<?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(); 


?> 

通知我已經改變了佔位符,每個參數?後轉爲bind_param()函數,其中,而不是單獨調用每個參數(這你可以做)我使用了一個函數調用,其中我指定type of variable to be inserted,然後爲每個佔位符指定一個變量。

+0

感謝@JayBlanchard!現在它工作了!再次感謝您 –

+0

如果答案解決了您的問題@NiniVanini,請考慮接受答案。以下是http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work然後返回到此處,並使用勾號/複選標記執行相同操作,直至變爲綠色。這告知社區,找到了解決方案。否則,其他人可能會認爲這個問題仍然存在,並且可能需要發佈(更多)答案。 *歡迎使用Stack!* –

+0

當然,再次感謝您的幫助和您的方法@JayBlanchard –