2012-07-25 60 views
0

不能得到這個工作。有人可以請我指出正確的方向,並舉例說明如何解決這個問題。謝謝。 我需要這個網址 domain.com/script.php?from=1123 &消息= 1234454使用URL字符串插入到MySQL

插入velues到我的表

<?php 

mysql_connect('localhost', 'user', 'pass'); 

mysql_select_db('dbname'); 

$sql = "insert into table (from, message) values ('".$_GET['from']."','".$_GET['message']."')"; 
if(!$sql){ 
echo "Error " . mysql_error(); } 
else{ echo "Success"; } 

?> 
+2

沒有什麼可以實際插入數據庫的 - 您只需生成一串SQL。 – andrewsi 2012-07-25 18:11:46

回答

0

你永遠叫mysql_query()實際執行查詢。

<?php 

mysql_connect('localhost', 'user', 'pass'); 

mysql_select_db('dbname'); 

$from = mysql_real_escape_string($_GET['from']); 
$message = mysql_real_escape_string($_GET['message']); 

// TODO: check that $from and $message are not empty and are valid 

$sql = "insert into table (from, message) values ('$from','$message')"; 
$result = mysql_query($sql); // This actually executes the query on the server 

if(!$result) { 
    echo "Error " . mysql_error(); 
} else { 
    echo "Success"; 
} 

致電mysql_real_escape_string也很重要。沒有它,你很容易被SQL注入。

另外,mysql_*函數已被棄用。您應該切換到MysqliPDO_Mysql

+0

錯誤您的SQL語法中有錯誤;檢查與您的MySQL服務器版本對應的手冊,以便在第1行的'table'('from','message')值('111111','223232')'附近使用正確的語法 – 2012-07-25 18:44:12

+0

添加'echo $ sql; '在運行查詢之前。什麼是全部輸出? – drew010 2012-07-25 18:44:14

+0

我認爲問題在於你必須使用反引號(')圍繞table,from和message,而不是單引號。 – drew010 2012-07-25 18:45:36

1

嘗試添加

mysql_query($sql); 

所以它實際上在目前增加了DB你只是創建一個字符串

+0

不,**不要**使用'mysql_query',特別是當沒有任何參數被正確轉義時。 [做得很好](http://bobby-tables.com/php.html)。發佈這樣的答案只是教授危險的技巧。 – tadman 2012-07-25 19:14:10

0

首先,你必須檢查變量的設置。

if(isset($_GET['from'],$_GET['message'])){ 
     $con = mysql_connect('localhost', 'user', 'pass'); 

     mysql_select_db('dbname',$con); 

     $from = mysql_real_escape_string($_GET['from']); 
     $message = mysql_real_escape_string($_GET['message']); 

// TODO: check that $from and $message are not empty and are valid 

$sql = "insert into table (from, message) values ('$from','$message')"; 
$result = mysql_query($sql); 

if(!$result) { echo "Error " . mysql_error(); } 
else { 
    echo "Success"; 
    mysql_close($con); 
} 

}else{die();} 
+0

互聯網需要的最後一件事是另一個使用'mysql_query'的例子。請不要這樣做。 – tadman 2012-07-25 19:15:14

+1

請使用MYSQLI – 2012-07-25 19:16:59