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);
}
$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);
The values you insert must be in quotes change the line
$sql = $sql.$recordFields[$i];
to
$sql = $sql."'".$recordFields[$i]."'";