1.使用內(nèi)置對(duì)象創(chuàng)建數(shù)據(jù)庫
$mysqli = mysqli_init();
if (!$mysqli) {
die('mysqli_init failed');
}
2.連接數(shù)據(jù)庫
if (!$mysqli->real_connect('localhost', 'root', '', 'test')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
3.設(shè)置字符集
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語句使用(增薯鼠,刪郎任,改,查)
//創(chuàng)建
$q = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
//插入
//$q = "INSERT INTO name1 (name, age) VALUES ('黃鵬','4')";
//查詢數(shù)據(jù)
// $q = "SELECT * FROM user";
// 更新
//$q="UPDATE user SET name = '還耕' WHERE age = '13'";
//刪除
$q="DELETE FROM user WHERE age='4'";
注意: 在寫數(shù)據(jù)庫語句是枉长,防止引號(hào)和其他有問題的字符破壞SQL命令的語法。我們需要
//將變量進(jìn)行轉(zhuǎn)義琼讽;
$var = $mysqli->real_escape_string($var);
5.查詢
$result = $mysqli->query($q);
6.返回結(jié)果集
if ($result = $mysqli->query($q)) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[1]);
}
/* free result set 關(guān)閉結(jié)果集*/
$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 關(guān)閉結(jié)果集*/
$result->close();
}
7.關(guān)閉數(shù)據(jù)庫
$mysqli->close();
8.前臺(tái)發(fā)到后臺(tái)數(shù)據(jù)也是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");
});