Sending a variable in PHP with a form to the same

2019-09-02 22:20发布

问题:

Please Help, I am coding a page with PHP where users choose a subject, click on the link and are directed to a page where they can comment on.The user make use of a small form to comment on a subject. I am trying to submit the form to the same page. So that the comment that the user submitted will display immediatly. I am sending a variable with the form using the GET method, but I am getting: Database query failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1,

but it is writing to my database, just not displaying the data

Here is my code(before head):

<?php 

// GET subject_id from previous page and see if it has been set
if (isset($_GET['subj'])) {  
subject_id = $_GET['subj'];
} else {
$subject_id = NULL;
}


// process form that was submitted to same page
if (isset($_POST['submit'])) {

$subject_id = mysql_prep($_GET['subj']);
$commentbox = trim(mysql_prep($_POST['commentbox']));

$query = "INSERT INTO comments (
subject_id, content
) VALUES (
{$subject_id}, '{$commentbox}'
)";


if ($result = mysql_query($query, $connection)) {
// as is, $message will still be discarded on the redirect
$message = "The page was successfully created.";
redirect_to("blog_subject.php");
} else {
$message = "The page was unsuccessfully created.";
redirect_to("blog_subject.php");
}
}
?>

......and then the code to display the subject,comments and form...

<?php
// Retrieving Subject Name from subjects database
global $connection;
if (isset($_GET['subj'])) {$subject_id = $_GET['subj'];} 

$query = "SELECT * FROM subjects WHERE subject_id = {$subject_id}";

$result_set = mysql_query($query, $connection);

if (!$result_set) {die("Database query Failed: " . mysql_error());}

if ($subject_set = mysql_fetch_array($result_set)) {

echo $subject_set['subject_name'];

} else {

return NULL;

}
?>
<br />
<?php
// Retrieving Comments from comments database

global $connection;

$subject_id = $_GET['subj'];

$comment_set = mysql_query("SELECT * FROM comments WHERE subject_id =
{$subject_id}", $connection);

if (!$comment_set) {
die("Database query Failed: " . mysql_error());
}

echo "<ul class=\"pages\">";
while ($comment_for_subject = mysql_fetch_array($comment_set)) {
echo "<li>{$comment_for_subject["content"]}</li>";
}
echo "</ul>";   
?>
<br /> 

<form action="blog_subject.php?subj=<?php echo $subject_id_van_vorige_bladsy; ?>"
method="post">
<textarea name="commentbox" cols="100" rows="10"></textarea><br />
<input name="submit" type="submit">
</form>

回答1:

Is subject_id a string or a number? if it is a string you need to escape it like this:

$comment_set = mysql_query("SELECT * FROM comments WHERE subject_id = '{$subject_id}'", $connection);

If that is not it, please do an echo on $comment_set and post the output of that