php-向数据库插入数据

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
    <meta charset="UTF-8">
</head>
<body>
<?php
    if($_SESSION['REQUEST_METHOD'] == 'POST'){  //处理表单
        //连接服务器并选中数据库:
        $dbc = mysql_connect('localhost','username','password');
        mysql_select_db('myblog',$dbc);

        //验证表单数据:
        $problem = FALSE;
        if(!empty($_POST['title']) && !empty($_POST['entry'])){
            $title = trim(strip_tags($_POST['title']));
            $entry = trim(strip_tags($_POST['entry']));
        }else{
            echo '<p style="color: red;">Please submit both a title and an enty.</p>';
            $problem = TRUE;
        }
        if(!$problem){
            //定义查询:
            $qurey = "INSERT INTO entries(entry_id,title,entry,date_entered) VALUES
            (0,'$title','$entry',NOW())";
            //执行查询:
            if(@mysql_query($query,$dbc)){
                echo '<p style="color: red;">Could not add the entry because:'.$qurey.'</p>';
            }
        }   //一切正常!
        mysql_close($dbc);  //关闭连接。
    }   //结束提交条件语句。

//显示表单
?>
<form action="add_entry.php" method="post">
    <p>Entry Title:<input type="text" name="title" size="40" maxsize="100"/></p>
    <p>Entry Text:<textarea name="entry" cols="40" rows="5"></textarea></p>
    <input type="submit" name="submit" value="Post This Entry!" />
</form>
</body>
</html>
<?php
    //mysql_connect() 打开一个到 MySQL 服务器的连接
    //mysql_select_db() 选择 MySQL 数据库
    //trim() 去除字符串首尾处的空白字符(或者其他字符)
    //mysql_query() 发送一条 MySQL 查询
    //mysql_close() 关闭 MySQL 连接
?>

猜你喜欢

转载自blog.csdn.net/Qjy_985211/article/details/80352874