php - 只有某些文本会插入数据库

标签 php mysql

我创建了一个简单的脚本来将表单中的文本插入到数据库中。但出于某种原因,有些文本不会插入!如果我从 lipsum.com 复制文本,它可以正常插入。但有时当我打字时,无论我尝试多少次,它都不会插入。随机的单词和段落总是会插入,而其他的不会!

这是我的表单代码

<?php 
session_start(); 
if(!$_SESSION['logged']){ 
header("Location: ../../System/login_page.php"); 
exit; 
} 
?>


<?php

require '../db_config.php';

$place_holder;

$result = mysql_query("SELECT alerts FROM alerts ORDER BY id DESC LIMIT 1;") or die     ("Could not make query");

while($row = mysql_fetch_array($result))
  {
  $place_holder = $row['alerts'];
  }

  ?>


    <div class="row">
<br/>   <br/>
        <div class="container">
        <div class="row">

        <div class="col-sm-4 contact-form">
        <form id="alert" method="post" class="form" role="form" action="../alert.php">
        <textarea value='hello' class="form-control" id="message" name="message" rows="5"><?php echo $place_holder;?></textarea>
        <br />
        <div class="row">
        <div class="col-xs-12 col-md-12 form-group">
        <button class="btn btn-primary pull-right" type="submit">Submit</button>
        </form>

这是我的操作代码(alert.php)

<?php

require 'db_config.php';

mysql_query("INSERT INTO alerts (alerts) VALUES('$_POST[message]')");

?>

最佳答案

您插入的数据未被清理:

mysql_query("INSERT INTO alerts (alerts) VALUES('$_POST[message]')");

如果 $_POST['message'] 包含单引号,您将遇到 SQL 错误。

使用 mysql_real_escape_string() 尝试以下操作:

$message = mysql_real_escape_string($_POST['message']);
mysql_query("INSERT INTO alerts (alerts) VALUES('$message')");

但是,我建议您切换到 MySQLiPDO库来利用准备好的语句。

MySQLi 示例(修改自 here ):

// Connect to the database
$mysqli = new mysqli("host", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

// Prepare the statement
if (!($stmt = $mysqli->prepare("INSERT INTO alerts (alerts) VALUES (?)"))) {
     echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

// Bind the values
if (!$stmt->bind_param("s", $_POST['message'])) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

// execute the query
if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

关于php - 只有某些文本会插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21122761/

相关文章:

mysql - 多次引用一个外键

php - 无法在嵌套 foreach 循环中多次循环遍历 mysql 结果

php - 保护文件下载在服务器上的文件夹中 &.htaccess 可见

php - php可以在没有用户请求的情况下在服务器端运行代码吗?

mysql - 导出latin1数据库并导入为utf8/转换为utf8

php - 插入表中的重复数据集

jquery - 是否可以使用 jquery post 或 get 请求来保存访客统计信息?

php - 具有相同列值的行并添加其受尊重的 int row 并排序

php - imagecreatefromjpeg 与 mysql 中断

php - 在 Yii2 中输出关系数据