首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

PHP sqlsrv从数据库插入/读取blob (varbinary)字段示例

PHP sqlsrv从数据库插入/读取blob (varbinary)字段示例:

插入Blob字段示例:

代码语言:php
复制
<?php
$serverName = "your_server_name";
$connectionOptions = array(
    "Database" => "your_database_name",
    "Uid" => "your_username",
    "PWD" => "your_password"
);

$conn = sqlsrv_connect($serverName, $connectionOptions);

if ($conn === false) {
    die(print_r(sqlsrv_errors(), true));
}

$filePath = "path_to_your_blob_file";
$fileContent = file_get_contents($filePath);
$sql = "INSERT INTO your_table (blob_column) VALUES (?)";
$params = array(
    array($fileContent, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY), SQLSRV_SQLTYPE_VARBINARY('max'))
);

$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
    die(print_r(sqlsrv_errors(), true));
}

sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
?>

读取Blob字段示例:

代码语言:php
复制
<?php
$serverName = "your_server_name";
$connectionOptions = array(
    "Database" => "your_database_name",
    "Uid" => "your_username",
    "PWD" => "your_password"
);

$conn = sqlsrv_connect($serverName, $connectionOptions);

if ($conn === false) {
    die(print_r(sqlsrv_errors(), true));
}

$sql = "SELECT blob_column FROM your_table WHERE id = ?";
$params = array(1); // Assuming the ID of the row you want to retrieve is 1

$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
    die(print_r(sqlsrv_errors(), true));
}

if (sqlsrv_fetch($stmt)) {
    $blobData = sqlsrv_get_field($stmt, 0, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY));
    $filePath = "path_to_save_blob_file";
    file_put_contents($filePath, $blobData);
}

sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
?>

以上示例代码演示了如何使用PHP的sqlsrv扩展从数据库插入和读取Blob字段(varbinary类型)。在插入Blob字段时,我们首先建立数据库连接,然后使用file_get_contents函数读取Blob文件的内容,并将其作为参数绑定到INSERT语句中。在读取Blob字段时,我们执行SELECT语句并使用sqlsrv_get_field函数获取Blob字段的内容,并将其保存到指定的文件路径中。

这些示例代码仅供参考,实际使用时需要根据自己的数据库和表结构进行相应的修改。另外,腾讯云提供了云数据库SQL Server服务,您可以通过以下链接了解更多相关产品信息:

请注意,以上答案仅供参考,具体实现方式可能因环境和需求而异。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券