<?php
/*
* 建立資料庫
* CREATE DATABASE `kiang_cycu` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
*
* 建立資料表
 
CREATE TABLE IF NOT EXISTS `messages` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`poster` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`title` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL,
`body` text COLLATE utf8_unicode_ci NOT NULL,
`time` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
 
*/
 
/*
* 資料庫連線
*/
$dbn = new mysqli(
'localhost', //主機位置
'root', //帳號
'123', //密碼
'guestbook' //資料庫名稱
);
$dbn->set_charset('utf8');//設定資料庫連線編碼 中文可以完整顯示
//物件裡面的函式->方法(set_charset)
 
/*
* 新增資料
*/
                //從資料庫查詢有多少數量     [!!!]判斷資料庫裡驗有沒有資料 如果"沒有"
if($dbn->query('SELECT COUNT(*) AS count FROM messages') ->fetch_object()->count == 0) {//資料表
$now = mktime();
for($i = 1; $i <= 20; $i++) {//[!!!]沒有資料的話 就塞20筆進去
//prepare 資料庫從使用者過來 先設定統一為字串格式
$stmt = $dbn->prepare('INSERT INTO messages VALUES (NULL, ?, ?, ?, ?)');
$poster = 'poster' . $i;
$title = 'title' . $i;
$body = 'body' . $i;
$date = date('Y-m-d H:i:s', ++$now);
//ssss 代表????都為字串格式 (不管是數字或是字串 都把他存成字串格式)
$stmt->bind_param('ssss', $poster, $title, $body, $date);
$stmt->execute();
$stmt->close();
}
}
 
/*
* 取得資料
*/
$result = $dbn->query('SELECT * FROM messages');//取所有資料
while($data = $result->fetch_object()) {
echo '<pre>';                              
print_r($data);//印出資料庫所有資料
echo '</pre>';
}

------------------------------------------------------------------------------------------

/* 取得資料 */
$result = $dbn->query('SELECT id FROM manager');//取所有資料
while($data = $result->fetch_object()) {
echo '<pre>';                             
print_r($data->id);//印出資料庫所有資料
echo '</pre>';
}

arrow
arrow
    全站熱搜

    cabuchi 發表在 痞客邦 留言(0) 人氣()