php 数据访问(以mysql数据库为例)

时间:2021-03-27 20:53:54

//建一个连接,造一个连接对象
$db = new MySQLi("localhost","root","123","mydb");

//判断是否出错
/*if(mysqli_connect_error())
{
 echo "连接失败!";
 exit;
}*/

mysqli_connect_error()?die("连接失败"):"";

//写SQL语句
$sql = "select * from Info";

//执行SQL语句,返回结果集对象
$reslut = $db->query($sql);

//从结果集中读取数据,返回数组
//$attr = $reslut->fetch_all(); //读取所有数据,返回索引二维数组

//$attr = $reslut->fetch_array(); //读取当前指针指向的数据,返回索引关联都存在的数组

//$attr = $reslut->fetch_assoc(); //返回关联数组

//$attr = $reslut->fetch_row(); //返回索引数组

//$attr = $reslut->fetch_object(); //返回对象
/*$arr = array();
while($attr = $reslut->fetch_row())
{
 array_push($arr,$attr);
}

var_dump($arr);*/

//造连接对象
$db = new MySQLi("localhost","root","123","mydb");

//写SQL语句
$sql = "insert into info values('p003','张三','1','n001','1990-2-3')";

//执行SQL语句
$result = $db->query($sql);

/*if($result)
{
 echo "执行成功!";
}
else
{
 echo "执行失败!";
}*/

//$result->fetch_row();

谨防mysql注入攻击