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

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 :)

我正在使用 substr(trim('SOME_FORM_VALUE'),0,7), code> 在将它们提交到数据库之前的某些表单值上。 p>

已提交为空白的表单字段在数据库中最终为 0 strong> (ZERO) em>。 如果我删除了 substr() strong>一切都很好,数据库中没有任何值。 数据库(InnoDB)列设置为 VARCHAR strong>和非空 strong>。 p>

代码示例: p>

  $ 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); 
  code>  pre> 
 
 

Last MySQL 查询最终看起来像这样: p>

  INSERT INTO` SOME_TABLE`(`SOME_TABLE_COLUMN1`,`SOME_TABLE_COLUMN2`)
VALUES(0,0); 
  code>  
 
 
  • 为什么 0 strong> (ZERO) em>空表单字符串上的substr()结果? li >
  • 知道如何防止输入 0 strong> (ZERO) em>吗? li> ul>

    谢谢大家:) p> div>

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)); 
   }