使用mysqli将二进制文件从php发送到mysql

时间:2015-06-19 14:36:23

标签: php mysql mysqli

我想从php脚本将数据发送到两个表中,picidcard是mysql db中的两个二进制文件,并且两者都有LONGBLOB类型始终是第一个插入查询执行成功(插入user表)但第二个查询(插入`申请人'表)有两种情况:

1 - 如果我在db中使picidcard字段为NULLABLE,则除了这两个数据之外的其他数据成功插入。

2 - 如果我将picidcard字段设为NOT NULLABLE,则不会插入“申请人”表格。

两种情况都无法将二进制数据保存到我的数据库中,问题出在哪里?

我在$ _FILES数组中也没有问题并传递它们,当我将它发布到php脚本时,我可以看到这些文件的详细信息。 我认为send_long_data出了问题,但我之前就像现在一样使用它!

这是脚本:

require_once('db_connection_config.php');
if (mysqli_connect_errno()) {
    print_r("<div class='bs-example center-block'><div id='alertshow' class='bs-example center-block alert alert-danger'><a href='#' class='close' data-dismiss='alert'>&times;</a><strong>Connection Error:</strong>" . mysqli_connect_errno() . "</div></div>");
    exit();
}
$today = date('Y:m:d');

$pass = randomPassword();

$stmt = $mysqli->prepare("INSERT INTO user (password,gender,firstname,lastname,email,phoneNum,mobileNum,Address,UserRoles_userRoleId) VALUES (?,?,?,?,?,?,?,?,3)");
$stmt->bind_param("sissssss", $pass, $_POST['gender'], $_POST['name'], $_POST['lastname'], $_POST['email'], $_POST['phonenum'], $_POST['mobilenum'], $_POST['address']);
$stmt->execute();

$mkey = mysqli_insert_id($mysqli);

$stmt->close();

if(isset($_FILES['pic']) && isset($_FILES['idcard'])){
$pic_file_path = $_FILES['pic']['tmp_name'];
    if ( !file_exists($pic_file_path) ) {
        throw new Exception('File not found.');
    }
$pic_handle = fopen($pic_file_path, "rb");
    if ( !$pic_handle ) {
        throw new Exception('File open failed.');
    }
    $pic_content = null;

$idpic_file_path = $_FILES['idcard']['tmp_name'];
$idpic_handle = fopen($idpic_file_path, "rb");
$idpic_content = null;

$stmt = $mysqli->prepare("INSERT INTO applicant (userId,nationalCode,fatherName,birthPlace,nationality,religion,postalCode,picture,idpicture,registrationDate,militaryServiceStatus) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("isssiisbbss", $mkey, $_POST['nationalcode'], $_POST['fathername'], $_POST['birthcity'], $_POST['nationality'], $_POST['religion'], $_POST['postalcode'], $pic_content, $idpic_content, $today, $_POST['mss']);
while (!feof($pic_handle)) {
    $stmt->send_long_data(1, fread($pic_handle, 8192));
}
fclose($pic_handle);
while (!feof($idpic_handle)) {
    $stmt->send_long_data(1, fread($idpic_handle, 8192));
}
fclose($idpic_handle);
$stmt->execute();
$stmt->close();
}


}

function randomPassword() {
    $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
    for ($i = 0; $i < 8; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
    }
    return implode($pass); //turn the array into a string
}

0 个答案:

没有答案