首页 > 解决方案 > PHP- SQL not saving long text

问题描述

I'm having trouble saving long text into a database from a form. The page loads and returns without saving or displaying an error. Short texts are saving. Here's the code:

HTML:

<textarea id="" name="text_01" style="width:80%; height:150px;">
</textarea>

PHP/SQL:

$_POST = filter_var($_POST, \FILTER_CALLBACK, ['options' => 'trim']);
if (isset($_POST['saveCover']) && !empty($_POST)) {
    $data = $_POST;
    if (empty($cover)) {
        error_log("New Text insert. ");
        $sql = "insert into tbl_text (id, text_01) values ($id, '".$data['text_01']."';
    } 

SQL(DB):

CREATE TABLE `tbl_text` (
 `id` int(11) NOT NULL,
`text_01` text,
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Project Cover Pages';

标签: phpmysqlsql

解决方案


Your query is open to injection.

What I can see you have quoted the text using ' (single quote), now imagine if the entered text contains any single quote then it will break your query, long/length of the string is not a problem here. Also you have missed a closing " (double quote)

Use prepared statement, from your code I am not sure what you are using - PDO or mysqli, update your code to use prepared statement accordingly. Here for testing purpose use addslashes() to check if you can save long text.

$sql = "insert into tbl_text (id, text_01) values ($id, '".addslashes($data['text_01'])."'";

推荐阅读