【问题标题】:Insert data to mysql doesn't work from php将数据插入到 mysql 不能从 php 工作
【发布时间】:2013-06-28 10:12:39
【问题描述】:

我有以下 PHP 代码:

    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
    $insert_query = mysql_query("INSERT INTO articles(articleTitle, articleContent, typeID)
    VALUES
   ('$_POST[articleTitle]','$_POST[articleContent]',$_POST[articleType])");
    }

typeID => 为数字,其他值为文本。

这段代码没有错误,但是插入查询不起作用(我不知道为什么,因为我没有收到任何错误消息)。

我该如何解决?

【问题讨论】:

标签: php mysql insert


【解决方案1】:

您的代码存在许多问题。

  1. 对 SQL 注入开放
  2. mysql_* 函数已被弃用

此代码未经测试,但应该给你一个想法:

try
    $dbh = new PDO('mysql:host=localhost;dbname=your_database_name', $user, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sth = $dbh->prepare('INSERT INTO Persons (articleTitle, articleContent, typeID) VALUES (:articleTitle, :articleContent, :articleType)');
    $sth->execute($_POST);

    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
}

看看这篇文章Why you Should be using PHP’s PDO for Database Access

【讨论】:

    【解决方案2】:

    试试这个

    if(isset($_POST[articleTitle])) {
        $insert_query = mysqli_query("INSERT INTO Persons (articleTitle, articleContent,typeID)
        VALUES
        ('$_POST[articleTitle]','$_POST[articleContent]',$_POST[articleType])");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多