Search code examples
phptrim

PHP trim not working


I m trying to get rid of the trailing comma my sql statemen using trim but it doesnt seem to work

if(isset($_POST['report'])){
    //====
    $sql = 'INSERT INTO weekly_repo ( hospnme, disease, week, under5, above5, dat) VALUES ';
    $week = intval($_POST['current_week']);
    $diseases = $_POST['diseases'];

    foreach($diseases as $disease){

        $sql .= ' ( "' . filterString($_POST['hospital']). '", "' . filterString($disease['disease']) . '", ' . $week . ', ' . intval($disease['under_5']) . ', ' . intval($disease['over_5']) . ', NOW()), ';

    }
    $sql = trim($sql, '\,');
    // ended up doing this
    //$sql = substr($sql, 0, strrpos($sql, ',')) . ';';
    $stmt = $conn->query($sql);

}

Solution

  • You don't need to escape \ the comma. A better approach might be to construct an array and then implode():

    foreach($diseases as $disease){
        $sql[] = ' ( "' . filterString($_POST['hospital']). '", "' . filterString($disease['disease']) . '", ' . $week . ', ' . intval($disease['under_5']) . ', ' . intval($disease['over_5']) . ', NOW()), ';
    }
    $sql = implode(',', $sql);