2012-07-25 53 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