i try to insert data into mysql database. i created PDO connection with mysql and now i want to insert data into database with oop. i tried a million ways but without result.
could anyone please help me?
include "DB.php"; class DataOperation extends Dbh { public function insert_record($table, $fields) { $insert = ""; $insert. = "INSERT INTO ".$table; $insert. = " (".implode(",", array_keys($fields)). ") VALUES "; $insert. = "('".implode("','", array_values($fields)). "')"; $this - > pdo - > prepare($insert); } } $obj = new DataOperation; if (isset($_POST["create"])) { $myArray = array( "firstname" => $_POST['firstname'], "lastname" => $_POST['lastname'], "email" => $_POST['email'] ); $obj - > insert_record("Users", $myArray); }
<form action="insert.php" method="POST"> <input type="text" class="inputs" name="firstname"> <input type="text" name="lastname"> <input type="text" name="email"> <button type="submit" name="create">Sign Up</button> </form>
You're preparing the statement, but you should be executing it instead.
However, your code is subject to SQL injection, you should placeholders in the query.
public function insert_record($table,$fields){
$field_names = array_keys($fields);
$placeholders = array_map(function($field) { return ":$field"; }, $field_names );
$insert = "";
$insert .= "INSERT INTO " . $table;
$insert .= " (" . implode(",", $field_names) . ") VALUES ";
$insert .= "('" . implode(",", $placholders) . ")";
$stmt = $this->pdo-> prepare($insert);
$stmt->execute($fields);
}
Hi this is my working code. Try this it should work 100%
$sql="INSERT INTO users(firstName,password,email,lastName,image)VALUES(:firstName,:password,:email,:lastName,:image)";
$stmt = $db->prepare($sql1);
$stmt->bindParam("firstName", $firstName,PDO::PARAM_STR);
$password=hash('sha256',$password);
$stmt->bindParam("password", $password,PDO::PARAM_STR);
$stmt->bindParam("email", $email,PDO::PARAM_STR);
$stmt->bindParam("lastName", $lastName,PDO::PARAM_STR);
$stmt->bindParam("image",$imgfile,PDO::PARAM_STR);
$stmt->execute();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.