mysql 简单语句之PHP操作数据库

数据库提前加几条数据

新增一条数据

<meta charset="utf-8">
<?php
// 链接数据库:需要链接的服务器,用户名和密码
mysql_connect("localhost", "root", 123456);
// 选择哪个数据库
mysql_selectdb("xiaobai");
// 设置字符集
mysql_query("SET NAMES UTF8");
// 向对应的数据库插入数据
$sql = "INSERT INTO form VALUES('小李',17,'男',1358995225,'[email protected]',88,'河北石家庄')";
//查询数据库中的数据
//$sql = "SELECT * FROM form";
//执行命令
mysql_query($sql);
?>

此时每一次请求页面的时候都会向数据库增加一条数据 

mysql_query() 函数执行一条 MySQL 查询

流程图

查询数据库中的数据

<meta charset="utf-8">
<?php
// 链接数据库:需要链接的服务器,用户名和密码
mysql_connect("localhost", "root", 123456);
// 选择哪个数据库
mysql_selectdb("xiaobai");
// 设置字符集
mysql_query("SET NAMES UTF8");
// 向对应的数据库插入数据
//$sql = "INSERT INTO form VALUES('小李',17,'男',1358995225,'[email protected]',88,'河北石家庄')";
//查询数据库中的数据
$sql = "SELECT * FROM form";
//执行命令
$result = mysql_query($sql);

echo $result;
print_r($result);
?>

此时输出这个$result是报错的,因为echo和print_r输出的是基本类型的值和数组,而$result的返回结果不是基本类型值,也不是数组

所以要将结果转换为数组

mysql_fetch_array() 函数从结果集中取得一行作为关联数组,或数字数组,或二者兼有

$arr = mysql_fetch_array($result);
print_r($arr);
echo "<br/>";

想要打印所有的数组内容,但是返回的却是一条数据,反复执行上面的命令后发现

执行一次打印一条,这样肯定不合理,办法就是使用 while循环来遍历所有的数据

while($arr = mysql_fetch_array($result)) {
    print_r($arr);
    echo "<br/>";
}

数据渲染到表格中  

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    table,
    td,
    th {
        border-collapse: collapse;
        line-height: 30px;
        border: 1px solid #333;
        padding: 0 20px;
    }
</style>

<body>
    <?php
    // 链接数据库:需要链接的服务器,用户名和密码
    mysql_connect("localhost", "root", 123456);
    //选择哪个数据库
    mysql_selectdb("xiaobai");
    // 设置字符集
    mysql_query("SET NAMES UTF8");
    // 向对应的数据库插入数据
    $sql = "SELECT * FROM form";
    $result = mysql_query($sql);
    ?>
    <table>
        <tr>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>电话</th>
            <th>邮箱</th>
            <th>成绩</th>
            <th>地址</th>
        </tr>
        <?php
        while ($arr = mysql_fetch_array($result)) { ?>
            <tr>
                <td><?php print_r($arr['name']) ?></td>
                <td><?php print_r($arr['age']) ?></td>
                <td><?php print_r($arr['sex']) ?></td>
                <td><?php print_r($arr['tel']) ?></td>
                <td><?php print_r($arr['email']) ?></td>
                <td><?php print_r($arr['score']) ?></td>
                <td><?php print_r($arr['adress']) ?></td>
            </tr>
        <?php } ?>
    </table>
</body>

</html>

返回查出来的结果数量

$num = mysql_num_rows($result);

 

 

 

猜你喜欢

转载自blog.csdn.net/weixin_41040445/article/details/114824979