在 Android/phpMyAdmin 中插入数据库时出错
Posted
技术标签:
【中文标题】在 Android/phpMyAdmin 中插入数据库时出错【英文标题】:Error inserting to database in Android/phpMyAdmin 【发布时间】:2016-06-06 17:39:26 【问题描述】:如果我在网络浏览器中测试我的 php 文件,它可以工作(例如,给定 newObsindiaries.php?idd="52"&ido="1"&when="10"
,它会毫无问题地插入数据库)。
但是,在 android 中,它不起作用并在日志中返回此消息:
org.json.JSONException: [idd=52, ido=1, when=10] 的字符 5 处未终止的数组
这是 PHP 代码:
<?php
$dbhost = "127.0.0.1";
$dbuser = "root";
$dbpass = "";
$dbname = "clinic_last";
$link = @mysqli_connect($dbhost,$dbuser,$dbpass,$dbname)
or die("Impossibile collegarsi al server: " . mysqli_error());
mysqli_select_db($link ,'clinic_last')
or die("unable to select database 'dbname': " . mysqli_error());
$idd = $_GET['idd'];
$ido = $_GET['ido'];
$when = $_GET['when'];
$string = ("INSERT INTO obsindiaries (`when`, ido, idd)
SELECT $when,$ido,idd FROM diaries WHERE idd = $idd LIMIT 1");
$string2 = "INSERT INTO obsindiaries (idod,idd,ido,`when`) VALUES
(NULL,'$idd','$ido','$when')";
$flag['code']=0;
$result = mysqli_query($link,$string);
// check if row inserted or not
if ($result)
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "**successfully Registration.**";
// echoing JSON response
echo json_encode($response);
if (!$result)
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
if (!$result)
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
mysqli_close($link);
?>
这是文件.class
的一部分:
public void ClickSaveObsindiaries()
SavingObs=(ImageButton)findViewById(R.id.saveObsindiaries);
SavingObs.setOnClickListener(new OnClickListener()
@Override
public void onClick(View arg0)
//INSERISCO VALORI DENTRO LISTA
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("idd", ID_diary.getText().toString()));
int positionTypeObs = typeObsindiaries.getSelectedItemPosition() + 1;
String valueType = String.valueOf(positionTypeObs);
nameValuePairs.add(new BasicNameValuePair("ido",valueType));
char first = hours.getSelectedItem().toString().charAt(0);
if (first=='I')
nameValuePairs.add(new BasicNameValuePair("when", IntervalHours.getText().toString()));
else
nameValuePairs.add(new BasicNameValuePair("when", hours.getSelectedItem().toString()));
System.out.println("valore di RESULT: "+nameValuePairs.toString());
try
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/newObsindiaries.php");
Log.e("httpPost is:"," "+httpPost.toString());
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));//,"UTF-8"
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
catch(Exception e)
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address", Toast.LENGTH_LONG).show();
try
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
catch(Exception e)
Log.e("Fail 2", e.toString());
try
JSONObject json_data = new JSONObject(nameValuePairs.toString());
code=(json_data.getInt("code"));
if(code==1)
Toast.makeText(getBaseContext(), "Inserted Successfully", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getBaseContext(), "Sorry, Try Again", Toast.LENGTH_LONG).show();
catch(Exception e)
Log.e("Fail 3", e.toString());
Log.e("JSON Parser", "Error parsing data " + e.toString());
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(add_obsindiaries.this, R.style.myDialog));
builder.setMessage("Misurazione inserita! Premere OK per tornare alla lista delle misurazioni")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog, int id)
Intent listOBS = new Intent(add_obsindiaries.this,obsindiaries_list.class);
fromObsList.putString("idDiary", fromObsList.getString("idDiary"));
listOBS.putExtras(fromObsList);
add_obsindiaries.this.finish();
startActivity(listOBS);
);
AlertDialog alert = builder.create();
alert.show();
);
【问题讨论】:
【参考方案1】:我认为问题出在这一行
JSONObject json_data = new JSONObject(nameValuePairs.toString());
您正在尝试解析从参数返回的数据。这没有意义。而nameValuePairs.toString()
将返回与 Json 格式不匹配的字符串,这就是您收到错误的原因。你应该使用result
而不是nameValuePairs.toString()
JSONObject json_data = new JSONObject(result);
【讨论】:
感谢回复,但还不行。日志显示“新”错误“org.json.JSONException:Java.lang.String 类型的值您需要检查从您的服务器返回的 Json。尝试使用 Postman 之类的工具来根据您的请求获得准确的结果。你能在你的php项目中发布函数
json_encode
吗?
我不知道问题出在哪里。我使用邮递员,ecc 检查它;如果在浏览器php文件中传递参数有效,否则无效,传递给php文件时格式结构有问题,我不知道真的需要帮助
你能把你在使用浏览器时得到的输出发到这里吗?
这是输出 "success":0,"message":"糟糕!发生错误。""success":0,"message":"必填字段是失踪”以上是关于在 Android/phpMyAdmin 中插入数据库时出错的主要内容,如果未能解决你的问题,请参考以下文章
有一个有序数组,要求将一个新输入的数插入到数组中并保证插入新数后,数组仍有序。
@mysql/xdevapi 如何在nodejs中调试“插入的行中错误的字段数”?