两种数据库连接方式对比
语法1:$result = $conn1->query("select * from 数据表名.")方式
conn1.php文件
<?php
header('content-type:text/html;charset=utf-8');
define('HOST','localhost');
define('USERNAME','root');
define('PASSWORD','自己的数据库密码');
define('DBNAME','自己的数据库名');
$conn1=@new mysqli(HOST,USERNAME,PASSWORD,DBNAME);
if($conn->connect_error){
die('数据库连接失败'.$conn->connect_error);
}
$conn1->query('SET NAMES UTF8');
$result=$conn1->query("select * from 数据表名");//注意这一点决定了其他引入此文件的语法
$arr=array();
for($i=0;$i<$result->num_rows;$i++){
$arr[$i]=$result->fetch_assoc();
}
?>
login.php文件
include "conn1.php";
$username=$_POST['username'];
$pass=sha1($_POST['pass']);
$result=$conn1->query("select * from database where username='$username' and pass='$pass'");
// $result=mysqli_fquery( $conn1,"select * from database where username='$username' and pass='$pass'");//另外一种连接方式语法,之前
// $result = $conn1->query("select * from where username ........."),此连接方式的语法,一定要和conn1的语法保持一致,之前没有搞清这一点,一直报错
$arr=array();
for($i=0;$i<$result->num_rows;$i++){
$arr[$i]=$result->fetch_assoc();
}
echo json_encode($arr);
regis.php
include "conn1.php";
echo($_POST['submit']);
if(isset($_POST['username']) && isset($_POST['pass'])){
$username=$_POST['username'];
$pass=sha1($_POST['pass']);
$sqli="INSERT INTO `database`(`username`, `pass`) VALUES ('$username','$pass')";
$res = mysqli_query($conn1,$sqli);
echo true;
}else{
exit('非法操作');
}
语法二:$result=mysqli_query($conn,'select * from 数据表名 ')方式
conn.php文件
$sever='localhost:3306';
$name='root';
$password='数据库密码';
$dbase='数据库名';
$conn=mysqli_connect($sever,$name,$password,$dbase);
mysqli_set_charset($conn,'UTF-8');
shopcar.php文件
include "conn.php";
$result=mysqli_query($conn,'select * from 数据表名');
$list=array();
for($i=0; $i <mysqli_num_rows($result);$i++){
$list[$i]=mysqli_fetch_array($result,MYSQLI_ASSOC);
}
echo json_encode($list);
details.php文件
include "conn.php";
$id=$_GET['sid'];
$result=mysqli_query($conn,"select * from 数据表名 where sid=$id");//
$list=mysqli_fetch_array($result,MYSQLI_ASSOC);
echo json_encode($list);