1
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+MySQL 接続・テーブル作成・クエリ実行

Posted at

PHP+MySQL 接続・テーブル作成・クエリ実行

備忘録のために、メモしてます。

MySQLへの接続

mysqli_connect.php
$link = mysqli_connect($hostname , $username, $password, $databases);
if (!$link) {
    echo '接続失敗です。';
    return;
}

テーブル作成

create_table.php
$query = <<<EOT
CREATE TABLE users(
    id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    age INTEGER(255) NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)DEFAULT CHARACTER SET=utf8mb4;
EOT;

$result = mysqli_query($link, $query);
    if($result){
        echo 'テーブルを作成したよー'.PHP_EOL;
    }else{
        echo 'errer:' . mysqli_error($link) . PHP_EOL;
    }
}

行の追加

createRow.php
$user = [
    'name' => 'hoge',
    'age' => 27
];

$sql = <<<EOL
INSERT INTO users(
    name,
    age
)VALUES(
    "{$user['name']}",
    "{$user['age']}"
)
EOL;

$result = mysqli_query($link, $sql);
if( !$result ){
    error_log('Error: fail to create user');
    error_log('error:'. mysqli_error($link));
}

mysqli_free_result($result);
mysqli_close($link);

データの取得

getTableData.php
$sql = "SELECT * FROM users";

$result = mysqli_query($link, $sql);
$users = [];
    while( $row = mysqli_fetch_assoc($result)) {
        $user = array(
            'name' => $row['name'],
            'age' => $row['age']
        );
        $users[] = $user;
    }

mysqli_free_result($result);
mysqli_close($link);

1
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
1
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?