PHP mysqli学习(七)面向过程方式

废话不说,上代码!

<?php
// mysqli 面向过程方式

// step1 连接数据库
$link = mysqli_connect('localhost:3306', 'root', 'root', 'zhy') or die('mysqli connect error ' . mysqli_connect_errno() . ':' . mysqli_connect_error());

// step2 设置字符集
mysqli_set_charset($link, 'utf8');

// step3 执行sql
$sql = 'INSERT INTO user (name, age, description) VALUES ("周芷若", "20", "为情所困的女子!");';
if($res = mysqli_query($link, $sql)){
    echo 'INSERT_ID : '.mysqli_insert_id($link);
    echo '<br/>';
    echo 'AFFECT_ROWS : '.mysqli_affected_rows($link);
}else{
    echo 'insert error '.mysqli_error($link).':'.mysqli_errno($link);
}
echo '<hr color="red"/>';
$sql = 'UPDATE user SET age = age + 10 WHERE name="周芷若";';
$sql .= 'DELETE FROM user WHERE id = "20";';

$res = mysqli_multi_query($link, $sql);
var_dump($res);

// step4 关闭连接
mysqli_close($link);
<?php
$link = mysqli_connect('localhost:3306', 'root', 'root', 'zhy') or die('mysqli connect error ' . mysqli_connect_errno() . ':' . mysqli_connect_error());
mysqli_set_charset($link, 'utf8');

$sql = "INSERT INTO user (name, age, description) VALUES(?,?,?);";
$stmt = mysqli_prepare($link, $sql);
$name = '小龙女';
$age = 18;
$description = '人间仙子小龙女';
mysqli_stmt_bind_param($stmt, 'sis', $name, $age, $description);
$res = mysqli_stmt_execute($stmt);

var_dump($res);
mysqli_close($link);
<?php
header('content-type:text/html;charset=utf-8');
$link = mysqli_connect('localhost:3306', 'root', 'root', 'zhy') or die('mysqli connect error ' . mysqli_connect_errno() . ':' . mysqli_connect_error());
mysqli_set_charset($link, 'utf8');

$sql = 'SELECT name, age, description FROM user';
$res = mysqli_query($link, $sql);
if($res && mysqli_num_rows($res) > 0){
    while($rows = mysqli_fetch_assoc($res)){
        $users[] = $rows;
    }
}

var_dump($users);

foreach ($users as $user) {
    if(!empty($user)){
        echo 'name : '.$user['name'].'<br/>';
        echo 'age : '.$user['age'].'<br/>';
        echo 'description : '.$user['description'].'<hr/>';
    }
}

mysqli_free_result($res);
mysqli_close($link);
CREATE TABLE `user` (
  `id` int(255) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(255) DEFAULT NULL,
  `age` int(10) DEFAULT NULL,
  `description` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;

 

posted @ 2016-05-10 09:40  皎如飞镜临丹阙  阅读(402)  评论(0编辑  收藏  举报