2013-01-17 20 views
0

我发送数据从iphone到服务器使用PHP它是从iPhone发送数据,但不插入在MySQL中我使用下面的PHP代码。插入数据在MySQL数据库在PHP

<?php 
    $con =  

    mysql_connect("surveyipad.db.6420177.hostedresource.com","tom","ben"); 
    if (!$con) 
    { 
    die('Could not connect: ' . mysql_error()); 
    } 

    mysql_select_db("surveyipad", $con); 



    $device_Id=$_POST['device_Id']; 
    $R1=$_POST['R1']; 
    $R2=$_POST['R2']; 
    $R3=$_POST['R3']; 
    $comment=$_POST['comment']; 
    $update_date_time=$_POST['update_date_time']; 

    $query=("INSERT INTO survey_responsese_pfizer (device_Id,R1,R2,R3,comment,update_date_time) 

    VALUES ('$device_Id','$R1','$R2','$R3','$comment','$update_date_time')"); 

    mysql_query($query,$con); 
    printf("Records inserted: %d\n", mysql_affected_rows()); 

    echo($device_Id) 
    ?> 
+0

你做了什么调试? Wheres'echo($ device_Id)'的结尾分号?你也有SQL注入,你应该转义输入否则添加'''你的参数之一将打破查询... –

+0

尝试打印出'mysql_error()',看看是否有某种错误,并张贴它这里 – Darvex

+0

保持您的字符串在引号之外。例如,使用'sprintf'。另外,请注意用户输入,这可能是错误的。在你的'$ _POST'值上需要'Mysql_real_escape_string',正如@zan所说的 - 去看看PDO。旁注:使用'die()'是这里不需要的东西,使用propper错误处理代替 – Tikkes

回答

1

好的一个只能通过示例学习,停止使用mysql_functions(),它们不再被维护并且被正式弃用。而在PHP 5.6中,它们很可能会被删除,导致代码被破坏。

移动到准备查询的PDO。 当前的代码中使用PDO的端口:

<?php 
// SQL Config 
$config['sql_host']='surveyipad.db.6420177.hostedresource.com'; 
$config['sql_db'] ='surveyipad'; 
$config['sql_user']='tom'; 
$config['sql_pass']='ben'; 

// SQL Connect 
try { 
     $db = new PDO("mysql:host=".$config['sql_host'].";dbname=".$config['sql_db'], $config['sql_user'], $config['sql_pass']); 
     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
     $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
}catch (Exception $e){ 
     die('Cannot connect to mySQL server.'); 
} 

// Check for POST, add isset($_POST['device_Id']) ect to add validations 
if($_SERVER['REQUEST_METHOD']=='POST'){ 
    // Build your query with placeholders 
    $sql = "INSERT INTO survey_responsese_pfizer 
        (device_Id,R1,R2,R3,comment,update_date_time) 
        VALUES 
        (:device_Id, :R1, :R2, :R3, :comment, :update_date)"; 

    // Prepare it 
    $statement = $db->prepare($sql); 
    // Assign your vairables to the placeholders 
    $statement->bindParam(':device_Id', $_POST['device_Id']); 
    $statement->bindParam(':R1', $_POST['R1']); 
    $statement->bindParam(':R2', $_POST['R2']); 
    $statement->bindParam(':R3', $_POST['R3']); 
    $statement->bindParam(':comment', $_POST['comment']); 
    $statement->bindParam(':update_date', $_POST['update_date_time']); 
    // Execute the query 
    $statement->execute(); 

    echo htmlspecialchars($device_Id); 
} 
?> 

未经检验的寿,希望它帮助。

+0

为什么使用'die()'?你发现一个异常,为什么要杀了它?否则,很好的答案! +1 – Tikkes

+0

它在编码中给出了错误和例外 – user1808433

+0

在第一次编辑时'''之前有一个rou红的''''。 –