我将这个表单与ajax脚本连接,当我提交长文本时结果不保存在数据库中(在posts表上,我有post_content列为" longtext" type)。当我提交简单的东西时(比如"你好世界")结果正确保存。当我以前使用mysqli时,我用这行代码解决了这个问题(使用mysqli_real_escape_string):
//$insert_posts = "INSERT INTO posts (post_content,post_date,post_topic,post_by_uid) VALUES ('".mysqli_real_escape_string($conn,$_POST['val'])."',NOW(),$id,'".$_SESSION['uid']."')";
但是现在有了PDO,我无法做到。我试过这个:$conn->quote($reply)
但它没有用。
<script>
function saveEditorTrigger()
{
for ( instance in CKEDITOR.instances ) CKEDITOR.instances[instance].updateElement();
}
</script>
<script>
$(function () {
$('form').on('submit', function (e) {
saveEditorTrigger();
var str = CKEDITOR.instances['reply-post'].getData();
var id = <?php echo $_GET['id']; ?>;
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data:{ val : str, id : id },
success: function (data) {
alert('Your answer is submitted');
location.replace("topic.php?id=<?php echo $_GET['id']; ?>");
}
});
});
});
</script>
&#13;
<form id="form" >
<br>
<textarea name="reply-post"></textarea>
<script>
CKEDITOR.replace( "reply-post" );
</script>
<input type="submit" name="submit" value="submit">
</form>
&#13;
post.php文件:
<?php
include 'dbh.php';
session_start();
$reply = $_POST['val'];
$id = $_POST['id'] ;
$insert_posts = $conn -> prepare("INSERT INTO posts (post_content,post_date,post_topic,post_by_uid) VALUES ('".$reply."',NOW(),$id,'".$_SESSION['uid']."')");
//$insert_posts = "INSERT INTO posts (post_content,post_date,post_topic,post_by_uid) VALUES ('".mysqli_real_escape_string($conn,$_POST['val'])."',NOW(),$id,'".$_SESSION['uid']."')";
$insert_posts -> execute();
?>
&#13;
我的问题是我做错了什么?有什么想法吗?
答案 0 :(得分:0)
<?php
include 'dbh.php';
session_start();
$reply = $_POST['val'];
$id = $_POST['id'] ;
$userId=$_SESSION['uid'];
$insert_posts = $conn -> prepare("INSERT INTO posts
(post_content,post_date,post_topic,post_by_uid)
VALUES
(:post_content,:post_date,:post_topic,:post_by_uid)");
$insert_posts->bindParam(':post_content', $reply, PDO::PARAM_STR);
$insert_posts->bindParam(':post_date', NOW(), PDO::PARAM_STR);
$insert_posts->bindParam(':post_topic', $id, PDO::PARAM_STR);
$insert_posts->bindParam(':post_by_uid', $userId, PDO::PARAM_STR);
$insert_posts -> execute();
?>
https://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html可能是一个很好的学习资源
答案 1 :(得分:0)
更正此代码,我让它成功。
<?php
include 'dbh.php';
session_start();
$reply = $_POST['val'];
$id = $_POST['id'] ;
if (isset($_SESSION['uid'])){
$user=$_SESSION['uid'];
$insert_posts = $conn -> prepare("INSERT INTO posts (post_content,post_date,post_topic,post_by_uid) VALUES (:post_content,NOW(),:post_topic,:post_by_uid)");
$insert_posts->bindParam(':post_content', $reply);
$insert_posts->bindParam(':post_topic', $id);
$insert_posts->bindParam(':post_by_uid', $user);
$insert_posts->execute();
}
?>