I've created a function to insert data different from displaying data. Then I get an error. Unknown column '$prod_name' in 'field list'. Please tell me any right suggestions because im a beginner in pdo. thanks
here is my code:
<?php
function run_db($sqlcom){
$con = new PDO('mysql:host=localhost; dbname=product', 'root', '');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->prepare($sqlcom);
$stmt->execute();
return $stmt;
}
function insertData($sqlcom)
{
$con = new PDO('mysql:host=localhost; dbname=product', 'root', '');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->prepare($sqlcom);
$stmt->execute();
return $stmt;
}
if(isset($_POST['btn-insert'])){
$prodname = $_POST['prod_name'];
$prodsupp = $_POST['prod_supplier'];
$prodprice = $_POST['prod_price'];
try{
$stmt = insertData('INSERT INTO tbl_product(prod_name, prod_supplier, prod_price)VALUES($prodname, $prodsupp, $prodprice)');
}catch(Exception $e){
die('error : ' . $e->getMessage());
}
}
?>
<html>
<head><title></title></head>
<body>
<table cellpadding="4" cellspacing="2" border='1'>
<tr>
<th>Product ID</th>
<th>Product NAME</th>
<th>Product SUPPLIER</th>
<th>Product PRICE</th>
</tr>
<?php $stmt = run_db('SELECT * FROM tbl_product'); while($product = $stmt->fetch(PDO::FETCH_OBJ)) { ?>
<tr>
<td><?php echo $product->prod_id; ?></td>
<td><?php echo $product->prod_name; ?></td>
<td><?php echo $product->prod_supplier; ?></td>
<td><?php echo $product->prod_price; ?></td>
</tr>
<?php } ?>
</table>
<br>
<br>
<form action="" method="post">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td>Product name:</td>
<td><input type="text" name="prod_name"></td>
</tr>
<tr>
<td>Product supplier:</td>
<td><input type="text" name="prod_supplier"></td>
</tr>
<tr>
<td>Product Price:</td>
<td><input type="text" name="prod_price"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="btn-insert" value="INSERT"></td>
</tr>
</table>
</form>
</body>
</html>