1, database design
create table book(
id int(4) not null primary key auto_increment,
name varchar(255) not null,
author varchar(255) not null)
CHARSET=utf8;
2, insert test data
##insert into book values(1,'php basic tutorial','smile1'),(2,'php intermediate tutorial','smile2'),(3,'php advanced tutorial','smile3');Database display:
##3. Set the database connection variables
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/3/5 0005 * Time: 上午 9:23 */ header("content-type:text/html;charset=utf-8"); //mysql:host:localhost;port=3306;dbname=php;charset=utf-8 $dbms='mysql'; $host='localhost'; $port='3306'; $dbname='php'; $charset='utf-8'; //用户名与密码 $user='root'; $pwd='root'; $dsn="$dbms:host=$host;port=$port;dbname=$dbname;charset=$charset";
4, PDO connects to the database
<?php try{ $pdo=new PDO($dsn,$user,$pwd); }catch (PDOException $exception){ echo $exception->getMessage().'<br>'; }
5, executes the sql statement and prints
$sql='select *from book'; $result=$pdo->query($sql); $row=$result->fetchAll(); echo "<pre>"; print_r($row); echo "</pre>";Print result display:
In actual operation, sometimes you only need to get the index array. In this case, you only need to change the fetchAll() function. The parameters can be
## Code:
<?php $row=$result->fetchAll(PDO::FETCH_ASSOC); //获取索引数组The print result is as follows:
If you want to get the value of the second column of the database, the code is as follows:
<?php $row=$result->fetchAll(PDO::FETCH_COLUMN,1);//获取第二列的所有值Print As follows:
Next Section