我正在尝试使用php和mysql制作一个facebook风格的分享帖子系统。
我想从数据克隆以下屏幕截图行: https://prnt.sc/hhp97n
在这一行中,您可以看到post_hashtags
是 NULL
,这意味着帖子没有主题标签。
当我分享这篇文章时,我得到了这个截图:https://prnt.sc/hhp8rx
我在克隆行之后没有为NULL
获取 post_hashtags
。
在克隆行之后应该是这样的:https://image.prntscr.com/image/Z5nloIeBSta6KCDCQfinqA.png
我不确定我的方式是否正确,但它确实有效。我用以下代码尝试了这个。
$query = mysqli_query($this->db,
"SELECT post_id, post_text, post_title
FROM posts
WHERE post_id = '$post_id'")
or die(mysqli_error($this->db));
$data=mysqli_fetch_array($query, MYSQLI_ASSOC);
$post_title = isset($data['post_title']) ? $data['post_title'] : NULL;
$post_text = isset($data['post_text']) ? $data['post_text'] : NULL;
$post_hashtags = isset($data['post_hashtags']) ? $data['post_hashtags'] : NULL;
$CloneThePost = mysqli_query($this->db,
"INSERT INTO `posts`(post_title,post_text,post_hashtags)
VALUES('$post_title','$post_text','$post_hashtags')"
) or die(mysqli_error($this->db));
答案 0 :(得分:1)
如果要插入NULL,则需要插入NULL。您正在插入空白字符串:''。如果您打印了INSERT语句,那么您将拥有这个。您之前可能使用过Oracle数据库 - 对于该DBMS,空字符串与NULL相同,但大多数DBMS对它们的处理方式不同。
值得注意的是,即使最初的捕获后免疫,重复也会引入SQL注入漏洞。
虽然你可以这样做:
$post_title = isset($data['post_title']) ?
"'" . mysqli_real_escape_string($db, $data['post_title']) . "'"
: NULL;
$post_text = isset($data['post_text']) ?
"'" . mysqli_real_escape_string($db, $data['post_text']) . "'"
: NULL;
$post_hashtags = isset($data['post_hashtags']) ?
"'" . mysqli_real_escape_string($db, $data['post_hashtags']) . "'"
: NULL;
...
VALUES($post_title,$post_text,$post_hashtags)
就个人而言,我只是试试这个......
INSERT INTO posts b (b.post_text, b.post_title, b.post_hashtags)
SELECT a.post_id, a.post_text, a.post_title, '"
. mysqli_real_escape_string($db, $post_hashtags) . "'
FROM posts a
WHERE a.post_id = '$post_id'
虽然我更倾向于规范化架构。
答案 1 :(得分:-1)
Try following code you have to set DEFAULT VALUE of field 'post_hashtags' as NULL in your table structure
$ post_hashtags =!empty($ data [' post_hashtags'])?$ data [' post_hashtags']:NULL;
if(!empty($post_hashtags))
{
$query="INSERT INTO `posts`(post_title,post_text,post_hashtags)VALUES('$post_title','$post_text','$post_hashtags')"
}
else
{
$query="INSERT INTO `posts`(post_title,post_text)VALUES('$post_title','$post_text')"
}
$CloneThePost = mysqli_query($this->db,$query) or die(mysqli_error($this->db));