在php中在mysql数据库中插入数据

在php中在mysql数据库中插入数据,php,mysql,Php,Mysql,我使用php从iphone向服务器发送数据。它从iphone发送数据,但不插入mysql。我使用以下php代码 <?php $con = mysql_connect("surveyipad.db.6420177.hostedresource.com","tom","ben"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("sur

我使用php从iphone向服务器发送数据。它从iphone发送数据,但不插入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)
   ?>

好的,我们只能通过示例了解,停止使用mysql_函数(),它们不再被维护,并且被正式弃用。在PHP5.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);
}
?>


未经测试,希望有帮助。

您进行了哪些调试?
echo($device\u Id)
的结尾分号在哪里?您还有sql注入,您应该转义输入,否则将
添加到一个参数将中断查询…尝试打印出
mysql\u error()
,查看是否存在某种错误,并将其发布到此处将字符串保留在引号之外。例如,使用
sprintf
。此外,请注意用户输入,它可能是错误的
Mysql\u real\u escape\u string将需要在您的
$\u POST
值上显示,并且正如@zan所说的,去看看PDO。旁注:此处不需要使用
die()
,请在中使用propper错误处理stead@Darvex插入的记录:-1我的Sql错误:0这是我在打印mmm后得到的结果…那么是否插入了值?您是否检查了数据库?为什么使用
die()
?你捕获了一个异常,为什么要杀死它?否则,答案很好+1.