怎么让php连接mysql测试代码l

1054人阅读
1、php.ini的设置
1)php.ini不需要复制到c:/windows/system32或c:/windows/system中,只要apache中的conf下的httpd.conf中配置PHPIniDir指定php相关文件所在路径就足够了。
2)extension启用php_mstring.dll,php_mysql.dll,php_mysqli.dll。这是配置PHP5的要求,有的文章写PHP4中自动启用mysql相关功能未测试。
3)extension_dir设置成php程序中ext的文件夹路径
4)不需要复制libmysql.dll或php5ts.dll到windows文件夹中,不用复制到windows/system32或windows/system中。
2、apache中httpd.conf的配置
1)在模块加载相关的后面写: LoadModule php5_module &c:/php5/php5apache2_2.dll&
并在后面加上对php程序文件夹的指向: PHPIniDir &c:/php/&
2)在文件类型中补充& AddType application/x-httpd-php .php
3)最重要的一项,如果使用的mysql是install版本可能不会用此项,但如果是noinstall版本,就是一定要按如下写,放在加载模块的前一句
LoadFile &c:/php5/libmysql.dll&
LoadModule php5_module &c:/php5/php5apache2_2.dll&
libmysql.dll文件是有用的,但需要的是让apache知道这个文件的位置是关键。这样用phpinfo()检查环境时,就能看到mysql相关项的设置了。
感谢 .cn/s/blog_azh17.html& 这个文章的作者。
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:61869次
积分:1053
积分:1053
排名:千里之外
原创:39篇
评论:14条正文 php连接mysql超时的解决方法
php连接mysql超时的解决方法
发布时间: & 编辑:
问题:php连接mysql读写数据,过一天就不work了。 经查发现mysql connection默认的超时时间为8小时。如果想让这个连接永久不超时,该怎么办呢?
function reconnect(){&
&&& if (!mysql_ping ($this-&db)) {&
&&&&&&& //here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.&
&&&&&&& mysql_close($this-&db);&
&&&&&&& $this-&connect();&
其中的mysql_ping()用来判断连接是否已经被断开了,若是断开了,关闭当前的链接,重新创建新的连接。
这样,只要发现连接被断开了,即可重新连接了。您可能感兴趣的文章:mysql_pconnect的水挺深的
服务器君一共花费了179.957 ms进行了4次数据库查询,努力地为您提供了这个页面。
试试阅读模式?希望听取您的建议
PHP的MySQL持久化连接,美好的目标,却拥有糟糕的口碑,往往令人敬而远之。这到底是为啥么。近距离观察后发现,这家伙也不容易啊,要看Apache的脸色,还得听MySQL指挥。
对于作为Apache模块运行的PHP来说,要实现MySQL持久化连接,首先得取决于Apache这个web服务器是否支持Keep-Alive。
Keep-Alive
Keep-Alive是什么东西?它是http协议的一部分,让我们复习一下没有Keep-Alive的http请求,从客户在浏览器输入一个有效url地址开始,浏览器就会利用socket向url对应的web服务器发送一条TCP请求,这个请求成功一次就得需要来回握三次手才能确定,成功以后,浏览器利用socket TCP连接资源向web服务器请求http协议,发送以后就等着web服务器把http返回头和body发送回来,发回来后浏览器关闭socket连接,然后做http返回头和body的解析工作,最后呈现在浏览器上的就是漂亮的页面了。这里面有什么问题呢?TCP连接需要三次握手,也就是来回请求三次方能确定一个TCP请求是否成功,然后TCP关闭呢?来回需要4次请求才能完成!每次http请求就3次握手,4次拜拜,这来来回回的不嫌累啊,多少时间和资源都被浪费在socket连接关闭上了,能不能一次socket TCP连接发送多次http请求呢?于是Keep-Alive就应运而生,http/1.0里需要客户端自己在请求头加入Connection:Keep-alive方能实现,在这里我们只考虑http1.1了,只需要设置一下Apache,让它默认就是Keep-Alive持久连接模式(Apache必须1.2+才能支持Keep-Alive)。在httpd.conf里找到KeepAive配置项,果断设置为On,MaxKeepAliveRequests果断为0(一个持久TCP最多允许的请求数,如果过小,很容易在TCP未过期的情况下,达到最大连接,那下次连接就又是新的TCP连接了,这里设置0表示不限制),然后对于mysql_pconnect最重要的选项KeepAliveTimeout设置为15(表示15秒)。
好了,重启Apache,测试一下,赶紧写行东西:
echo "Apache进程号:". getmypid();
很简单,获取当前PHP执行者(Apache)的进程号,用浏览器浏览这个页面,看到什么?对,有看到一串进程号数字,15秒内,连续刷新页面,看看进程号有无变化?木有吧?现在把手拿开,交叉在胸前,度好时间,1秒,2秒,3,...15,16。好,过了15秒了,再去刷新页面,进程号有没有变化?变了!又是一个新的Apache进程了,为什么15秒后就变成新的进程了?记得我们在Apache里设置的KeepAliveTimeout吗?它的值就是15秒。现在我们应该大致清楚了,在web服务器默认打开KeepAlive的情况下,客户端第一次http成功请求后,Apache不会立刻断开socket,而是一直监听来自这一客户端的请求,监听多久?根据KeepAliveTimeout选项配置的时间决定,一旦超过这一时间,Apache就会断开socket了,那么下次同一客户端再次请求,Apache就会新开一个进程来相应。所以我们之前15内不停的刷新页面,看到的进程号都是一致的,表明是浏览器请求给了同一个Apache进程。
浏览器是怎么知道不需要重新进行TCP连接就可以直接发送http请求呢?因为http返回头里就会带上Connection:keep-alive,Keep-alive:15两行,意思就是让客户端浏览器明白,这次socket连接我这边还没关闭呢,你可以在15内继续使用这个连接,并发送http请求,于是乎浏览器就知道应该怎么做了。
那么,PHP的MySQL连接资源是怎么被hold住的呢,这需要查看PHP的mysql_pconnect的函数代码,我看了下,大概的做法就是mysql_pconnect根据当前Apache进程号,生成hash key,找hash表内有无对应的连接资源,没有则推入hash表,有则直接使用。有些代码片段可以说明(具体可查看PHP5.3.8源码ext/mysql/PHP_mysql.c文件690行PHP_mysql_do_connect函数)
#1.生成hash key
user=php_get_current_user();//获取当前PHP执行者(Apache)的进程唯一标识号
//hashed_details就是hash key
hashed_details_length = spprintf(&hashed_details, 0, "MySQL__%s_", user);
#2.如果未找到已有资源,就推入hash表,名字叫persistent_list,如果找到就直接使用
/* try to find if we already have this link in our persistent list */
if (zend_hash_find(&EG(persistent_list), hashed_details, hashed_details_length+1, (void **) &le)==FAILURE) {
/* we don't */
/* hash it up(推入hash表) */
Z_TYPE(new_le) = le_
new_le.ptr =
if (zend_hash_update(&EG(persistent_list), hashed_details, hashed_details_length+1, (void *) &new_le, sizeof(zend_rsrc_list_entry), NULL)==FAILURE) {
{/* The link is in our list of persistent connections(连接已在hash表里)*/
mysql = (PHP_mysql_conn *) le->//直接使用对应的sql连接资源
zend_hash_find比较容易看明白,原型是zend_hash_find(hash表,key名,key长,value);如果找到,value就有值了。
MySQL的wait_timeout和interactive_timeout
说完Keep-Alive,该到MySQL家串串门了,说的是mysql_pconnect,怎么能绕开MySQL的设置。影响mysql_pconnect最重要的两个参数就是wait_timeout和interactive_timeout,它们是什么东西?先撇一边,首先让我们把上面的代码改动一下PHP代码
$conn = mysql_pconnect("localhost","root","123456") or die("Can not connect to MySQL");
echo "MySQL线程号:". MySQL_thread_id($conn). "&br />";
echo "Apache进程号". getmypid();
以上的代码没啥好解释的,让我们用浏览器浏览这个页面,看到什么?看到两个显眼的数字。一个是MySQL线程号,一个是Apache进程号,好了,15秒后再刷新这个页面,发现这两个id都变了,因为已经是新的Apache进程了,进程id是新的,hash key就变了,PHP只好重新连接MySQL,连接资源推入persistent list。如果15内刷新呢?Apache进程肯定不变,MySQL线程号会变吗?答案得问MySQL了。首先这个MySQL_thread_id是什么东西?shell方式登录MySQL后执行命令'',看到了什么?
+-----+------+-----------+------+--------+-----+------+-----------------+
| User | Host
| Command| Time| State| Info
+-----+------+-----------+------+--------+-----+------+-----------------+
| 348 | root | localhost | NULL | Query
0| NULL | show processlist|
| 349 | root | localhost | NULL | Sleep
+-----+------+-----------+------+--------+-----+------+-----------------+
发现了很重要的信息,这个processlist列表就是记录了正在跑的线程,忽略Info列为show processlist那行,那行是你当前shell登录MySQL的线程。PHP连接MySQL的线程就是Id为349那行,如果读者自己做测试,应该知道这个Id=349在你的测试环境里是另外一个值,我们把这个值和网页里输出的MySQL_thread_id($conn)做做比较,对!他们是一样的。接下来最重要的是观察Command列和Time列,Command = Sleep,表明什么?表明我们mysql_pconnect连接后就一直在sleep,Time字段就告诉我们,这个线程Sleep了多久,那么Sleep了多久这个线程才能作废呢?那就是wait_timeout或者interactive_timeout要做的工作了,他们默认的值都是8小时,天啊,太久了,所以如果说web服务器关掉KeepAlive支持,那个这个processlist很容易就被撑爆,就爆出那个Too many connections的错误了,max_connectiosns配置得再多也没用。为了观察这两个参数,我们可以在MySQL配置文件my.cnf里设置这两个值,找到[MySQLd]节点,在里面设置多两行
interactive_timeout = 60
wait_timeout
配置完后,重启MySQL,shell登录MySQL,这时候show processlist可以发现只有当前线程。然后运行那个带有mysql_pconnect的PHP页面,再回来MySQL端show processlist可发现,多了一个Commond为Sleep的线程,不停的show processlist(方向键上+enter键)观察Time列的变化2,5,10...14!,突然那个Sleep线程程被kill掉了,咋回事,还没到30秒呢,噢!忘了修改一下Apache keepalive的参数了,把KeepAliveTimeOut从15改成120(只为观察,才这么改),重启Apache。刷新那个页面,好,开始不停的show processlist,2..5..10..14,15,..20...26....28,29!线程被kill,这次是因为wait_timeout起了作用,浏览器那边停了30秒,30内如果浏览器刷新,那这个Time又会从0开始计时。这种连接不属于interactive connection(MySQL shell登录那种连接就属于interactive connection),所以采用了wait_timeout的值。如果mysql_pconnect的第4个参数改改呢
$conn = mysql_pconnect('localhost','root','123456',MySQL_CLIENT_INTERACTIVE);
echo "MySQL线程号:".MySQL_thread_id($conn)."&br />";
echo "Apache进程号:".getmypid();
刷新下页面,MySQL那边开始刷show processlist,这回Time > 30也不会被kill,>60才被kill了,说明设置了MySQL_CLIENT_INTERACTIVE,就会被MySQL视为interactive connection,那么这次PHP的MySQL连接在120秒内未刷新的情况下,何时作废将取决于MySQL的interactive_timeout的配置值。
PHP的mysql_pconnect要达到功效,首先必须保证Apache是支持keep alive的,其次KeepAliveTimeOut应该设置多久呢,要根据自身站点的访问情况做调整,时间太短,keep alive没啥意义,时间太长,就很可能为一个闲客户端连接牺牲很多服务器资源,毕竟hold住socket监听进程是要消耗cpu内存的。最后Apache的KeepAliveTimeOut配置得和MySQL的time out配置要有个平衡点,联系以上的观察,假设mysql_pconnect未带上第4个参数,如果Apache的KeepAliveTimeOut设置的秒数比wait_timeout小,那真正对mysql_pconnect起作用的是Apache而不是MySQL的配置。这时如果MySQL的wait_timeout偏大,并发量大的情况下,很可能就一堆废弃的connection了,MySQL这边如果不及时回收,那就很可能Too many connections了。可是如果KeepAliveTimeOut太大呢,又回到之前的问题,所以貌似Apache。KeepAliveTimeOu不要太大,但比MySQL。wait_timeout 稍大,或者相等是比较好的方案,这样可以保证keep alive过期后,废弃的MySQL连接可以及时被回收。
本文地址:,欢迎访问原出处。
不打个分吗?
转载随意,但请带上本文地址:
如果你认为这篇文章值得更多人阅读,欢迎使用下面的分享功能。
小提示:您可以按快捷键 Ctrl + D,或点此 。
大家都在看
现代魔法研究协会欢迎你
阅读一百本计算机著作吧,少年
马丁 (作者), 邓辉 (译者)
《敏捷软件开发:原则模式与实践》由享誉全球的软件开发专家和软件工程大师Robert C.Martin将向您展示如何解决软件开发人员、项目经理及软件项目领导们所面临的最棘手的问题。这本综合性、实用性的敏捷开发和极限编程方面的指南,是由敏捷开发的创始人之一所撰写的。1.讲述在预算和实践要求下,软件开发人员和项目经理如何使用敏捷开发完成项目;2.使用真实案例讲解如何用极限编程来设计、测试、重构和结对编程;3.包含了极具价值的可多次使用的C++和JAVA源代码;4.重点讲述了如何使用UML和设计模式解决面向客户系统的问题。
扫一扫,在手机上阅读
栏目最新博文
7,385 views
43,368 views
18,806 views
32,263 views
32,595 views
24,621 views
54,096 views
52,283 views
24,651 views
58,893 views
栏目博文推荐
21,882 views
4,813 views
13,641 views
23,024 views
10,910 views
13,066 views
9,491 views
6,777 views
9,545 views
13,430 views
天才就其本质而论只不过是对事业、对工作过程的热爱而已。
关于网站与作者
互联网信息太多太杂,各互联网公司不断推送娱乐花边新闻,SNS,微博不断转移我们的注意力。但是,我们的时间和精力却是有限的。这里是互联网浩瀚的海洋中的一座宁静与美丽的小岛,供开发者歇息与静心潜心修炼(愿景)。
“Veda”的本义是知识、启示,希望这里能为开发者提供充足的技术资料。
我的电子邮件gonnsai(,腾讯微博:,欢迎与我联系。18743人阅读
Android(79)
我们先来看一个简单的Android app例子(这里是一个商品存货清单项目),在Android程序中,我们可以访问(call)PHP脚本来执行简单的CRUD操作(创建,读取,更新,删除)。为了使你对它的体系结构有一个大概的了解,这里先说一下它是怎么工作的。首先你的Android项目访问(call)PHP脚本来执行一条数据操作,我们称它为“创建”。然后PHP脚本连接MySQL数据库来执行这个操作。这样,数据从Android程序流向PHP脚本,最终存储在MySQL数据库中。
好了,让我们来深入的看一下。
请注意:这里提供的代码只是为了使你能简单的连接Android项目和PHP,MySQL。你不能把它作为一个标准或者安全编程实践。在生产环境中,理想情况下你需要避免使用任何可能造成潜在注入漏洞的代码(比如MYSQL注入)。MYSQL注入是一个很大的话题,不可能用单独的一篇文章来说清楚,并且它也不在本文讨论的范围内,所以本文不以讨论。
1. 什么是WAMP Server
WAMP是Windows,Apache,MySQL和PHP,Perl,Python的简称。WAMP是一个一键安装的软件,它为开发PHP,MySQL Web应用程序提供一个环境。安装这款软件你相当于安装了Apache,MySQL和PHP。或者,你也可以使用。
2. 安装和使用WAMP Server
你可以从下载WAMP,安装完成之后,可以从开始-&所有程序-&WampServer-&StartWampServer运行该程序。
在浏览器中输入来测试你的服务器是否安装成功。同样的,也可以打开来检验phpmyadmin是否安装成功。
3. 创建和运行PHP项目
现在,你已经有一个能开发PHP和MYSQL项目的环境了。打开安装WAMP Server的文件夹(在我的电脑中,是C:\wamp\),打开www文件夹,为你的项目创建一个新的文件夹。你必须把项目中所有的文件放到这个文件夹中。
新建一个名为android_connect的文件夹,并新建一个php文件,命名为test.php,尝试输入一些简单的php代码(如下所示)。输入下面的代码后,打开,你会在浏览器中看到“Welcome,I am connecting Android to
PHP,MySQL”(如果没有正确输入,请检查WAMP配置是否正确)
echo&Welcome, I am connecting Android to PHP, MySQL&;
?&4. 创建MySQL数据库和表
在本教程中,我创建了一个简单的只有一张表的数据库。我会用这个表来执行一些示例操作。现在,请在浏览器中输入,并打开phpmyadmin。你可以用PhpMyAdmin工具创建数据库和表。
创建数据库和表:数据库名:androidhive,表:product
CREATE TABLE products(
pid int(11) primary key auto_increment,
name varchar(100) not null,
price decimal(10,2) not null,
description text,
created_at timestamp default now(),
updated_at timestamp
);5. 用PHP连接MySQL数据库
现在,真正的服务器端编程开始了。新建一个PHP类来连接MYSQL数据库。这个类的主要功能是打开数据库连接和在不需要时关闭数据库连接。
新建两个文件db_config.php,db_connect.php
db_config.php--------存储数据库连接变量
db_connect.php-------连接数据库的类文件
db_config.php
 * All database connection variables
define('DB_USER', &root&); // db user
define('DB_PASSWORD', &&); // db password (mention your db password here)
define('DB_DATABASE', &androidhive&); // database name
define('DB_SERVER', &localhost&); // db server
这里的DB_USER &DB_PASSWORD要换成自己数据库对应的用户名、密码
db_connect.php
 * A class file to connect to database
class DB_CONNECT {
    // constructor
    function __construct() {
        // connecting to database
        $this-&connect();
    }
    // destructor
    function __destruct() {
        // closing db connection
        $this-&close();
    }
    /**
     * Function to connect with database
     */
    function connect() {
        // import database connection variables
        require_once __DIR__ . '/db_config.php';
        // Connecting to mysql database
        $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
        // Selecing database
        $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
        // returing connection cursor
        return $
    }
    /**
     * Function to close db connection
     */
    function close() {
        // closing db connection
        mysql_close();
    }
?&怎么调用:当你想连接MySQl数据库或者执行某些操作时,可以这样使用db_connect.php
$db= new DB_CONNECT(); // creating class object(will open database connection)6. 使用PHP执行基本CRUD操作
在这部分,我将讲述使用PHP对MySQL数据库执行基本CRUD(创建,读取,更新,删除)操作。
如果你是PHP和MySQL新手,我建议你可以先学习和基础知识。
6. a)在MYSQL中新建一行(创建一行新的产品)
在你的PHP项目中新建一个php文件,命名为create_product.php,并输入以下代码。该文件主要实现在products表中插入一个新的产品。
在下面的代码我使用POST来读取产品数据并把他们存储在products表中。
最后我会输出一些JSON返回值,以便返回给客户端(Android项目)
create_product.php
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
    $name = $_POST['name'];
    $price = $_POST['price'];
    $description = $_POST['description'];
    // include db connect class
    require_once __DIR__ . '/db_connect.php';
    // connecting to db
    $db = new DB_CONNECT();
    // mysql inserting a new row
    $result = mysql_query(&INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')&);
    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response[&success&] = 1;
        $response[&message&] = &Product successfully created.&;
        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response[&success&] = 0;
        $response[&message&] = &Oops! An error occurred.&;
        // echoing JSON response
        echo json_encode($response);
    }
    // required field is missing
    $response[&success&] = 0;
    $response[&message&] = &Required field(s) is missing&;
    // echoing JSON response
    echo json_encode($response);
?&对于上面的代码,JSON的返回值会是:
当POST 参数丢失
&success&: 0,
&message&: &Required field(s) is missing&
}当product成功创建
&success&: 1,
&message&: &Product successfully created.&
}当插入数据时出现错误
&success&: 0,
&message&: &Oops! An error occurred.&
实际测试的时候,出现Required field(s) is missing php错误,我把$_POST换成$_GET就对了,对应的NewProductActivity也要换成GET方法
6. b)从MySQL中读取一行信息(读取产品详细信息)
创建一个新的php文件,命名为get_product_details.php,写入以下代码。
该文件通过传递产品id作为POST参数获得单个产品的详细信息
get_product_details.php
 * Following code will get single product details
 * A product is identified by product id (pid)
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET[&pid&])) {
    $pid = $_GET['pid'];
    // get a product from products table
    $result = mysql_query(&SELECT *FROM products WHERE pid = $pid&);
    if (!empty($result)) {
        // check for empty result
        if (mysql_num_rows($result) & 0) {
            $result = mysql_fetch_array($result);
            $product = array();
            $product[&pid&] = $result[&pid&];
            $product[&name&] = $result[&name&];
            $product[&price&] = $result[&price&];
            $product[&description&] = $result[&description&];
            $product[&created_at&] = $result[&created_at&];
            $product[&updated_at&] = $result[&updated_at&];
            // success
            $response[&success&] = 1;
            // user node
            $response[&product&] = array();
            array_push($response[&product&], $product);
            // echoing JSON response
            echo json_encode($response);
        } else {
            // no product found
            $response[&success&] = 0;
            $response[&message&] = &No product found&;
            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no product found
        $response[&success&] = 0;
        $response[&message&] = &No product found&;
        // echo no users JSON
        echo json_encode($response);
    }
    // required field is missing
    $response[&success&] = 0;
    $response[&message&] = &Required field(s) is missing&;
    // echoing JSON response
    echo json_encode($response);
?&The json response for the above file will be
When successfully getting product details
&success&: 1,
&product&: [
&pid&: &1&,
&name&: &iPHone 4S&,
&price&: &300.00&,
&description&: &iPhone 4S white&,
&created_at&: & 01:41:42&,
&updated_at&: & 00:00:00&
When no product found with matched pid
&success&: 0,
&message&: &No product found&
}6. c)从MySQL读取所有行(读取所有产品信息)
我们需要用json数据在Android设备上显示所有的产品。
新建一个php文件,命名为get_all_products.php,写入以下代码。
get_all_products.php
 * Following code will list all the products
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query(&SELECT *FROM products&) or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) & 0) {
    // looping through all results
    // products node
    $response[&products&] = array();
    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $product = array();
        $product[&pid&] = $row[&pid&];
        $product[&name&] = $row[&name&];
        $product[&price&] = $row[&price&];
        $product[&created_at&] = $row[&created_at&];
        $product[&updated_at&] = $row[&updated_at&];
        // push single product into final response array
        array_push($response[&products&], $product);
    }
    // success
    $response[&success&] = 1;
    // echoing JSON response
    echo json_encode($response);
    // no products found
    $response[&success&] = 0;
    $response[&message&] = &No products found&;
    // echo no users JSON
    echo json_encode($response);
And the JSON response for above code
Listing all Products
&products&: [
&pid&: &1&,
&name&: &iPhone 4S&,
&price&: &300.00&,
&created_at&: & 02:04:02&,
&updated_at&: & 00:00:00&
&pid&: &2&,
&name&: &Macbook Pro&,
&price&: &600.00&,
&created_at&: & 02:04:51&,
&updated_at&: & 00:00:00&
&pid&: &3&,
&name&: &Macbook Air&,
&price&: &800.00&,
&created_at&: & 02:05:57&,
&updated_at&: & 00:00:00&
&pid&: &4&,
&name&: &OS X Lion&,
&price&: &100.00&,
&created_at&: & 02:07:14&,
&updated_at&: & 00:00:00&
&success&: 1
When products not found
&success&: 0,
&message&: &No products found&
}6. d)在MySQL中更新某一行(更新产品详细信息)
新建一个php文件,命名为update_product.php。每一个产品通过pid标识。
update_product.php
 * Following code will update a product information
 * A product is identified by product id (pid)
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['pid']) && isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
    $pid = $_POST['pid'];
    $name = $_POST['name'];
    $price = $_POST['price'];
    $description = $_POST['description'];
    // include db connect class
    require_once __DIR__ . '/db_connect.php';
    // connecting to db
    $db = new DB_CONNECT();
    // mysql update row with matched pid
    $result = mysql_query(&UPDATE products SET name = '$name', price = '$price', description = '$description' WHERE pid = $pid&);
    // check if row inserted or not
    if ($result) {
        // successfully updated
        $response[&success&] = 1;
        $response[&message&] = &Product successfully updated.&;
        // echoing JSON response
        echo json_encode($response);
    } else {
    }
    // required field is missing
    $response[&success&] = 0;
    $response[&message&] = &Required field(s) is missing&;
    // echoing JSON response
    echo json_encode($response);
?&The json reponse of above code, when product is updated successfully
&success&: 1,
&message&: &Product successfully updated.&
}6. e)在MySQL中删除某一行(删除一个产品)
新建一个php文件,命名为delete_product.php。该文件主要功能是从数据库中删除一个产品。
delete_product.php
 * Following code will delete a product from table
 * A product is identified by product id (pid)
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['pid'])) {
    $pid = $_POST['pid'];
    // include db connect class
    require_once __DIR__ . '/db_connect.php';
    // connecting to db
    $db = new DB_CONNECT();
    // mysql update row with matched pid
    $result = mysql_query(&DELETE FROM products WHERE pid = $pid&);
    // check if row deleted or not
    if (mysql_affected_rows() & 0) {
        // successfully updated
        $response[&success&] = 1;
        $response[&message&] = &Product successfully deleted&;
        // echoing JSON response
        echo json_encode($response);
    } else {
        // no product found
        $response[&success&] = 0;
        $response[&message&] = &No product found&;
        // echo no users JSON
        echo json_encode($response);
    }
    // required field is missing
    $response[&success&] = 0;
    $response[&message&] = &Required field(s) is missing&;
    // echoing JSON response
    echo json_encode($response);
?&When product successfully deleted
&success&: 1,
&message&: &Product successfully deleted&
When product not found
&success&: 0,
&message&: &No product found&
}到目前为止,我们为products表建立了一个简单的接口。服务器端编程已经完成了,接下来让我们开始真正的Android应用程序编程。
7. 新建一个Android应用程序
在Eclipse IDE中创建一个新项目,填写所需的细节信息。
1. 新建项目,在菜单中选择File-&New-&Android Project,把Activity类命名为MainScreenActivity
2. 打开AndroidManifest.xml,添加以下代码。我先在manifest文件中添加了所需的全部Activity类。同样需要添加INTERNET连接权限(非常重要)
AndroidManifest.xml
&?xml version=&1.0& encoding=&utf-8&?&
&manifest xmlns:android=&/apk/res/android&
    package=&com.example.androidhive&
    android:versionCode=&1&
    android:versionName=&1.0& &
    &uses-sdk android:minSdkVersion=&8& /&
    &application
        android:configChanges=&keyboardHidden|orientation&
        android:icon=&@drawable/ic_launcher&
        android:label=&@string/app_name& &
        &activity
            android:name=&.MainScreenActivity&
            android:label=&@string/app_name& &
            &intent-filter&
                &action android:name=&android.intent.action.MAIN& /&
                &category android:name=&android.intent.category.LAUNCHER& /&
            &/intent-filter&
        &/activity&
        &!-- All Product Activity --&
        &activity
            android:name=&.AllProductsActivity&
            android:label=&All Products& &
        &/activity&
        &!-- Add Product Activity --&
        &activity
            android:name=&.NewProductActivity&
            android:label=&Add New Product& &
        &/activity&
        &!-- Edit Product Activity --&
        &activity
            android:name=&.EditProductActivity&
            android:label=&Edit Product& &
        &/activity&
    &/application&
    &!--  Internet Permissions --&
    &uses-permission android:name=&android.permission.INTERNET& /&
&/manifest&3. 在res-&layout文件夹下新建一个xml文件,命名为mian_screen.xml。这个layout文件包含两个简单的按钮,通过这两个按钮可以查看所有产品和添加新产品。如下图所示
main_screen.xml
&?xml version=&1.0& encoding=&utf-8&?&
&LinearLayout xmlns:android=&/apk/res/android&
    android:layout_width=&fill_parent&
    android:layout_height=&fill_parent&
    android:orientation=&vertical&
    android:gravity=&center_horizontal&&
    &!--  Sample Dashboard screen with Two buttons --&
    &!--  Button to view all products screen --&
    &Button android:id=&@+id/btnViewProducts&
        android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:text=&View Products&
        android:layout_marginTop=&25dip&/&
    &!--  Button to create a new product screen --&
    &Button android:id=&@+id/btnCreateProduct&
        android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:text=&Add New Products&
        android:layout_marginTop=&25dip&/&
&/LinearLayout&
4. 打开MainScreenActivity.java为main_screen.xml文件里的两个按钮添加点击事件
MainScreenActivity.java
package com.example.
import android.app.A
import android.content.I
import android.os.B
import android.view.V
import android.widget.B
public class MainScreenActivity extends Activity{
    Button btnViewP
    Button btnNewP
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_screen);
        // Buttons
        btnViewProducts = (Button) findViewById(R.id.btnViewProducts);
        btnNewProduct = (Button) findViewById(R.id.btnCreateProduct);
        // view products click event
        btnViewProducts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Launching All products Activity
                Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                startActivity(i);
            }
        });
        // view products click event
        btnNewProduct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Launching create new product activity
                Intent i = new Intent(getApplicationContext(), NewProductActivity.class);
                startActivity(i);
            }
        });
    }
}5. 在ListView中显示所有产品(读取)
现在我们需要一个Activity来以列表的形式显示所有产品。如我们所知,使用ListView需要两个xml文件,一个是列表布局,另一个是单个的列表项布局。在res-&layout文件夹下新建两个xml文件:all_product.xml和list_item.xml
all_product.xml
&?xml version=&1.0& encoding=&utf-8&?&
&LinearLayout xmlns:android=&/apk/res/android&
    android:layout_width=&fill_parent&
    android:layout_height=&fill_parent&
    android:orientation=&vertical&&
    &!-- Main ListView
         Always give id value as list(@android:id/list)
    --&
    &ListView
        android:id=&@android:id/list&
        android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&/&
&/LinearLayout&list_item.xml
&?xml version=&1.0& encoding=&utf-8&?&
&LinearLayout xmlns:android=&/apk/res/android&
    android:layout_width=&fill_parent&
    android:layout_height=&wrap_content&
    android:orientation=&vertical& &
    &!-- Product id (pid) - will be HIDDEN - used to pass to other activity --&
    &TextView
        android:id=&@+id/pid&
        android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:visibility=&gone& /&
    &!-- Name Label --&
    &TextView
        android:id=&@+id/name&
        android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:paddingTop=&6dip&
        android:paddingLeft=&6dip&
        android:textSize=&17dip&
        android:textStyle=&bold& /&
&/LinearLayout&6. 新建一个名为AllProductActivity.java的类文件。
在下面的代码中,
首先,在后台AsyncTask线程中发送一个请求给get_all_products.php
然后,从get_all_products.php获取JSON格式的数据,我为json转换了格式(parser),并使其显示在ListView中。
如果没有找到产品,会跳转到AddNewProductActivity
AllProductActivity.java
package com.example.
import java.util.ArrayL
import java.util.HashM
import java.util.L
import org.apache.http.NameValueP
import org.json.JSONA
import org.json.JSONE
import org.json.JSONO
import android.app.ListA
import android.app.ProgressD
import android.content.I
import android.os.AsyncT
import android.os.B
import android.util.L
import android.view.V
import android.widget.AdapterV
import android.widget.AdapterView.OnItemClickL
import android.widget.ListA
import android.widget.ListV
import android.widget.SimpleA
import android.widget.TextV
public class AllProductsActivity extends ListActivity {
    // Progress Dialog
    private ProgressDialog pD
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
    ArrayList&HashMap&String, String&& productsL
    // url to get all products list
    private static String url_all_products = &/android_connect/get_all_products.php&;
    // JSON Node names
    private static final String TAG_SUCCESS = &success&;
    private static final String TAG_PRODUCTS = &products&;
    private static final String TAG_PID = &pid&;
    private static final String TAG_NAME = &name&;
    // products JSONArray
    JSONArray products =
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_products);
        // Hashmap for ListView
        productsList = new ArrayList&HashMap&String, String&&();
        // Loading products in Background Thread
        new LoadAllProducts().execute();
        // Get listview
        ListView lv = getListView();
        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView&?& parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                        .toString();
                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        EditProductActivity.class);
                // sending pid to next activity
                in.putExtra(TAG_PID, pid);
                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
            }
        });
    }
    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }
    }
    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask&String, String, String& {
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllProductsActivity.this);
            pDialog.setMessage(&Loading products. Please wait...&);
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List&NameValuePair& params = new ArrayList&NameValuePair&();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, &GET&, params);
            // Check your log cat for JSON reponse
            Log.d(&All Products: &, json.toString());
            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);
                    // looping through All Products
                    for (int i = 0; i & products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);
                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);
                        // creating new HashMap
                        HashMap&String, String& map = new HashMap&String, String&();
                        // adding each child node to HashMap key =& value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);
                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            NewProductActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
           
        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AllProductsActivity.this, productsList,
                            R.layout.list_item, new String[] { TAG_PID,
                                    TAG_NAME},
                            new int[] { R.id.pid, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });
        }
    }
7. 添加一个新产品(写入)
创建一个新的view和activity来向MySQL数据库添加新产品。
新建一个简单的表单,创建提供输入产品名称,价格和描述的EditText
add_product.xml
&?xml version=&1.0& encoding=&utf-8&?&
&LinearLayout xmlns:android=&/apk/res/android&
    android:layout_width=&match_parent&
    android:layout_height=&match_parent&
    android:orientation=&vertical& &
    &!-- Name Label --&
    &TextView android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:text=&Product Name&
        android:paddingLeft=&10dip&
        android:paddingRight=&10dip&
        android:paddingTop=&10dip&
        android:textSize=&17dip&/&
    &!-- Input Name --&
    &EditText android:id=&@+id/inputName&
        android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:layout_margin=&5dip&
        android:layout_marginBottom=&15dip&
        android:singleLine=&true&/&
    &!-- Price Label --&
    &TextView android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:text=&Price&
        android:paddingLeft=&10dip&
        android:paddingRight=&10dip&
        android:paddingTop=&10dip&
        android:textSize=&17dip&/&
    &!-- Input Price --&
    &EditText android:id=&@+id/inputPrice&
        android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:layout_margin=&5dip&
        android:layout_marginBottom=&15dip&
        android:singleLine=&true&
        android:inputType=&numberDecimal&/&
    &!-- Description Label --&
    &TextView android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:text=&Description&
        android:paddingLeft=&10dip&
        android:paddingRight=&10dip&
        android:paddingTop=&10dip&
        android:textSize=&17dip&/&
    &!-- Input description --&
    &EditText android:id=&@+id/inputDesc&
        android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:layout_margin=&5dip&
        android:layout_marginBottom=&15dip&
        android:lines=&4&
        android:gravity=&top&/&
    &!-- Button Create Product --&
    &Button android:id=&@+id/btnCreateProduct&
        android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:text=&Create Product&/&
&/LinearLayout&
8. 新建一个Activity来处理向MySQL数据库插入新产品。
新建名为NewProductActivity.java的文件,输入以下代码。在下面的代码中
首先,从EditText获得用户输入的产品数据,格式化成基本参数格式
然后,向create_product.php发送请求,通过HTTP POST创建一个新的产品
最后,从create_product.php获取json返回值,如果success值为1,新得到的列表中就加入了新增的产品。
NewProductActivity.java
package com.example.
import java.util.ArrayL
import java.util.L
import org.apache.http.NameValueP
import org.apache.http.message.BasicNameValueP
import org.json.JSONE
import org.json.JSONO
import android.app.A
import android.app.ProgressD
import android.content.I
import android.os.AsyncT
import android.os.B
import android.util.L
import android.view.V
import android.widget.B
import android.widget.EditT
public class NewProductActivity extends Activity {
    // Progress Dialog
    private ProgressDialog pD
    JSONParser jsonParser = new JSONParser();
    EditText inputN
    EditText inputP
    EditText inputD
    // url to create new product
    private static String url_create_product = &/android_connect/create_product.php&;
    // JSON Node names
    private static final String TAG_SUCCESS = &success&;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_product);
        // Edit Text
        inputName = (EditText) findViewById(R.id.inputName);
        inputPrice = (EditText) findViewById(R.id.inputPrice);
        inputDesc = (EditText) findViewById(R.id.inputDesc);
        // Create button
        Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
        // button click event
        btnCreateProduct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // creating new product in background thread
                new CreateNewProduct().execute();
            }
        });
    }
    /**
     * Background Async Task to Create new product
     * */
    class CreateNewProduct extends AsyncTask&String, String, String& {
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NewProductActivity.this);
            pDialog.setMessage(&Creating Product..&);
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            String name = inputName.getText().toString();
            String price = inputPrice.getText().toString();
            String description = inputDesc.getText().toString();
            // Building Parameters
            List&NameValuePair& params = new ArrayList&NameValuePair&();
            params.add(new BasicNameValuePair(&name&, name));
            params.add(new BasicNameValuePair(&price&, price));
            params.add(new BasicNameValuePair(&description&, description));
            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    &POST&, params);
            // check log cat fro response
            Log.d(&Create Response&, json.toString());
            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                    startActivity(i);
                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
           
        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }
    }
}9. 读取,更新,删除一项产品
你稍加注意就会发现,在AllProductsActivity.java中,选中列表的某一项,会进入EditProductActivity.java。
接下来新建一个名为edit_product,xml的xml文件,创建类似create_product,xml的表单。
edit_product,xml
&?xml version=&1.0& encoding=&utf-8&?&
&LinearLayout xmlns:android=&/apk/res/android&
    android:layout_width=&match_parent&
    android:layout_height=&match_parent&
    android:orientation=&vertical& &
    &!-- Name Label --&
    &TextView android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:text=&Product Name&
        android:paddingLeft=&10dip&
        android:paddingRight=&10dip&
        android:paddingTop=&10dip&
        android:textSize=&17dip&/&
    &!-- Input Name --&
    &EditText android:id=&@+id/inputName&
        android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:layout_margin=&5dip&
        android:layout_marginBottom=&15dip&
        android:singleLine=&true&/&
    &!-- Price Label --&
    &TextView android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:text=&Price&
        android:paddingLeft=&10dip&
        android:paddingRight=&10dip&
        android:paddingTop=&10dip&
        android:textSize=&17dip&/&
    &!-- Input Price --&
    &EditText android:id=&@+id/inputPrice&
        android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:layout_margin=&5dip&
        android:layout_marginBottom=&15dip&
        android:singleLine=&true&
        android:inputType=&numberDecimal&/&
    &!-- Description Label --&
    &TextView android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:text=&Description&
        android:paddingLeft=&10dip&
        android:paddingRight=&10dip&
        android:paddingTop=&10dip&
        android:textSize=&17dip&/&
    &!-- Input description --&
    &EditText android:id=&@+id/inputDesc&
        android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:layout_margin=&5dip&
        android:layout_marginBottom=&15dip&
        android:lines=&4&
        android:gravity=&top&/&
    &LinearLayout android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:orientation=&horizontal&&
        &!-- Button Create Product --&
    &Button android:id=&@+id/btnSave&
        android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:text=&Save Changes&
        android:layout_weight=&1&/&
    &!-- Button Create Product --&
    &Button android:id=&@+id/btnDelete&
        android:layout_width=&fill_parent&
        android:layout_height=&wrap_content&
        android:text=&Delete&
        android:layout_weight=&1&/&
    &/LinearLayout&
&/LinearLayout&10. 对应edit_product.xml新建EditProductActivity.java,并输入下列代码。
在以下代码中:
首先,从intent中读取发送给ListView的产品id(pid)
然后,向get_product_details.php发送请求,获得json格式的产品详细信息,把它显示在EditText中。
然后,当产品信息显示在表单中后,如果用户点击保存按钮,会向update_product.php发送另一个HTTP请求,更新数据库中的产品信息
如果用户点击删除按钮,将会向delete_product.php发送请求,该产品慧聪MySQL数据库中删除,ListView刷新后显示新的产品列表。
EditProductActivity.java
package com.example.
import java.util.ArrayL
import java.util.L
import org.apache.http.NameValueP
import org.apache.http.message.BasicNameValueP
import org.json.JSONA
import org.json.JSONE
import org.json.JSONO
import android.app.A
import android.app.ProgressD
import android.content.I
import android.os.AsyncT
import android.os.B
import android.util.L
import android.view.V
import android.widget.B
import android.widget.EditT
public class EditProductActivity extends Activity {
    EditText txtN
    EditText txtP
    EditText txtD
    EditText txtCreatedAt;
    Button btnS
    Button btnD
    S
    // Progress Dialog
    private ProgressDialog pD
    // JSON parser class
    JSONParser jsonParser = new JSONParser();
    // single product url
    private static final String url_product_detials = &/android_connect/get_product_details.php&;
    // url to update product
    private static final String url_update_product = &/android_connect/update_product.php&;
    // url to delete product
    private static final String url_delete_product = &/android_connect/delete_product.php&;
    // JSON Node names
    private static final String TAG_SUCCESS = &success&;
    private static final String TAG_PRODUCT = &product&;
    private static final String TAG_PID = &pid&;
    private static final String TAG_NAME = &name&;
    private static final String TAG_PRICE = &price&;
    private static final String TAG_DESCRIPTION = &description&;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_product);
        // save button
        btnSave = (Button) findViewById(R.id.btnSave);
        btnDelete = (Button) findViewById(R.id.btnDelete);
        // getting product details from intent
        Intent i = getIntent();
        // getting product id (pid) from intent
        pid = i.getStringExtra(TAG_PID);
        // Getting complete product details in background thread
        new GetProductDetails().execute();
        // save button click event
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // starting background task to update product
                new SaveProductDetails().execute();
            }
        });
        // Delete button click event
        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // deleting product in background thread
                new DeleteProduct().execute();
            }
        });
    }
    /**
     * Background Async Task to Get complete product details
     * */
    class GetProductDetails extends AsyncTask&String, String, String& {
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditProductActivity.this);
            pDialog.setMessage(&Loading}

我要回帖

更多关于 php7怎么连接mysql 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信