我已经成功创建了一个mysql数据库并试图用一个php文件填充它。
php的代码如下所示:
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$userid = $_POST['userid'];
$time = $_POST['time'];
$button = $_POST['button'];
$weight = $_POST['weight'];
$sex = $_POST['sex'];
$sql = "INSERT INTO beerconsumption (userid, time, button, weight, sex)
VALUES ('userid', 'time', 'button', 'weight', 'sex')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
如果我mannualy调用php文件它确实会进行修改但只是0.如果我改变了行
VALUES ('1', 'time', 'button', 'weight', 'sex')";
它将一个放在表格的第一个字段中。 但如果我使用邮递员或我的Android应用程序发布不同的值,它仍然只是发布0。
目前我只是没有弄错。
Android脚本:
public void sendData(){
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
}, new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error){
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("verify", "******");
parameters.put("userid",userID);
parameters.put("time",Long.toString(java.lang.System.currentTimeMillis()));
parameters.put("button", Integer.toString(button));
parameters.put("weight",Integer.toString(calc.person.getWeight()));
parameters.put("sex",Integer.toString(calc.person.getSex()));
return parameters;
}
};
requestQueue.add(request);
}
答案 0 :(得分:1)
我测试你的代码是否完美,你可以查看表单提交和POST数据。
<?php
$servername="localhost";
$dbname="android";
$username="root";
$password="root";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO so(a,b,c,d,e) VALUES ('1', 'time', 'button', 'weight', 'sex')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
答案 1 :(得分:0)
我做了一些研究并将我的PHP代码更改为:
<?php
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$con = mysqli_connect(HOST,USER,PASS,DB);
$userid = $_POST['userid'];
$time = $_POST['time'];
$button = $_POST['button'];
$weight = $_POST['weight'];
$sex = $_POST['sex'];
$sql = "insert into beerconsumption (userid,time,button,weight,sex) values ('$userid','$time','$button','$weight','$sex')";
if(mysqli_query($con,$sql)){
echo 'success';
}
else{
echo 'failure';
}
mysqli_close($con);
?>
这似乎运作良好,但我现在有一些安全疑虑。这都是纯文本转移不是吗?