标签:
使用PHP操作数据库有两种方式
下面演示使用第一种方式:
<!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <?php $conn = mysql_connect("localhost", "root", "zxbbugu"); if(!$conn) { die("Could not connect:" . mysql_error()); } mysql_select_db("test", $conn); //mysql_query("SET NAMES utf8"); $result = mysql_query("INSERT INTO mytable(headline, create_time) VALUES(‘中国‘, ‘" . date("Y-m-d h:i:s") . "‘);"); if( $result < 1) { echo "insert error!"; } $query = mysql_query("SELECT * FROM mytable LIMIT 100 OFFSET 0;"); while ($row = mysql_fetch_array($query, MYSQL_BOTH)) { echo "<p>", $row["id"], " - " , $row["headline"], " - ", $row["create_time"], "</p>"; } mysql_close(); ?> </body> </html>
下面是使用PDO方式:
<!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <?php $pdo = new PDO("mysql:host=localhost;dbname=test", "root", "zxbbugu"); $stmt = $pdo->prepare(‘SELECT * FROM mytable WHERE id = :id‘); $stmt->execute(array(":id"=>1)); foreach ($stmt as $row) { echo $row["headline"]; } $result = $pdo->exec("INSERT INTO mytable(headline, create_time) VALUES(‘中国‘, ‘" . date("Y-m-d h:i:s") . "‘);"); if($result) { $str = sprintf("add data completed, lastupdateid=%s", $pdo->lastInsertId()); echo $str; } $rs = $pdo->query("SELECT * FROM mytable"); while ($row = $rs->fetch()) { echo "<p>", $row["id"], " - " , $row["headline"], " - ", $row["create_time"], "</p>"; } ?> </body> </html>
建议使用PDO方式,这样可以减少SQL注入安全性问题。(php5以上建议使用PDO方式做数据库操作)
标签:
原文地址:http://www.cnblogs.com/HD/p/4519890.html