Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!