php 在mysql数据库中插入数据 [英] inserting data in mysql data base in php
本文介绍了php 在mysql数据库中插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 php 将数据从 iphone 发送到服务器它是从 iphone 发送数据但没有插入到 mysql 我正在使用以下 php 代码.
i am sending data from iphone to server using php it is sending data from iphone but not inserting in mysql i am using following php code.
<?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_functions(),它们不再维护并已正式弃用.而在 PHP 5.6 中,它们很可能会被删除,从而导致代码损坏.
Ok one only learns by example, stop using the mysql_functions(), They are no longer maintained and are officially deprecated. And in PHP 5.6 they will most likely be removed, rendering you code broken.
使用准备好的查询移动到 PDO.使用 PDO 的当前代码的端口:
Move over to PDO with prepared querys. A Port of your current code using 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);
}
?>
未经测试,希望有帮助.
Untested tho, hope it helps.
这篇关于php 在mysql数据库中插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文