原⽣PHP连接数据库的四种⽅式第1种连接⽅式 mysql_connect  (php版本需⼩于5.5)
mysql_connect连接数据库php版本需⼩于5.5
$con = mysql_connect("localhost","root","root");
if($con){
// 选择表
mysql_select_db('bysj',$con);
//执⾏SQL语句
$sql = "select * from user";
$result =mysql_query($sql);
//输出数据
while($row = mysql_fetch_row($result)){
foreach($row as $k => $v){
echo "\n".$v;
}
echo "<br>".$v;
}
}else{
die("⽆法连接数据库".mysql_error());
}
关键函数:
mysql_connect()连接数据库
mysql_select_db()选择数据库
mysql_query()执⾏sql语句
mysql_fetch_row()从结果集中取得⼀⾏作为数字数组。
mysql_error()数据库连接错误显⽰信息
第2种连接⽅式⾯向对象mysqli
$con =  new MySQLi("localhost","root","root","bysj");
if($con->connect_error){
die("连接数据库失败!".$con->connect_error);
}
echo "连接数据库成功!";
$sql = "select * from user";
$result = $con->query($sql);
foreach($result as $k => $v){
echo "<br>".$v['id']."\n".$v['name'];
}
关键字:
$con = new MySQLi连接数据库 (四个参数)
$con->query()执⾏sql语句
第3种连接⽅式⾯向过程mysqli_connect
mysql下载链接
$con3 = mysqli_connect("localhost","root","root","bysj");
if(!$con){
die( "连接数据库失败!".mysqli_connect_error);
}
echo "连接数据库成功!";
$sql3 = "select * from user";
$result3 = mysqli_query($con3,$sql3);
foreach($result3 as $k => $v){
echo "<br>".$v['id']."-->".$v['name'];
}
关键字:
mysqli_connect连接数据库 (四个参数)
mysqli_query执⾏sql语句 (两个参数)
第4种连接⽅式 PDO
$con = new PDO("mysql:host=localhost;dbname=bysj;","root","root");
try{
echo "连接数据库成功!";
$sql = "select * from user";
$result = $con->query($sql);
foreach($result as $k => $v  ){
echo "<br>".$v['id']."-->".$v['name'];
}
}catch(PDOException $e){
echo $e->getMessage();
}
$con = new PDO("mysql:host=localhost;dbname=bysj;","root","root");连接数据库 (四个参数)$con->query()执⾏sql语句

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。