views:

214

answers:

3

Hello,

I am building a blog site and am having trouble with updating fields in my MYSQL database. Whenever I hit the update button on the form that uses PHP, it adds extra space before the text string in the MYSQL text field. Here is the PHP code:

   //UPDATE TEXT
   $updated_text = $_POST['text'.$the_post['ID'][$n]];
   if ($updated_text != "") {  
     $sql = "UPDATE posts SET TEXT = '".addslashes($updated_text)."' WHERE ID = '".$the_post['ID'][$n]."'";
     $text_result = mysql_query($sql) or die(mysql_error());
   }

Thanks

+4  A: 

Hi,

Not sure why you have this problem, but you could first try using trim to remove white-characters at the beginning and end of your string :

$updated_text = trim($_POST['text'.$the_post['ID'][$n]]);

If this solves the problem, it's because you are receiving those whitespaces from the form -- else... Well, strange ^^


A couple of other notes :

  • When escaping data to send it to your DB server, yOu should use the functions that are specific to your DB. Here, you are working with a MySQL database, and the mysql_* function, which means you should use mysql_real_escape_string instead of addslashes.
  • You are escaping the data you're putting in the TEXT ; but, to avoid SQL injections, you should protect the data use in the where clause too.
    • If your ID is a char/varchar in DB, it means using mysql_real_escape_string on $the_post['ID'][$n] too
    • If your ID is an integer in database :
      • the quotes arround the value are not necessary : quotes, in SQL, are the string-delimiter ; there is no need for any delimiter for integers
      • you should make sure you are sending an integer to the DB ; for instance, using intval($the_post['ID'][$n])
    • This will not change anything about your problem -- but taking care of security is always best ;-)
Pascal MARTIN
+2  A: 

Perhaps its an issue of the text-area tag of your html - for example if its indented or so..

Brimstedt
+1; I´ve had surprises with IDE's auto-formatting my code and adding spaces between the opening and the closing tag...
jeroen
A: 

I found that the empty mySQL field was inserting " " into my html form value, so I used:

$variable = trim($variable," ");

to trim the unwanted space.

Scott