使用PHP操作数据库有两种方式
- 使用mysql_XXXX()方法
- 使用这种方式,需要先把php.ini里的extension=php_mysql.dll去掉注释
- 使用PDO
- 使用这种试,需要把php.ini里的extension=php_pdo_mysql.dll去掉注释
下面演示使用第一种方式:
<!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方式做数据库操作)
时间: 2024-09-27 19:25:18