MySQL PHP - substr()导致0个零在空表单字段中输入数据库

I am using substr(trim('SOME_FORM_VALUE'),0,7), on some form values just before submitting them to the database.

Form fields that have been submitted blank, are ending up as 0 (ZERO) in the database. If I remove the substr() everything is fine and there is no value in the database. The database (InnoDB) column is set as VARCHAR and not null.

code example:

$data_Arr = array(
'SOME_TABLE_COLUMN1' => substr(trim('SOME_FORM_VALUE1'),0,7),
'SOME_TABLE_COLUMN2' => substr(trim('SOME_FORM_VALUE2'),0,50)
);

$this->db->update('SOME_TABLE', $data_Arr);

Last MySQL Query ends up looking like this:

INSERT INTO `SOME_TABLE` (`SOME_TABLE_COLUMN1`, `SOME_TABLE_COLUMN2`)
VALUES (0, 0);
  • Why is 0 (ZERO) the result of substr() on an empty form string?
  • Any idea how to prevent the 0 (ZERO) from being entered?

Thanks all :)

Used 'mb_strimwidth' - does NOT resolve to zero in the event of empty string.

<?php
echo mb_strimwidth("Hello World", 0, 10);
// outputs Hello W
?>

substr():

Returns the extracted part of string; or FALSE on failure, or an empty string.

So you're probably getting the false value converted to 0 if you're attempting to return a portion of the string that is out of bounds.

i think you could try using if to test before substr

   if (strlen($string) > 7){
    $file_name= substr(trim($string,0,$max)); 
   }