在这里,我们在数据库(myDB)中创建了一个具有以下值的“student”表:
CREATE TABLE students ( id INT(4) UNSIGNED auto_increment PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, class INT(2) );
INSERT INTO students (firstname, lastname, class) VALUES -> ('sathish','kumar',12), -> ('rakesh','singh',8), -> ('sonam','gupta',11), -> ('dilbar','pathak',6), -> ('salim','khan',7), -> ('kabir','singh',6), -> ('arjun','reddy',6);
这里是数据库表(学生表)中的数据,
我们使用PHP PDO(PHP数据对象)与MySQL进行接口
<?php echo "<table style='border: solid 1px black;'>"; echo "<tr><th>id</th><th>Firstname</th><th>Lastname</th><th>class</th></tr>"; class TableRows extends RecursiveIteratorIterator { function __construct($it) { parent::__construct($it, self::LEAVES_ONLY); } function current() { return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>"; } function beginChildren() { echo "<tr>"; } function endChildren() { echo "</tr>" . "\n"; } } //定义数据库变量 $host = "localhost"; $user = "mydbuser"; $password = "mydbpassword"; $db = "myDB"; //尝试声明 try { //创建新的PDO连接 $conn = new PDO("mysql:host=$host;dbname=$db", $user, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // mysql从表中选择* $stmt = $conn->prepare("SELECT * FROM students"); $stmt->execute(); //设置结果数组 $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { echo $v; } } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } $conn = null; echo "</table>"; ?>
要了解有关PDO的更多信息,请阅读PHP手册:PHP数据对象(PDO)