0

I'm trying to write code to insert new items into a database.

if(isset($_POST['btnAddVeg'])){

$addVegType = $_POST['txtAddVegType'];
$AddVegName = $_POST['txtAddVegName'];

$insertQuery = 'insert into vegetables (vegetable_type, vegetable_id)     values ("$addVegType", "$AddVegName")';

$statement2 = $db->prepare($insertQuery);
$statement2->execute();
$results2 = $statement2->fetchAll();
$statement2->closeCursor();
foreach($results2 as $result2){

echo "<table border = '0'><th>ID</th><th>Type</th><th>Name</th>    <tr><td>".$result2['vegetable_id'].'</td>';
echo "<td>".$result2['vegetable_type'].'</td>';
echo "<td>".$result2['vegetable_name'].'</td></tr></table>';

}

I get this error:

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error in /vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/task9.php(54): PDOStatement->fetchAll() #1 {main} thrown in vvvvvvvvvvv/task9.php on line 54

Probably ridiculously easy but what am I missing?

Thank you

dawie
  • 3
  • 3

1 Answers1

0

Executing an INSERT statement doesn't return a resultset object.

Just remove the line that does the statement2->fetchAll.

And remove the lines that reference $results2.

We would need that if we were executing a SELECT statement, to get a resultset (a set of rows) returned.


Also important to point out: the code is vulnerable to SQL Injection.

https://xkcd.com/327/

https://www.owasp.org/index.php/SQL_Injection

spencer7593
  • 106,611
  • 15
  • 112
  • 140