gpt4 book ai didi

javascript - 默认 NULL 未设置

转载 作者:行者123 更新时间:2023-12-03 04:34:04 24 4
gpt4 key购买 nike

我在 contenteditable 方面遇到问题。我正在尝试使用 contenteditable 制作 ajax post 方法。我有两个 contenteditable div。

如果它没有写入任何内容,则它必须是数据库表中的NULL,但它显示空帖子未设置NULL

AJAX

$("body").on("click", ".post", function() {
var text1 = $("#text1").html();
var text2 = $("#text2").html();

var data = 'text1=' + encodeURIComponent(text1) + '&text2=' + encodeURIComponent(text2);

$.ajax({
type: 'POST',
url: '/requests/post.php',
data: data,
cache: false,
beforeSend: function() {
// Do something
},
success: function(html) {
console.log("post sended");
}
});

});

HTML

<div class="abc" id="text1" contenteditable="true" placeholder="Write something1"></div>
<div class="text2" id="text2" contenteditable="true" placeholder="Write something2"></div>

post.php

<?php 
include "../inc/inc.php";
if(isset($_POST['text1'])){
$text1 = mysqli_real_escape_string($db, $_POST['text1']);
$text2 = mysqli_real_escape_string($db, $_POST['text2']);
$data = $POST->POST($uid,$text1, $text2);
}
?>

和POST函数

public function POST($uid,$text1, $text2) {


$time=time(); // Current post time
$ip=$_SERVER['REMOTE_ADDR']; // user ip
$query = mysqli_query($this->db,"SELECT post_id,text1,text2 FROM `posts` WHERE uid_fk='$uid' order by post_id desc limit 1") or die(mysqli_error($this->db));
$result = mysqli_fetch_array($query, MYSQLI_ASSOC);
// Add the insert POST
$query = mysqli_query($this->db,"INSERT INTO `posts` (text1,text2, uid_fk,time) VALUES ('$text1','$text2','$uid','$time')") or die(mysqli_error($this->db));

}

所有代码都工作正常。但问题是text2。如果不写入任何文本,则数据库中显示空结果。我想设置 id 默认 NULL

enter image description here

方法不对

enter image description here

应该是这样的

enter image description here

我在这里缺少什么?任何人都可以在这方面帮助我吗?

最佳答案

问题是您正在传递 empty value而不是null本身

只需检查字符串是否为 empty如果为空则置 null

if(isset($_POST['text1'])){
$text1 = mysqli_real_escape_string($db, $_POST['text1']);
$text2 = mysqli_real_escape_string($db, $_POST['text2']);
$text1 = !empty($text1) ? $text1 : null;
$text2 = !empty($text2) ? $text2 : null;
$data = $POST->POST($uid,$text1, $text2);
}

你也是 insert语句添加 '围绕字符串,这将使得 null作为字符串 'null' :

因此要进行相应的处理,请使用 pdo:

$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname","$dbusername","$dbpassword");
$stmt = $dbh->prepare("INSERT INTO `posts` (text1,text2, uid_fk,time) VALUES (:text1,:text2,:uid,:time)");

$statement->execute(array(':text1'=>$text1,
':text2', $text2,
':uid', $uid,
':time', $time
));

编辑:

由于某些原因,如果您不能或不想使用 PDO。你最终会侵入sql。像这样的东西:

$text2 = !empty($text2) ? "'".$text2."'":null;
$text1 = !empty($text1) ? "'".$text1."'":null;
$query = mysqli_query($this->db,"INSERT INTO `posts` (text1,text2, uid_fk,time) VALUES ($text1,$text2,'$uid','$time')");

关于javascript - 默认 NULL 未设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43366571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com