1

I'm using prepared statements to add rows to my database. I'm restructuring my code and am running into an issue with bind_param - I assume it's syntactical but can't figure out what's wrong.

No data supplied for parameters in prepared statement

function insertRow($fieldNames, $fields, $table, $link) {
    $field_names=implode(', ',$fieldNames);
    $field_values=implode(', ',$fields);
    //add question marks
    $q_marks=array();
    forEach($fieldNames as &$qm) {
        array_push($q_marks, "?");
    }
    $qs = implode(',',$q_marks);

    $stmnt = "INSERT INTO $table ($field_names) VALUES ($qs)";
    echo("<br>$stmnt<br>");
    $addrow = $link->prepare("INSERT INTO $table ($field_names) VALUES ($qs)");
    //add param types (all strings)
    $s_chars=array();
    forEach($fieldNames as &$s) {
        array_push($s_chars, "s");
    }    
    $s = implode('',$s_chars);
    echo("$s, $field_values<br>");

    $addrow->bind_param($s, $field_values);
    try {
        echo("adding row...");
        $addrow->execute();            
    } catch(Exception $e){
        echo("error: " .$e ."<br>");
        return false;
    }
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
froggomad
  • 1,747
  • 2
  • 17
  • 40
  • 2
    You must be aware of [SQL injection through table and field names](https://phpdelusions.net/pdo/sql_injection_example). I recently wrote an [answer providing a safe solution for such a function](https://stackoverflow.com/a/57871864/285587) – Your Common Sense Sep 11 '19 at 07:34
  • Thanks, I am. Everything's sanitized before it gets here – froggomad Sep 11 '19 at 23:51

1 Answers1

1

Trying to use the line

$addrow->bind_param($s, $field_values);

tries to pass a list of the fields joined with commas. This actually supposed to be the value of each value as a separate value. This can easily be done using the splat operator (...) and the original field values...

$addrow->bind_param($s, ...$fields);

You can also do a few tweaks with other parts of the code, rather than...

$s_chars=array();
forEach($fieldNames as &$s) {
    array_push($s_chars, "s");
}    
$s = implode('',$s_chars);

you can just use

$s = str_repeat("s", count($fieldNames));
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55