user9538545
user9538545

Reputation:

Create WAV file for each record in database

I have table in database in which I'm storing wav files in longblob column. I'm trying to create an folder and store all wav's of given user on the server. What I have so far is query to database and table and so far simple example of storing just one wav. I'm not much familiar with PHP and I'll need a little bit help on this.

$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);
}

The snipped above is creating one wav in that directory.

If user has 5 saved wav files, how to create directory with name userID and file1.wav, file2.wav .. etc inside?

Upvotes: 0

Views: 240

Answers (2)

Cid
Cid

Reputation: 15247

Just create the path and filename with concatenation of userid and number of files already created. Then, check if that path exists, otherwise create it.

$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++;
}

Upvotes: 1

PierreN
PierreN

Reputation: 988

With the following code, will work :

$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);
}

Upvotes: 0

Related Questions