php和数据库


PHP文本连接数据库

准备工作

首先要打开mysql服务以及apache服务

在网页中输入127.0.0.1/phpmyadmin进入mysql图形化管理界面

新加一个名叫test的库,库里table1表,表里有id,username,password三个字段

image-20220322200840920

连接数据库

在www目录下新建一个php,开始php连接数据库

connect_error){
    die("error".$conn->connect_error);
}
echo "success";
?>

数据库增删改查

准备一条数据库语句,然后执行,最后输出结果

//查找语句,查找table1里id<3的数据
$sql = "SELECT * FROM table1 WHERE id < 3";

//执行sql语句,并且返回给变量$result
$result = $conn->query($sql);
//条件语句,如果$result不为空
if ($result->num_rows > 0)
{    
    //输出数据,fetch_accos()从结果集中取出一行作为关联数组
    while ($row=$result->fetch_assoc()) {
        echo $row['id'].'------'.$row['username'].'------'.$row['password']."
"; } }else{ echo "0 结果"; } ?>

//插入数据
$sql = "INSERT INTO table1 (id,username,password) VALUES(4,'haha','123456')";
//===代表全等于 ==必须要求两边数据类型一致,否则会强制类型转换
if($conn->query($sql)===TRUE){
    echo "success";
}else{
    echo "error:".$conn->error;
}

$sql = "DELETE FROM table1 WHERE username='haha'";
if($conn->query($sql)===TRUE){
    echo "success";
}else{
    echo "error:".$conn->error;
}

$sql = "UPDATE table1 SET password='niu' WHERE username='xm'";
if($conn->query($sql)===TRUE){
    echo "success";
}else{
    echo "error:".$conn->error;
}

html和PHP结合起来美化网页

<html>
 <head>
  <title> db test </title>
 </head>

 <body>
 <?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
$conn = new mysqli($servername,$username,$password,$dbname);
if ($conn->connect_error)&#123;
    die("error".$conn->connect_error);
&#125;
$sql = "SELECT * FROM table1 WHERE id < 4";
$result = $conn->query($sql);
if ($result->num_rows > 0) &#123;
    echo "<table border='1'>";
    echo "<tr><th>id</th> <th>username</th> </tr>";
    while ($row = $result->fetch_assoc()) &#123;
        echo "<tr>";
        echo "<td>".$row['id']."</td>";
        echo "<td>".$row['username']."</td>";
        echo "</tr>";
    &#125;
    echo "</table>";
&#125;
$conn->close();

 ?>
 </body>
</html>

文章作者: Broken-year
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Broken-year !
  目录