binary file content shown in php print_r but not s

2020-02-06 11:48发布

i have to save the files from input fields to database,i'll do it this way:

    $mkey = mysqli_insert_id($mysqli);
    $i=0;
    while (isset($_FILES['file'.$i])) {
        $filepath = ini_get('upload_tmp_dir')."/".basename($_FILES['file'.$i]['tmp_name']);
        $filepath = addslashes($filepath);
        $handle = fopen($filepath, "rb");
        $content = fread($handle, filesize($filepath));
        $stmt = $mysqli->prepare("INSERT INTO attachment (filename,filecontent,mkey) VALUES (?,?,?)");
        $stmt->bind_param("sbi",$_FILES['file'.$i]['name'],$content,$mkey);
        $stmt->execute();
        fclose($handle);
        $i++;
    }

no error occured,and the other 2 fields mkey and filename are filled in database columns,but the content no,$content shown with print_r in my browser and i sure the $content variable is not empty,but mysql shows me nothing of the content.

1条回答
Fickle 薄情
2楼-- · 2020-02-06 12:07

RTM ;-)

If data size of a variable exceeds max. allowed packet size (max_allowed_packet), you have to specify b in types and use mysqli_stmt_send_long_data() to send the data in packets.

So I have never done this myself but i would assume it needs to look something like this based on your code and the example on the functions doc page:

    $filepath = ini_get('upload_tmp_dir')."/".basename($_FILES['file'.$i]['tmp_name']);
    $filepath = addslashes($filepath);
    $handle = fopen($filepath, "rb");
    $content = null;

    $stmt = $mysqli->prepare("INSERT INTO attachment (filename,filecontent,mkey) VALUES (?,?,?)");
    $stmt->bind_param("sbi",$_FILES['file'.$i]['name'], $content, $mkey);

    while (!feof($handle)) {
        // $maxPacketSize would be the size of your max packet setting for mysql,
        // or something safely assumed to be below it
        $stmt->send_long_data(1, fread($handle, $maxPacketSize));
    }
    fclose($handle);
    $stmt->execute();
查看更多
登录 后发表回答