Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAshish Mehra
Courses Plus Student 340 PointsHow to insert form input in database
I just try myself to insert record in database but i got error
if(isset($_POST['submit'])){
$name = $_POST["name"];
$age = $_POST["Age"];
$city = $_POST["city"];
$img = $_POST["img"];
try{
$insert = $db->query("Insert INTO info values($name,$age,$city,$img)");
$exec->exec($insert);
echo "Record Added";
}catch(Exception $e){
echo "Record not created";
$e->getMessage();
}
}
1 Answer
Simon Coates
28,694 PointsI'm not entirely sure what you're using, because if it's pdo (it looks similar), i think you're using it wrong. The following is a PDO usage of prepared statements (should use these for use provided values regardless of your database connection library). In PDO, running query on a PDO will run the query, whereas for an insert you should run prepare on the PDO object, to retrieve a PDOStatement object. You can then bind params (or bind values) to safely add the values, and call execute on the PDOstatement object. The following is a simple example where $dbh is a PDO.
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
MySQLi has a similiar pattern see http://php.net/manual/en/mysqli.quickstart.prepared-statements.php.
Ashish Mehra
Courses Plus Student 340 Pointsthanks for your answer :-)
Simon Coates
28,694 PointsSimon Coates
28,694 Pointswhat is $exec?