ドットインストールでPHP学習入門を取り組んでいる際...
index.phpにて
// ユーザーをDBに登録してブラウザに user add!!! と出力したい
$db->exec("insert into users (name, score) values ('tanaka', 99)");
echo "user add!!!";
よっしゃ、これでOKなはずと思ったがブラウザで以下エラーが表示される![]()
エラー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にデータも登録出来てブラウザにも期待通りの出力が出来ました![]()
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)