为数据库中的每条记录创建wav文件

ozxc1zmp  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(375)

我在数据库中存储了一个表 wav 中的文件 longblob 列。我正在尝试创建一个文件夹并存储所有 wav 服务器上给定用户的。到目前为止,我所做的是对数据库和表的查询,以及到目前为止只存储一个数据库和表的简单示例 wav . 我不太熟悉php,我需要一些帮助。

$con=mysqli_connect("localhost","root","xxxx","testDB");

if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT recording FROM users WHERE accountID = '1234'";
$result=mysqli_query($con,$sql);

while ($result = mysqli_fetch_array($row)) {

    $data = $result["recording"];

    //mkdir('/var/spool/sounds/', 0755, true);

    $wavFileName = "/var/spool/sounds/wavfile.wav";
    $fh = fopen($wavFileName, 'w'); 
    fwrite($fh, $data);
    fclose($fh);
}

上面剪掉的是创造一个 wav 在那个目录里。
如果用户有5个保存的wav文件,如何用名称创建目录 userID 以及 file1.wav , file2.wav .. 里面有什么?

a14dhokn

a14dhokn1#

使用以下代码,将工作:

$account_id = 1234;
mkdir('/var/spool/sounds/'.$account_id, 0755, true);
$sql="SELECT recording FROM users WHERE accountID = ".$account_id ;
$result=mysqli_query($con,$sql);
$i=0;
while ($result = mysqli_fetch_array($row)) {
    $i++;
    $data = $result["recording"];

    $wavFileName = "/var/spool/sounds/".$account_id."/file".$i.".wav";
    $fh = fopen($wavFileName, 'w'); 
    fwrite($fh, $data);
    fclose($fh);
}
zpjtge22

zpjtge222#

只需创建路径和文件名,将userid和已经创建的文件数串联起来。然后,检查该路径是否存在,否则创建它。

$directory = "/var/spool/sounds/" . $userID;
$fileExtension = ".wav";
$fileNumber = 1;
while ($result = mysqli_fetch_array($row))
{
    $data = $result["recording"];
    if (!is_dir($directory))
        mkdir($directory, 0755, true);

    $wavFileName = $directory . "/file" . $fileNumber;
    /*
     *  if you need to check if the file already exists,
     *  you can rename the new file "/var/spool/sounds/userId/file1_copy.wav"
     *  or "/var/spool/sounds/userId/file1_copy_copy.wav" if a copy already exists and so on.
     */
    while (file_exists($wavFileName . $fileExtension))
        $wavFileName .= "_copy";
    $fh = fopen($wavFileName . $fileExtension, 'w'); 
    fwrite($fh, $data);
    fclose($fh);
    $fileNumber++;
}

相关问题