怎么连接安卓的mysql 安卓直连mysql( 三 )


?
3、创建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
);
4、用PHP连接MySQL数据库
现在,真正的服务器端编程开始了 。新建一个PHP类来连接MYSQL数据库 。这个类的主要功能是打开数据库连接和在不需要时关闭数据库连接 。
新建两个文件db_config.php,db_connect.php
db_config.php--------存储数据库连接变量
db_connect.php-------连接数据库的类文件
db_config.php
?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
?
5、在PHP项目中新建一个php文件,命名为create_product.php,并输入以下代码 。该文件主要实现在products表中插入一个新的产品 。
?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);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?
JSON的返回值会是:
当POST 参数丢失
[php] view plaincopy
{
"success": 0,
"message": "Required field(s) is missing"
}
关于怎么连接安卓的mysql和安卓直连mysql的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

推荐阅读