GuerillaRadio
GuerillaRadio

Reputation: 1297

MySql INSERT statement is inserting a '0' rather than variable contents

I have a simple INSERT statement which looks like this...

mysql_query("INSERT INTO comments (`user_id`, `profile_id`, `comment`) VALUES ('{$_SESSION['user_id']}', ('$problemID'), ('$comment'))") or die(mysql_error());

Everything is being inserted fine apart from the $problemID variable. In the MySql table it is just returning a 0. The table is set up to receive integers up to 11 characters.

The variable itself is set on a different page but is retrieved using this...

$problemID = intval( $_GET["problem"]);

If I echo the $problemID I get the correct number so I'm unsure as to why it won't just insert this number into my table. Any pointers would be great.

Upvotes: 0

Views: 232

Answers (3)

Martin
Martin

Reputation: 1213

Remove the brackets and try to add the variables rather than including them into the string.

mysql_query("INSERT INTO comments (`user_id`, `profile_id`, `comment`)
VALUES ('".$_SESSION['user_id']."', ".$problemID.", '".mysql_real_escape_string($comment)."')") or die(mysql_error());

Upvotes: 0

pp19dd
pp19dd

Reputation: 3633

Make sure that your comment is more clearly sanitized; Try something like this:

mysql_query( sprintf(
    "INSERT INTO 
        comments (`user_id`, `profile_id`, `comment`) 
    VALUES     
        (%s, %s, '%s')",
    intval( $_SESSION['user_id'] ),
    intval( $problemID ),
    mysql_real_escape_string( $comment )
)) or die( mysql_error() );

Just to be thorough, make sure that your table has a separate primary index (aka entry ID) with auto-increment tacked on. It could be that your MySQL insertion is working fine, however, the receiving table doesn't know that it should keep appending entries.

Upvotes: 3

Brian Driscoll
Brian Driscoll

Reputation: 19635

My hunch is that your INSERT query is referring to the wrong column in your comments table, as you have the following:

INSERT INTO comments (`user_id`, `profile_id`, `comment`)

but you're referring to a variable named $problemID, so my guess is that you meant something like this:

INSERT INTO comments (`user_id`, `problem_id`, `comment`)

Perhaps you copied and pasted the query code but forgot to change the column name in the projection?

Upvotes: 0

Related Questions