【问题标题】:How to insert image directly into the database (php)?如何将图像直接插入数据库(php)?
【发布时间】:2020-05-26 23:01:42
【问题描述】:

知道不推荐,但是需要直接在msql数据库中插入图片。

字段已经像一个blob了

代码:插入

 public function insert($tableName, array $data){
    $stmt = $this->pdo->prepare("INSERT INTO $tableName (".implode(',', array_keys($data)).")
        VALUES (".implode(',', array_fill(0, count($data), '?')).")"
    );
    try{
        $stmt->execute(array_values($data));
        return $stmt->rowCount();
    } catch (\PDOException $e) {
        throw new \RuntimeException("[".$e->getCode()."] : ". $e->getMessage());
    }
}

代码:数据

if(isset($_REQUEST['submit']) and $_REQUEST['submit']!=""){
extract($_REQUEST);
    $userCount  =   $db->getQueryCount('tb_user','id');
    if($userCount[0]['total']){
           $Photo = $_FILES['in_Photo'];
           $contentFile = file_get_contents($in_Photo['tmp_name']);
        $data = array(
                'C_Imagem'=>$contentFile,
                'C_user'=>$in_Name,
        );
        $insert =   $db->insert('tb_cruds',$data);
        if($insert){
            header('location:index.php?msg=ras');
            exit;
        }else{
            header('location:index.php?msg=rna');
            exit;
        }
    }else{
        header('location:'.$_SERVER['PHP_SELF'].'?msg=dsd');
        exit;
    }

}

代码:HTML

<div class="form-group">
    <label>Photo</label>
    <input class="" type="file" name="in_Photo" id="in_Photo"   />
</div>

【问题讨论】:

  • 既然知道不推荐,为什么不推荐呢?我建议您将图像保存到一个文件夹并保存它们的名称,如果需要,可能是路径。这样,您的数据库负载就会减少。
  • 如何存入数组,本例中数组为$data?

标签: php html image


【解决方案1】:
  1. 首先更改数据库的排序规则 => utf8mb4_general_ci
  2. 文件大小应相应
    TEXT 可存储 65,535 个字符(约 64KB) MEDIUMTEXT = 16,777,215 个字符(约 16 MB) LONGTEXT = 4,294,967,295 个字符(约 4GB) VARCHAR 最多可以存储 255 个字符

【讨论】:

    猜你喜欢
    • 2017-03-23
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    相关资源
    最近更新 更多