PHP MySQL reads data
PHP MySQL Read data
Read data from MySQL database
The SELECT statement is used to read data from the data table:
SELECT column_name(s) FROM table_name
To learn more about SQL, please visit our SQL tutorial.
In the following example, we read the data of the id, firstname and lastname columns from the table MyGuests and display it on the page:
Example (MySQLi - Object-oriented)
connect_error) { die("连接失败: " . $conn->connect_error); } $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 输出每行数据 while($row = $result->fetch_assoc()) { echo "
id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"]; } } else { echo "0 个结果"; } $conn->close(); ?>
The following example reads all records of the MyGuests table and displays them in an HTML table:
Example (PDO)
"; echo ""; class TableRows extends RecursiveIteratorIterator { function __construct($it) { parent::__construct($it, self::LEAVES_ONLY); } function current() { return " Id Firstname Lastname Reg date " . parent::current(). " "; } function beginChildren() { echo ""; } function endChildren() { echo " " . "\n"; } } $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare("SELECT * FROM MyGuests"); $stmt->execute(); // 设置结果集为关联数组 $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { echo $v; } $dsn = null; } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } $conn = null; echo ""; ?>