我尝试将数据插入mysql数据库。 我用mysql创建了PDO连接,现在我想用oop将数据插入数据库。 我尝试了一百万种方法,但没有结果。
有人可以帮我吗?
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>
答案 0 :(得分:1)
嗨,这是我的工作代码。试试这个应该可以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();
答案 1 :(得分:0)
您正在准备该语句,但是应该执行它。
但是,您的代码需要进行SQL注入,因此您应该在查询中使用占位符。
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);
}