I'm trying to insert data into db from php
public function writeIntoDB($fields, $values, $table){
$query = $this->composeInsertQuery($fields, $values, $table);
if (($this->conn->query($query)) === TRUE){
...
}
echo "Error: " . query . "<br>" . $this->conn->error;
}
I wrote this function but the code inside the if statement is never executed, I get only the echo without error because $this->conn->error
return null. The other function called is composeInsertQuery(...):
private function composeInsertQuery($fields, $values, $table){
$query = "INSERT INTO " . $table . " (id,";
foreach ($fields as $value) {
$query .= $value . ",";
}
$query = substr($query, 0, -1) . ") VALUES ('$this->key',";
foreach ($values as $value) {
$query .= "'$value',";
}
$query = substr($query, 0, -1) . ")";
return $query;
}
It compose the query in a modular way because I need to have different number of fields every time. However this is not the problem because I tried to print the composed query and assign it directly to a variable, like this:
public function writeIntoDB($fields, $values, $table){
$query = "INSERT INTO ... all the query ....";
if (($this->conn->query($query)) === TRUE){
...
}
echo "Error: " . query . "<br>" . $this->conn->error;
}
But even in this case I got the echo with $this->conn->error
always empty string. Of course the same query works correctly from terminal.
$this->conn->query
return NULL and this is weird according to PHP documentation:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN > queries mysqli_query() will return a mysqli_result object. For other > successful queries mysqli_query() will return TRUE.
Delete the id field in composeInsertQuery()