编程语言
首页 > 编程语言> > php

php

作者:互联网

<?php
//操作数据的增删改update

// .连接数据库
try {
    $pdo = new PDO("mysql:host=localhost;dbname=test;", "root", "");

} catch (PDOException $e) {
    die("数据库连接失败" . $e->getMessage());
}
// .防止中文乱码
$pdo->query("SET NAMES 'UTF8'");
// .通过action的值进行对应操作
switch ($_GET['action']) {
    case 'add':
    {   //增加操作
        $name = $_POST['name'];
        $sex = $_POST['sex'];
        $hobby = $_POST['hobby'];
        $address = $_POST['home'];
        $remark = $_POST['other'];

        //写sql语句
        $sql = "INSERT INTO info VALUES (NULL ,'{$name}','{$sex}','{$hobby}','{$address}','{$remark}')";
        $rw = $pdo->exec($sql);
        if ($rw > 0) {
            echo "<script> //alert('增加成功');
                               window.location='ex01b.php'; //跳转
                    </script>";
        } else {
            echo "<script> alert('增加失败');
                               window.history.back(); //返回上一页
                    </script>";
        }
        break;
    }
    case "del":
    {    // .获取表单信息
        //通过id删除信息
        $id = $_GET['id'];
        $sql = "DELETE FROM info WHERE id='{$id}'";
        $rw = $pdo->exec($sql);
        if ($rw > 0) {
            echo "<script> alert('数据删除成功!');
                               window.location='ex01b.php'; //跳转
                    </script>";
        } else {
            echo "<script> alert('数据删除失败!');
                               window.history.back(); //返回上一页
                    </script>";
        }

        break;
    }
    case "edit" :
    {   // .获取表单信息
        //原id
        $id = $_POST['id'];
        //表单信息
        //修改之后的信息
        $name = $_POST['name'];
        $sex = $_POST['sex'];
        $hobby = $_POST['hobby'];
        $address = $_POST['address'];
        $remark = $_POST['remark'];
        $sql = "UPDATE info SET name='{$name}',sex='{$sex}',address='{$address}',remark='{$remark}',hobby='{$hobby}' WHERE id='{$id}'";
        $rw = $pdo->exec($sql);
        if ($rw > 0) {
            echo "<script>alert('修改成功');window.location='ex01b.php'</script>";
        } else {
            echo "<script>alert('修改失败');window.history.back()</script>";
        }
        break;
    }

}

今天做了php实验,用php语言连接数据库并对其进行操作

标签:name,sex,sql,hobby,POST,php,id
来源: https://www.cnblogs.com/chenjiachengshmily/p/16339353.html