Insert into table with prepared statement

2020-04-21 08:13发布

I'm trying to insert data from a form into a database using PHP and Mysqli but I can't get it working! My database has 4 fields: DATE, TITLE, CONTENT, ID. The ID field is auto-increment.

I've checked the connection and that's working fine. I've also echoed the form field values and the $blogDate variable I created, they're all fine too.

Here's my prepared statement:

if ($newBlog = $mysqli->prepare('INSERT INTO Blog VALUES ($blogDate, $_POST["bTitle"], $_POST["bContent"])')) {
  $newBlog->execute();
  $newBlog->close();
}

It's just not inserting the values into my table.

标签: php mysqli
3条回答
祖国的老花朵
2楼-- · 2020-04-21 08:23

Since you are aware about prepared statement:

$newBlog = $mysqli->prepare('INSERT INTO Blog (`dateCol`, `titleCol`, `contentCol`) VALUES (?, ?, ?)');
$newBlog->bind_param( 'sss', $blogDate, $_POST["bTitle"], $_POST["bContent"] );
$newBlog->execute();
$newBlog->close();
查看更多
叛逆
3楼-- · 2020-04-21 08:24

You are generating SQL containing strings that are not quoted or escaped.

Don't insert the data directly into the SQL string, use placeholders (?) and then bind the parameters before executing.

$query = "INSERT INTO Blog VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $blogDate, $_POST["bTitle"], $_POST["bContent"]);
$stmt->execute();
查看更多
祖国的老花朵
4楼-- · 2020-04-21 08:28

since you are using auto increment field you need to specify column name and then values try this code

$query = "INSERT INTO Blog (colname_1,colname_2,colname_3) VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $blogDate, $_POST["bTitle"], $_POST["bContent"]);
$stmt->execute();
查看更多
登录 后发表回答