0
1

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 5 years have passed since last update.

MySQLでカラム名が変えられない

0
Posted at

ドットインストールでPHP学習入門を取り組んでいる際...

index.phpにて

  // ユーザーをDBに登録してブラウザに user add!!! と出力したい
  $db->exec("insert into users (name, score) values ('tanaka', 99)");
  echo "user add!!!";

よっしゃ、これでOKなはずと思ったがブラウザで以下エラーが表示される:fearful:

エラーSQLSTATE[42S22]: Column not found: 1054 Unknown column 'score' in 'field list'

原因

ターミナルでusersテーブルを見ると、scoreで作ったはずがscireと作っていました。

mysql> desc users;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(255) | YES  |     | NULL    |                |
| scire | int(11)      | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

ささっとググり、ターミナルでカラム名を変更るためにコマンドを叩く

alter table users change column scire score;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

あれなんでエラーが出るんだろう.....

対策

カラム名を変更するときは型も指定しなければいけない
先ほどのコマンドの最後にintを追加して再度実行すると、無事DBにデータも登録出来てブラウザにも期待通りの出力が出来ました:v_tone2:

mysql> alter table users change column scire score int;
Query OK, 0 rows affected (0.12 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc users;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(255) | YES  |     | NULL    |                |
| score | int(11)      | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?