我创建了一个简单的脚本来将表单中的文本插入到数据库中。但出于某种原因,有些文本不会插入!如果我从 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')");
但是,我建议您切换到 MySQLi
或 PDO
库来利用准备好的语句。
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/