I need help finding the error

I created a file with some useful PHP functions for working with SQL databases, but I am having a problem with the code that inserts a record into an SQL table. When I try to execute this code, it looks like this:

Fatal error: Unprepared error: unsupported operand types in C: \ xampp \ htdocs \ iterations_php_mysql.php: 118 Stack trace: # 0 C: \ xampp \ htdocs \ prova.php (9): setRecord (Object (mysqli), 'studenti ', Array, Array) # 1 {main} selected in C: \ xampp \ htdocs \ iterations_php_mysql.php on line 118

This is the function ( $link

is the host reference get with $link = mysqli_connect($host, $username);

, $table

is the table name, $tableFields

is the array containing the field names, $recordFields

is the array containing the fields of the new record):

function setRecord($link, $table, $tableFields, $recordFields){

    $sql = "INSERT INTO ".$table." (";

    if(count($tableFields) == count($recordFields)) $n = $tableFields;
    else    return false;

    for($i=0; $i<$n; $i++){

        $sql = $sql . $tableFields[$i];
        if($i != $n-1){   $sql = $sql . ", ";}   //this is the line 118
    }

    $sql = $sql.") VALUES (";

    for($i=0; $i<$n; $i++){

        $sql = $sql.$recordFields[$i];
        if($i != $n-1)   $sql = $sql . ", ";
    }

    $sql = $sql.")";

    return mysqli_query($link, $sql);
}

      

+3


source to share


2 answers


$n = $tableFields

      

So, I assume that $ tableFields is an array?

If so, then there is no point in doing the following with an array:

if ($i != $n-1) ...

      

Because you cannot do arithmetic on an array like this. This will work better:

if ($i != count($n)-2) ...

      



Note that you will need to subtract 2 because the arrays start at index 0.

But I have a better suggestion to simplify the code:

Instead of all this:

for($i=0; $i<$n; $i++){
    $sql = $sql . $tableFields[$i];
    if($i != $n-1){   $sql = $sql . ", ";}   //this is the line 118
}

      

Write this:

$sql .= implode(", ", $tableFields);

      

+2


source


The values ​​you are inserting must be in quotes, change the line

$sql = $sql.$recordFields[$i];

      



to

$sql = $sql."'".$recordFields[$i]."'";

      

+1


source







All Articles