【问题标题】:Unable to insert more than one row in MySQL?无法在 MySQL 中插入多于一行?
【发布时间】:2015-10-29 01:44:25
【问题描述】:

这是我的 PHP 代码:

$html = $_POST['html'];
$username   = $_POST['username'];
$connection = new mysqli('host', 'username', 'password', 'database');
$username   = $connection->real_escape_string($username);
$html       = $connection->real_escape_string($html);
$connection->query("INSERT INTO savedarticles (username, article) VALUES ('$username', '$html')");

这是我的 AJAX 代码:

$.ajax({
  type: "POST",
  url: 'savedarticle.php',
  data: {
    html: innerHTML,
    username: '<?php echo $_SESSION['user']; ?>'    
  }
}); 

$html 每次都有唯一的值。假设我有两个值:

  1. 用户名 = alpha , html = bla, bla class="bla"
  2. 用户名 = alpha , html = 更多 bla class="bla"

按类我想表示 HTML 中有双引号,但我正在转义它们。如果我单击这两个中的任何一个,则值将存储在数据库中,但不会存储后续值。如果我先单击 1,它将被保存,然后单击 2 将没有任何效果。如果我先单击 2,它将被保存,然后单击 1 将没有任何效果。 万一这很重要,我还有另一个具有相同列名username 的表。另外我的表savedarticles 有一个Id 列,其值为intusername 列的类型为varchar(255)article 的列类型为text

【问题讨论】:

  • 请不要通过插入字符串 ('$username') 来构建查询,这是非常不安全和脆弱的。已准备好声明以解决此问题:stackoverflow.com/a/1290995/252218
  • $html 是否包含 html 元素?
  • 尝试在 ajax 上打印日志,看看它在第一次触发后是否仍然有效。
  • 什么触发$.ajax({?控制台有错误吗?

标签: php jquery mysql


【解决方案1】:

我已经编辑了您的代码。请查看并尝试。

<?php
$html = $_POST['html'];
$username   = $_POST['username'];
$connection = mysqli_connect('host', 'username', 'password', 'database');
$username   = $connection->real_escape_string($username);
$html       = $connection->real_escape_string($html);
$connection->query("INSERT INTO savedarticles (username, article) VALUES ('".$username."', '".$html."')");

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-13
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多