pdo mariadb_使用PDO函数从MySQL(MariaDB)数据库获取数据PHP示例

pdo mariadb

Here, we have created a "students" table in the database (myDB) with the following values:

在这里,我们在数据库(myDB)中创建了一个具有以下值的“学生”表:

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);

Here, is the data in the database table (students tables),

这里是数据库表(学生表)中的数据,

fetch data from MySQL (MariaDB) database using PDO function

We use PHP PDO (PHP Data Objects) to interface with MySQL

我们使用PHP PDO(PHP数据对象)与MySQL进行接口

PHP代码从数据库中获取数据 (PHP code to fetch data from database)

<?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";
    }
}


//Define Database variables
$host = "localhost";
$user = "mydbuser";
$password = "mydbpassword";
$db = "myDB";


//Try Statement
try {
//Creating a New PDO Connection
    $conn = new PDO("mysql:host=$host;dbname=$db", $user, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//mysql Select * from table
    $stmt = $conn->prepare("SELECT * FROM students");
    $stmt->execute();

// set the resulting array
    $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>";
?> 

To learn more about the PDO, please read PHP manual: PHP Data Objects (PDO)

要了解有关PDO的更多信息,请阅读PHP手册: PHP数据对象(PDO)

翻译自: https://www.includehelp.com/php/fetch-data-from-mysql-mariadb-database-using-pdo-function.aspx

pdo mariadb

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值