使用PHP准备的语句将image(blob)插入mysql数据库

时间:2019-05-04 11:02:35

标签: php mysql sql prepared-statement

我需要使用准备好的语句将图像插入mysql数据库...除图像外,其他所有内容都将插入

$name = mysqli_real_escape_string($conn, $_POST['name']);
    $category = mysqli_real_escape_string($conn, $_POST['category']);
    $privacy = mysqli_real_escape_string($conn, $_POST['privacy']);
    $maxmembers = mysqli_real_escape_string($conn, $_POST['maxmembers']);
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    $file = $_FILES['avatar']['tmp_name'];
    $image = addslashes(file_get_contents($_FILES['avatar']['tmp_name']));
    $image_name =addslashes($_FILES['avatar']['tmp_name']);
    $image_size = getimagesize($_FILES['avatar']['tmp_name']);



$sql = "INSERT INTO hjuma_groups (name, description, category, privacy, maxmembers, owner, avatarname, avatar) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = mysqli_stmt_init($conn);
            if (!mysqli_stmt_prepare($stmt, $sql)) {
              echo "SQL error";
            }else {
              mysqli_stmt_bind_param($stmt,"sssssssb", $name,$description,$category, $privacy,$maxmembers, $owner, $image_name, $image);
              mysqli_stmt_execute($stmt);
            }

1 个答案:

答案 0 :(得分:0)

我认为您缺少的难题是图像数据上的base64_encode,如下所示:

$name =             $_POST['name']);
$category =         $_POST['category'];
$privacy =          $_POST['privacy'];
$maxmembers =       $_POST['maxmembers']);
$description =      $_POST['description']);
$name =             $_FILES['avatar']['name'];
$image_name =       $_FILES['avatar']['tmp_name'];
$image =            base64_encode( file_get_contents( $image_name ) );
$image_size =       getimagesize( $image_name );



$sql = "insert into `hjuma_groups` 
        ( `name`, `description`, `category`, `privacy`, `maxmembers`, `owner`, `avatarname`, `avatar`) 
        values 
        (?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);

if( !mysqli_stmt_prepare( $stmt, $sql ) ) {
    echo "SQL error";
}else {
    mysqli_stmt_bind_param( $stmt, "sssssssb", $name, $description, $category, $privacy, $maxmembers, $owner, $image_name, $image );
    mysqli_stmt_execute($stmt);
}