Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
I need some help to find an error

I created a file with some useful PHP functions to operate with SQL databases but I have a problem with the code that inserts a record in a SQL table. When I try to execute this code it appear this:

Fatal error: Uncaught 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} thrown in C:\xampp\htdocs\iterations_php_mysql.php on line 118

This is the function ($link is the link of the host get with $link = mysqli_connect($host, $username);, $table is the table name, $tableFields is an array that contain the names of the fields, $recordFields is an array that contains 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);
}
about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

$n = $tableFields

So I guess $tableFields is an array?

If so, then it makes no sense to do the following with an array:

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

Because you can't do arithmetic on an array like that. It would work better like this:

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

Note you'd have to subtract 2, because arrays start at index 0.

But I have a better suggestion to simplify your 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);
about 4 years ago · Santiago Trujillo Denunciar

0

The values you insert must be in quotes change the line

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

to

$sql = $sql."'".$recordFields[$i]."'";
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda