0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PHPからDBにデータを挿入する方法

Last updated at Posted at 2022-03-27

・PHPからDBにデータを挿入する方法
~はじめに~
insert intoでデータを挿入することが可能だが、いたずらされる可能性がある。
そのため、以下の方法でデータを挿入する方が良い。

~推奨方法~
preparebind_paramexecuteを使う。
例)挿入するデータ(カラムの種類)が1つの時

<?php
$db = new mysqli("localhost:8889", "root", "root", "mydb");
$input = "入力値";
$statement = $db->prepare("insert into data(memo) values(?)");
if (!$statement) {
    die($db->error);
}
$statement->bind_param("s", $input);
$return = $statement->execute();
if ($return) {
    echo "データを挿入しました";
} else {
    echo $db->error;
}
?>

補足画像
image.png
※$statement->execute()でデータ挿入の実行

例)挿入するデータ(カラムの種類)が複数の時

<?php
$db = new mysqli("localhost:8889", "root", "root", "mydb");
$input1 = "入力値";
$input2 = 2;
$statement = $db->prepare("insert into data(memo1, memo2) values(?, ?)");
if (!$statement) {
    die($db->error);
}
$statement->bind_param("si", $input1, $input2);
$return = $statement->execute();
if ($return) {
    echo "データを挿入しました";
} else {
    echo $db->error;
}
?>

補足画像
image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?