【发布时间】:2014-07-18 22:01:17
【问题描述】:
public class MainActivity extends Activity {
private ArrayList<NameValuePair> nameValuePairs;
private DefaultHttpClient httpclient;
private HttpPost httppost;
private HttpResponse response;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
InputStream is = null;
// http post
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("post",
"20"));
nameValuePairs
.add(new BasicNameValuePair("price", "14:30"));
nameValuePairs.add(new BasicNameValuePair("description",
"19"));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://mydomain111.site11.com/mysql_con.php");
httppost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag",
"Error in http connection" + e.toString());
}
} catch (Exception e) {
}
}
});
thread.start();
// TODO Auto-generated method stub
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
这是 php 部分:
<?php
$con=mysql_connect("mysqlxxx.000webhost.com","xxxxx", "xxxxxxxx") or die('Could not connect: ' . mysql_error());
mysql_select_db("xxxxxx_test",$con);
if(isset($_POST['post'])&&isset($_POST['price'])&&isset($_POST['description'])){
$post=$_POST['post'];
$issue=$_POST['price'];
$description=$_POST['description'];
$sql="INSERT INTO test (post,price,description) VALUES ('$post','$issue','$description')";
$r=mysql_query($sql);
if(!$r)
echo "Error in query: ".mysql_error();
}
else echo "no data endered";
mysql_close();
?>
我尝试了这段代码并在 000webhost 上创建了一个表并将我的 php 文件上传到那里。但是每当我从我的 android 手机或模拟器运行应用程序时,在这两种情况下,表都没有更新我想要插入的值,我还用浏览器打开了 php 文件,该文件保存到 xampp 上的 htdocs 中,浏览器显示:
" mysql_connect():连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立连接失败,因为连接的主机没有响应。在 C:\xampp\htdocs\Echo\mysql_con 中。第 5 行的 php"
现在,我怎样才能让它工作,特别是在我的 android 手机中。我是 android 新手,这段代码仅用于学习目的。
编辑:我没有发布日志,因为它很清楚并且没有显示错误
【问题讨论】:
-
您正在尝试从外部连接到 000webhost 数据库?
-
我正在尝试从我的 android 手机连接;所以我猜是外部连接。
-
您是高级用户? 000webhost数据库免费用户无法对外连接。
-
不,我是免费用户。我不知道。我认为情况就是这样。但它实际上也不适用于模拟器。
-
您的代码很容易受到 SQL 注入攻击,您可能想了解一下。另外,请注意 mysql 扩展(提供 mysql_ 函数)自 2012 年以来已被弃用,取而代之的是 mysqli 和 PDO 扩展。强烈建议不要使用它。见stackoverflow.com/questions/12859942/…
标签: php android mysql json database