PHP学习(1)--数据库的连接

来源:互联网 发布:lol韩服网络错误 编辑:程序博客网 时间:2024/06/13 11:23

首先介绍一个很好的学习PHP的网站(菜鸟教程)

数据库连接PHP源代码:

        <!DOCTYPE html>            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />        <html>            <body>                <h1>我的第一张 PHP 页面</h1>                <?php                $con = mysqli_connect("localhost","root","","taoeytest");                if ($con)                {                    echo "连接成功</br>";                }                $result = mysqli_query($con,"SELECT * FROM student");                // some code                echo "<table border='5'>                <tr>                <th>id</th>                <th>age</th>                <th>name</th>                </tr>";                while($row = mysqli_fetch_array($result))                {                    echo "<tr>";                    echo "<td>" . $row['id'] . "</td>";                    echo "<td>" . $row['age'] . "</td>";                    echo "<td>" . $row['name'] . "</td>";                    echo "</tr>";                }                echo "</table>";                mysqli_close($con);                ?>            </body>        </html>

关键要掌握的语句和技术:

1).调整页面编码

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

2).连接本地数据库

$con = mysqli_connect("localhost","root","","taoeytest");
    括号中:主机名,用户名,密码,数据库名

3).简单的读取数据库中的数据(用while循环)

$result = mysqli_query($con,"SELECT * FROM student");

括号中变量:(要执行的连接,要执行的查询语句)

while($row = mysqli_fetch_array($result))        {             echo $row['id'];             echo $row['age'];             echo $row['name'] ;             echo "</tr>";//回车换行        }

其他人的代码:

<html>        <head>        <title>浏览表中记录</title>        </head>        <body>        <center>        <?php        $db_host=localhost;      //MYSQL服务器名        $db_user=root;       //MYSQL用户名        $db_pass="";       //MYSQL用户对应密码        $db_name="test";      //要操作的数据库        //使用mysql_connect()函数对服务器进行连接,如果出错返回相应信息        $link=mysql_connect($db_host,$db_user,$db_pass)or die("不能连接到服务器".mysql_error());        mysql_select_db($db_name,$link);   //选择相应的数据库,这里选择test库        $sql="select * from test1";     //先执行SQL语句显示所有记录以与插入后相比较        $result=mysql_query($sql,$link);   //使用mysql_query()发送SQL请求        echo "当前表中的记录有:";        echo "<table border=1>";     //使用表格格式化数据        echo "<tr><td>ID</td><td>姓名</td><td>邮箱</td><td>电话</td><td>地址</td></tr>";        while($row=mysql_fetch_array($result))  //遍历SQL语句执行结果把值赋给数组        {         echo "<tr>";         echo "<td>".$row[id]."</td>";   //显示ID         echo "<td>".$row[name]." </td>";  //显示姓名         echo "<td>".$row[mail]." </td>";   //显示邮箱         echo "<td>".$row[phone]." </td>";  //显示电话         echo "<td>".$row[address]." </td>";  //显示地址         echo "</tr>";        }        echo "</table>";        ?>        </center>        </body>        </html>
0 0
原创粉丝点击