duancai1904 2015-07-02 06:14
浏览 44
已采纳

当值具有Quote时,列值的字符串长度减1

Hi I have table for "comments" , here it has a field called "comment_text" , I insert the comment like this to table

   $query="insert into `comments` 
    (`id`,
    `comment_text`, 
    `date`) 
    values
    ('',
    '".sprintf("%-70s",mysql_real_escape_string(ucwords(trim($strTitle63_5))))."',
    '$date')";

As you can see i am setting the comment length to fix 70 characters (always the original comment is less than 70 characters.)

Everything works fine unless i insert a value with quote , if i insert a comment with a quote , in the database table i can see only 69 characters .

Example :

I insert these two comments

Comment 1 : "Flat Rate Overlaps With Another Flat Rate Code"

Comment 2 : "Claim Details Don't Match BSI/BRI Guidelines"

later when i try to check the string length . Comment 1 is 70 and Comment 2 is 69. Is there any reason for this ?

Every comment that has a quote gives me this issue . :( .

Thanks in advance .

UPDATE

My code

Model

function get_coc5_comment_details()
{
    $this->db->select("comment_text");
    $this->db->from("comments");
    $result=$this->db->get();

    return $result->result_array();
}

Controller

function validate_db()
{
    $result = $this->invoice_model->get_comment_details();
    $this->load->view("comment_details_view",array("result"=>$result));
}

view

foreach ($result as $row)
{
    $comment = $row['comment_text'];

    echo strlen($comment)."<br>";
}
  • 写回答

1条回答 默认 最新

  • dongzhan1383 2015-07-02 06:22
    关注

    Everything works fine unless i insert a value with quote , if i insert a comment with a quote , in the database table i can see only 69 characters .

    Because when there is a quote in your string and then you run it through mysql_real_escape_string it adds a \ in your string :)

    And that's one extra character. Once that goes to the database \ is removed and you see 69.

    Why don't you consider prepared statements?

    Also, storing extra spaces in the database for no reason at all is not good design. You can write a wrapper method for display that appends your comments with extra spaces to complete the 70 character length when using those. I think you should be storing the original comments in the database. What if some day that length requirement becomes 75 for some reason?

    For example

    $str="test";
    echo str_pad($str, 70,'*');   // This will take it to 70 characters.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)