PHP访问数据库
1.原生mysql方式
<?php //最原生态的访问方式,不过SQL注入是个麻烦事 $con = mysql_connect("localhost","root","sa123456"); if($con) { mysql_select_db("dedecms"); mysql_query("set names gbk");//设置数据访问编码,防止乱码 $rs = mysql_query("select * from dede_area",$con); #var_dump(mysql_fetch_array($rs)); //同时提供数字索引与文本索引两种访问方式 /*while($row = mysql_fetch_row($rs)) { var_dump($row); }*/ #var_dump( mysql_fetch_($rs) ); #mysql_fetch_assoc($result) while($row = mysql_fetch_assoc($rs))//只提供文本索引访问数据 { #var_dump($row); echo $row['name']."<br/>"; } } mysql_close($con); ?>
2.优化过的mysql数据库访问方式,mysqli
<?php //mysqli的访问方式,更加OO且安全性和性能都有提升,参数的方式可防止SQL注入 $mysqli = new mysqli("localhost","root","sa123456","phpdb"); $mysqli->query("set names gbk"); $sql = "insert into article(title,content,createBy,createTime) values(?,?,?,?)"; $stmt = $mysqli->prepare($sql); $stmt->bind_param("ssss", $title,$content,$createBy,$createTime); $title = "hello!!!"; $content = "这里是新闻的内容"; $createBy = "admin"; $createTime = date('Y-m-d H:i:s'); $stmt->execute(); $stmt->close(); $mysqli->close(); ?>
3.通用数据库访问方式,pdo
<?php try { //pdo方式访问数据库,数据访问方式抽象到了更高层次,可支持灵活的切换为不同类型数据库 $dsn = "mysql:host=localhost;dbname=dedecms"; $pdo = new PDO($dsn, "root", "sa123456"); } catch (PDOException $e) { echo "Failed to get DB handle: " . $e->getMessage() . "\n"; exit; } $pdo->query("set names gbk"); $query = $pdo->prepare("select * FROM dede_area"); $query->execute(); for($i=0; $row = $query->fetch(); $i++){ echo $i." - ".$row['name']."<br/>"; } ?>