PHP教程

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语言连接数据库并对其进行操作

这篇关于php的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!