1.使用内置对象创建数据库
$mysqli = mysqli_init();
if (!$mysqli) {
die('mysqli_init failed');
}
2.连接数据库
if (!$mysqli->real_connect('localhost', 'root', '', 'test')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
3.设置字符集
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
} else {
printf("Current character set: %s\n", $mysqli->character_set_name());
}
4.sql语句使用(增,删,改,查)
//创建
$q = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
//插入
//$q = "INSERT INTO name1 (name, age) VALUES ('黄鹏','4')";
//查询数据
// $q = "SELECT * FROM user";
// 更新
//$q="UPDATE user SET name = '还耕' WHERE age = '13'";
//删除
$q="DELETE FROM user WHERE age='4'";
注意: 在写数据库语句是,防止引号和其他有问题的字符破坏SQL命令的语法。我们需要
//将变量进行转义;
$var = $mysqli->real_escape_string($var);
5.查询
$result = $mysqli->query($q);
6.返回结果集
if ($result = $mysqli->query($q)) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[1]);
}
/* free result set 关闭结果集*/
$result->close();
}
//如果想直接返回json
$i=0;
if ($result = $mysqli->query($sql)) {
while ($row = $result->fetch_object()) {
$param[$i++]=$row;
}
echo json_encode($param);
/* free result set 关闭结果集*/
$result->close();
}
7.关闭数据库
$mysqli->close();
8.前台发到后台数据也是json的方法##
$.ajax({
url:url,
data:JSON.stringify(data),
type:'post',
dataType:'json',
headers:{
Accept:"application/json",
"Content-Type":"application/json"
}
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});