简体   繁体   English

在PHP中插入sql

[英]Insert into sql in PHP

Lets say I have a file called comments.php . 可以说我有一个名为comments.php的文件。 In it I have a row like this: 在其中有这样的一行:

$post_id = $_GET['id']; 
$result = mysqli_query($con,"SELECT * FROM comments WHERE post_id = $post_id"); 

$post_id is the id of the actual entry. $post_id是实际条目的ID。

If I echo $post_id it shows the entry's number, no problem there. 如果我回显$post_id它会显示条目的编号,那里没有问题。

There's also a file called comment_send.php . 还有一个名为comment_send.php的文件。

In it I want to send a comment, alongside with the id of the actual entry, so the comments will know where they belong to. 我要在其中发送评论以及实际条目的ID,以便评论知道它们的位置。

$post_id = $_GET['id'];
$result = mysqli_query($con,"SELECT * FROM comments WHERE post_id = $post_id"); 
$sql="INSERT INTO comments (comment, post_id) VALUES ('$_GET[comment]','$post_id')";

However, when I hit the submit button I get this: Notice: Undefined index: id 但是,当我按下“提交”按钮时,我得到以下信息: Notice: Undefined index: id

I dont understand the problem because in the comments.php everything works fine but if I move the same part into another file it fails. 我不明白这个问题,因为在comments.php一切正常,但是如果我将同一部分移动到另一个文件中,它将失败。 Does anyone know what my problem might be? 有人知道我的问题是什么吗?

And yeah, the comment arrives in the database, with the number 0, instead of the entry number. 是的,注释以数字0而不是条目号到达数据库。

Your submitting data from the client to the server using a form, right? 您使用表单将数据从客户端提交到服务器,对吗? Check your action on your form. 检查您对表单的操作。 Is it POST (as it should be if you are updating your database)? 是POST(如果要更新数据库,应该这样)吗? If so, change $post_id = $_GET['id']; 如果是这样,则更改$post_id = $_GET['id']; to $post_id = $_POST['id']; $post_id = $_POST['id'];

As a troubleshooting tool, I typically add something like echo('<pre>'.print_r($_REQUEST,1).'</pre>'); 作为故障排除工具,我通常添加类似echo('<pre>'.print_r($_REQUEST,1).'</pre>'); to the top of my page. 到我的页面顶部。 You can then find out what type of data you are sending to the server. 然后,您可以找出要发送到服务器的数据类型。 Then when you get to your SQL statement, be sure to echo the query to see what it is. 然后,当您进入SQL语句时,请确保回显查询以查看查询的含义。

Also, sanitize your data as you are open to SQL injection. 另外,在对SQL注入开放的同时清理数据。

It doesn't look like you are passing 'id' to your comment_send.php page. 您似乎没有将'id'传递到comment_send.php页面。 Either pass it in with your comment, or save it as a $_SESSION variable on the previous page. 可以将其与您的评论一起传递,也可以将其另存为上一页中的$ _SESSION变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM