multiple query use resultset of previous query in one php file

I am trying to use a value that I receive from a MySQL query and then do an insert but it's not working. I'm getting an syntax error but the Insert Query is correct.

The select query returns an amount which I'm checking and then the program should do the insert query.

    <?php
require 'header.php';

$resID = mysql_real_escape_string($_POST['resID']);
$materialen_id = mysql_real_escape_string($_POST['materialen_id']);
$aantal = mysql_real_escape_string($_POST['aantal']);
$effectief_gebruikt = mysql_real_escape_string($_POST['effectief_gebruikt']);
$opmerking = mysql_real_escape_string($_POST['opmerking']);
//$datum_van = date('d-m-Y', $_POST['datum_van']);
//$datum_tot = date('d-m-Y', $_POST['datum_tot']);
$datum_van = $_POST['datum_van'];
$datum_tot = $_POST['datum_tot'];


$sql = "SELECT `aantal_beschikbaar` 
        FROM `materialen` 
        WHERE `id` = $materialen_id";
        
$result = mysql_query($sql) or die(mysql_error());

while ($row = mysql_fetch_array($result))
{
    $tot = $row['aantal_beschikbaar'];
    echo 'totaal: ' . $tot;
}



$sql2 = "SELECT `aantal` FROM `materialen_per_reservatie`
        WHERE `materialen_id` = $materialen_id";  
$result2 = mysql_query($sql2) or die(mysql_error());

while ($row = mysql_fetch_array($result2))
{
    //$aant = $row['aantal'];
    //echo $aant
    echo $row['aantal'];
}

$besch = ($tot - $aant);
echo 'beschikbaar: ' . $besch;



/*$sql3 = "SELECT * FROM `materialen_per_reservatie`
        WHERE `reservaties_id` = $resID
        AND   `materialen_id` = $materialen_id";
$result3 = mysql_query($sql3) or die(mysql_error());*/

if($besch > $aantal){



        $string2 = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`, `materialen_id`, `aantal`, `effectief_gebruikt`, `opmerking`, `datum_van`, `datum_tot`) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')";
        mysql_query($string2) or die(mysql_error());  

        
}      
  
require 'footer.php';
?>

Provided that the error is on only the insert query...

Your insert query is missing a needed space:

INSERT INTO `materialen_per_reservatie` (`reservaties_id`, `materialen_id`, `aantal`, `effectief_gebruikt`, `opmerking`, `datum_van`, `datum_tot`) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')

Add a space after materialen_per_reservatie. And I'm not sure you need all of the quotes.

INSERT INTO materialen_per_reservatie (reservaties_id, materialen_id, aantal, effectief_gebruikt, opmerking, datum_van, datum_tot) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')