Blogger Information
Blog 13
fans 0
comment 0
visits 6980
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
使用SQL儲存數據(2019年7月25日)
Little的博客
Original
592 people have browsed it

把原來存到php array中的數據改為database存放.

1.$sql = 'sql語句'; //設置sql語句

2. $preobj = $pdo->prepare($sql)  // 建立預處理對象

3.$preobj->execute(); //執行

4. $arr = $preobj->fetch/fetchAll(PDO::FETCH_ASSOC) //把數據存放到數組中

**個人理解: fetch->用於單維數組, fetchAll->用於多維數組 , fetchAll + SQL語句中使用LIMIT 可做到fetch效果

0725.jpg


主要部份修改在header,所以只貼header部份的代碼。

实例

<?php

//connect to database first
require __DIR__ . '/../db/connect.php';

//get foods data from database
$sql = 'SELECT * FROM `foods`';
//prepare
$preObj = $pdo->prepare( $sql );
//execute
$preObj->execute();
//input to array
$foods = $preObj->fetchAll( PDO::FETCH_ASSOC );

//get category data from database
$sql    = 'SELECT * FROM `category`';
$preObj = $pdo->prepare( $sql );
$preObj->execute();
$cates = $preObj->fetchAll( PDO::FETCH_ASSOC );
//count array length
$cate_count = count( $cates );

$sql    = 'SELECT *  FROM `system` LIMIT 1';
$preObj = $pdo->prepare( $sql );
$preObj->execute();
$system = $preObj->fetch( PDO::FETCH_ASSOC );

//fetchAll ->using in 多維數組, fetch->using in 1維數組
//fetch + LIMIT = fetch
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="../css/style.css">
    <meta name="description" content="<?php echo $system['desc'] ?>">
    <meta name="keywords" content="<?php echo $system['key'] ?>">
    <title><?php echo $system['title'] ?></title>
</head>
<body>

<div class="header">
    <ul class="nav">
        <li><a href="index.php">HomePage</a></li>
		<?php foreach ( $cates as $cate ) : ?>
            <li><a href="list.php?cat_id=<?php echo $cate['cat_id']; ?>"><?php echo $cate['alias'] ?></a></li>
		<?php endforeach; ?>
    </ul>
</div>

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:fetchAll()就算取一条, 那也是二维数组, 与fetch()不同
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post