资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

php创建数据库连接脚本,php怎么和mysql数据库连接

如何连接android和php mysql数据库

使用JSON连接Android和PHP Mysql数据库方法:

我们提供的服务有:成都网站设计、成都做网站、微信公众号开发、网站优化、网站认证、洪洞ssl等。为上千家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的洪洞网站制作公司

1、打开安装WAMP Server的文件夹,打开www文件夹,为你的项目创建一个新的文件夹。必须把项目中所有的文件放到这个文件夹中。

2、新建一个名为android_connect的文件夹,并新建一个php文件,命名为test.php,尝试输入一些简单的php代码(如下所示)。

test.php

?php

echo"Welcome, I am connecting Android to PHP, 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"

}

如何实现PHP自动创建数据库

你做好程序以后,把数据库导出成sql文件

1、连接数据库

2、读取这个sql文件里的sql语句,并执行

3、生成一个数据库连接参数的php文件

?php

$con = mysql_connect("localhost","peter","abc123");

if (!$con)

{

die('Could not connect: ' . mysql_error());

}

if (mysql_query("CREATE DATABASE my_db",$con))

{

echo "Database created";

}

else

{

echo "Error creating database: " . mysql_error();

}

mysql_close($con);

?

?php

class ReadSql {

//数据库连接

protected $connect = null;

//数据库对象

protected $db = null;

//sql文件

public $sqlFile = "";

//sql语句集

public $sqlArr = array();

public function __construct($host, $user, $pw, $db_name) {

$host = empty($host) ? C("DB_HOST") : $host;

$user = empty($user) ? C("DB_USER") : $user;

$pw = empty($pw) ? C("DB_PWD") : $pw;

$db_name = empty($db_name) ? C("DB_NAME") : $db_name;

//连接数据库

$this-connect = mysql_connect($host, $user, $pw) or die("Could not connect: " . mysql_error());

$this-db = mysql_select_db($db_name, $this-connect) or die("Yon can not select the table:" . mysql_error());

}

//导入sql文件

public function Import($url) {

$this-sqlFile = file_get_contents($url);

if (!$this-sqlFile) {

exit("打开文件错误");

} else {

$this-GetSqlArr();

if ($this-Runsql()) {

return true;

}

}

}

//获取sql语句数组

public function GetSqlArr() {

//去除注释

$str = $this-sqlFile;

$str = preg_replace('/--.*/i', '', $str);

$str = preg_replace('/\/\*.*\*\/(\;)?/i', '', $str);

//去除空格 创建数组

$str = explode(";\n", $str);

foreach ($str as $v) {

$v = trim($v);

if (empty($v)) {

continue;

} else {

$this-sqlArr[] = $v;

}

}

}

//执行sql文件

public function RunSql() {

foreach ($this-sqlArr as $k = $v) {

if (!mysql_query($v)) {

exit("sql语句错误:第" . $k . "行" . mysql_error());

}

}

return true;

}

}

//范例:

header("Content-type:text/html;charset=utf-8");

$sql = new ReadSql("localhost", "root", "", "log_db");

$rst = $sql-Import("./log_db.sql");

if ($rst) {

echo "Success!";

}

?

php登录页面完整代码连接数据库

创建conn.php,连接数据库。

$dns = 'mysql:host=127.0.0.1;dbname=test';

$username = 'root';

$password = 'root';

// 1.连接数据库,创建PDO对象

$pdo = new PDO($dns,$username,$password);

创建login.html,登陆页面。

用户名

密 码

创建login.php,验证账号密码。

header("Content-Type: text/html; charset=utf8");

if(!isset($_POST["submit"])){

exit("错误执行");

}//检测是否有submit操作

include('conn.php');//链接数据库

$name = $_POST['name'];//post获得用户名表单值

$pwd = sha1($_POST['password']);//post获得用户密码单值

if ($name $pwd){//如果用户名和密码都不为空

$sql = "select * from user where username = '$name' and password='$pwd'";//检测数据库是否有对应的username和password的sql

$stmt = $pdo-prepare($sql);

$stmt-execute();

if($stmt-fetch(PDO::FETCH_BOUND)){//0 false 1 true

header("refresh:0;url=welcome.html");//如果成功跳转至welcome.html页面

exit;

}else{

echo "用户名或密码错误";

echo "

setTimeout(function(){window.location.href='login.html';},1000);

";//如果错误使用js 1秒后跳转到登录页面重试;

}

}else{//如果用户名或密码有空

echo "表单填写不完整";

echo "

setTimeout(function(){window.location.href='login.html';},1000);

";

//如果错误使用js 1秒后跳转到登录页面重试;

}

$pdo = null;

创建signup.html,注册页面

用户名:

密 码:

创建signup.php

header("Content-Type: text/html; charset=utf8");

if(!isset($_POST['submit'])){

exit("错误执行");

}//判断是否有submit操作

$name=$_POST['name'];//post获取表单里的name

$pwd = sha1($_POST['password']);//post获取表单里的password

include('conn.php');//链接数据库

$sql="insert into user(id,username,password) values (null,'$name','$pwd')";//向数据库插入表单传来的值的sql

$stmt = $pdo-prepare($sql);

$stmt-execute();

$stmt-fetch(PDO::FETCH_BOUND);

if (!$stmt){

die('Error: ' . $stmt-getMessage());//如果sql执行失败输出错误

}else{

echo "注册成功";//成功输出注册成功

}

$pdo = null;//关闭数据库


本文标题:php创建数据库连接脚本,php怎么和mysql数据库连接
文章起源:http://cdkjz.cn/article/dseodgo.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220