- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经对此进行了一段时间的研究,但一无所获。
我想做的是创建一个注册/登录 Activity ,它将所有访问详细信息存储在远程 SQL 数据库中。
我的代码大纲是创建“Registrar”对象,将其转换为 JSON 对象,并将该 JSON 对象转换为字符串,然后通过 httpclient 将该字符串作为帖子发送到 PHP 页面(位于在我的 XAMPP 上),请注意我使用的是 Android Studio 模拟器。
我的问题:
我不知道 JSON 文件是否被 PHP 服务器接收到。这是我的代码:
提交功能:
public void goSubmit(View view) throws IOException {
EditText nameEdit = (EditText) findViewById(R.id.nameEdit);
EditText idEdit = (EditText) findViewById(R.id.idEdit);
String name = nameEdit.getText().toString();
String ID = idEdit.getText().toString();
//Creating Student (Registrar) Object
Student registrar = new Student();
registrar.setMajor(majorEdit);
registrar.setName(name);
registrar.setId(ID);
//Creating JSON String
String registrarJSON = null;
try {
registrarJSON = ObjInJSON(registrar);
Toast.makeText(this, registrarJSON, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//Posting JSON String on Remote PHP
String PHPresponse = sendToRegistrationPHP(registrarJSON);
Toast.makeText(this, PHPresponse, Toast.LENGTH_LONG).show();
//Receive PIN from PHP as JSON String
//Parsing JSON string to integer (pin)
//Set PIN in registrar.getpin()
//Passing the object to setPassword Activity condition registrar.pin =! null
}
学生类(class):
public class Student {
String Id = "NULL" ;
String Major = "NULL";
String Name = "NULL";
String Password = "NULL";
String Pin = "NULL";
public String getPin() {
return Pin;
}
public void setPin(String pin) {
Pin = pin;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getId() {
return Id;
}
public String setId(String id) {
Id = id;
return id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getMajor() {
return Major;
}
public void setMajor(String major) {
Major = major;
}
}
创建字符串格式的 JSON 对象:
protected String ObjInJSON(Student studentC) throws JSONException, UnsupportedEncodingException {
String ID = studentC.getId();
String Pin = studentC.getPin();
String Major = studentC.getMajor();
String Password = studentC.getPassword();
String Name = studentC.getName();
JSONObject json_obj = new JSONObject();
json_obj.put("id", ID);
json_obj.put("password", Password);
json_obj.put("pin", Pin);
json_obj.put("major", Major);
json_obj.put("name", Name);
return json_obj.toString();
}
发送到 PHP 服务器:
public static String sendToRegistrationPHP(String jarr) throws IOException {
StringBuffer response = null;
try {
String myurl = "10.0.2.2:8070/StudentaccistancePHP/MySqlTEST.php";
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(jarr);
writer.close();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response in universal: " + response.toString());
} catch (Exception exception) {
System.out.println("Exception: " + exception);
}
if (response != null) {
return response.toString();
}
else return "Not WORKING !";
}
PHP 服务器:
<?php
$json = file_get_contents('php://input');
$data = json_decode($json, true);
$ID = $data['id'];
$password = $data['password'];
$pin = "323232";
$major = $data['major'];
$name = $data['name'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "studentassictance";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "INSERT INTO students (id, major, name, password, pin)
VALUES ('$ID', '$major', '$name', '$password', '$pin')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully <br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
但是,没有任何内容被插入到数据库中。
最佳答案
首先,您需要检查以 JSON 形式到达 PHP 端的内容。你可以
var_dump($json,$data);
在 json_encode()
调用后观察它是一个有效的 JSON。你可以验证它here
其次,向您展示SHOW CREATE TABLE students
第三,将所有内容重写为 PDO,因为它支持命名参数,如果需要的话,理论上您以后可以更轻松地迁移到另一个数据库引擎。所以它会是这样的:
<?php
define('DSN','mysql:dbname=test;host=localhost');
define('DB_USERNAME','testuser');
define('DB_PASSWORD','testpassword');
$connect = new PDO(DSN, DB_USERNAME, DB_PASSWORD);
$json = file_get_contents('php://input');
/*$json = '{
"id": "111",
"password": "sfsdfsdf",
"major": "Math",
"name": "Test User"
}';*/
$data = json_decode($json, true);
$ID = $data['id'];
$password = $data['password'];
$pin = "323232";
$major = $data['major'];
$name = $data['name'];
$sql = "INSERT INTO `students`(`id`,`major`, `name`, `password`, `pin`) VALUES(:id, :major, :name, :password, :pin)";
$result = $connect->prepare($sql);
//bind parameter(s) to variable(s)
$result->bindParam( ':id', $ID, PDO::PARAM_INT );
$result->bindParam( ':major', $major, PDO::PARAM_STR );
$result->bindParam( ':name', $name, PDO::PARAM_STR );
$result->bindParam( ':password', $password, PDO::PARAM_STR );
$result->bindParam( ':pin', $pin, PDO::PARAM_STR );
$status = $result->execute();
if ($status)
{
echo "New record created successfully <br>";
} else
{
echo "Error: <br>" .
var_dump($connect->errorInfo(),$status);
}
$connect = null;
关于php - 从 Android 应用程序在 PHP 文件上发布 JSON 文件,并将 JSON 解码为 PHP 上的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33972814/
有人可以解释一下为什么我得到: "use of unassigned local variable number_of_column" for: if (i f.LastWriteTime).Fir
我正在尝试为查询定义和初始化 MySQL 变量。 我有以下几点: declare @countTotal int; SET @countTotal = select COUNT(*) from nG
局部变量由小写字母或下划线(_)开头.局部变量不像全局和实变量一样在初始化前含nil值. ruby>$foo nil ruby>@foo nil ruby>foo ER
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
当我单击 Login 类上的注册按钮时,出现 nullpointerException,它给出了该错误。我尝试修改本地和全局变量,但似乎没有任何方法可以修复该错误,我可能在 onClickListen
我之前看过一些关于此的帖子,但我一直无法找到有关 actionListeners 的帖子。我正在尝试使用 JButton 数组创建井字棋。如果可能的话,如何在使用 for 循环临时变量的同时向它们添加
我试图找出一种将 getView() 方法中的位置变量传递给内部类的方法。但是,这不能是最终变量,因为 ListView 中的每个项目都会调用 getView() ,因此它会发生变化。有没有办法访问该
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 9 年前。 Improve th
这对你们中的某些人来说似乎微不足道,但我对下面的这两个示例感到困惑。 int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int i
这个问题在这里已经有了答案: How do JavaScript closures work? (86 个答案) 关闭 7 年前。 所以我正在复习我的 vanilla Javascript,专门用于
我正在将mockito与spring(java 1.8)一起使用,并且我尝试在我的Answer对象中使用局部变量: public IProductDTO productForMock = null;
是否可以在java中为静态方法注入(inject)局部变量,比如 @Inject public void someMethod() { @MyInjectQualifier MyObjectC
我有一个函数,每 2 秒被重复调用一次,每次从屏幕顶部带来一个具有随机纹理的球。我希望能够在 touchesBegan 中使用这个球,但我不能,因为它是一个局部变量。我试过将它设为全局变量,但这给了我
这是(我假设)一个基本问题,但我似乎无法弄清楚。 给定以下代码: from src.Globals import * import pygame # Used to manage how fast t
这就是我在循环中引用全局变量的方法。 _.forEach(myTableName.detailsObjects, function (o, key) { if
我已经创建了一些代码: import numpy as np Length=(2.7)*10**-3 Nx=4 x = np.linspace(0, Length, Nx+1) # mes
如何获取局部变量? 我有这个代码 if (ctrl is Control) { Control c = (Control)ctrl; foreach (object innerCtrl
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: Difference between class variables and class instance
我正在学习 Python 3,我有一个关于 Python 中面向对象编程的非常基本的问题。这是我的代码。 class pet: number_of_legs = 0 def count
我有以下代码块: class Student{ int age; //instance variable String name; //instance varia
我是一名优秀的程序员,十分优秀!