2016-04-06 8 views
0

データベース行に保存しようとしています。しかし、私はいつもエラーになる。PHPを使用してデータベースに行を挿入できません

私のコードは次のとおりです。$connection

function save_activation_key($connection, $username, $key) { 
    $date = time(); 
    $is_used = 0; 
    $query = "INSERT INTO account_activation_key ( key, date, is_used) 
    VALUES ( '" . $username . "'," 
       . " '" . $date . "'," 
       . " '" . $is_used . "')"; 
    $retval = mysql_query($query, $connection); 
    echo $retval; 
    $retval = mysql_query($query, $connection); 
    if(! $retval) 
    { 
     die('Could not enter data: ' . mysql_error()); 
    }  
} 

は、データベースへの有効な接続です。

データベースの構造:私は私のコードを呼び出すとき

id : int 
key: varcha(45) 
date: date 
is_used: tinyint(1) 

私はエラーを取得する:

Could not enter data: 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 'key, date, is_used) VALUES ( 'uzivatelsky_jmeno', '1459971829', '0')' at line 1 

問題がありますか?

ヘルプ

+0

あなたは 'クエリ文をecho'し、それが有効であるかどうかを確認することはできますか? – Maximus2012

+0

[mysql_'データベース拡張](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)を使用しないでください。 は廃止予定です PHPを学んでいるだけの方は、 'PDO'や' mysqli_'データベースの拡張機能を学んでください。 [ここでは使い方を決めるのに役立ちます](http://stackoverflow.com/questions)/12859942/why-shouldnt-i-use-mysql-functions-in-php) – RiggsFolly

答えて

3

keyはMYSQL予約語であり、実際には列名として使用しないでください。

MYSQL Reserved Words List can be found here https://dev.mysql.com/doc/refman/5.7/en/keywords.html

しかし、これらの列名をバッククォートで囲むと、それを取り除くことができます。

次のようにクエリ文字列の連結を簡素化することもできます。これにより、デバッグが非常に簡単になります。

function save_activation_key($connection, $username, $key) { 
    $date = time(); 
    $is_used = 0; 
    $query = "INSERT INTO `account_activation_key` 
        ( `key`, `date`, `is_used`) 
       VALUES ('$username', '$date', '$is_used')"; 

    $retval = mysql_query($query, $connection); 
    echo $retval; 
    $retval = mysql_query($query, $connection); 
    if(! $retval) 
    { 
     die('Could not enter data: ' . mysql_error()); 
    }  
} 

BIG NOTE

Please dont use the mysql_ database extension , it is deprecated (gone for ever in PHP7) Which means this code will never run when all that is available is PHP7 or greater. Especially if you are just learning PHP, spend your energies learning the PDO or mysqli_ database extensions, and here is some help to decide which to use

+0

'key'は' date'ではなくSmokeyです。 –

+0

私はあなたがそのコメントでピッチを知っていることを知っていました。 Arternoon Ralph @ Fred-ii- – RiggsFolly

+0

* Afternoon Smokey * –

-2

のおかげで、おそらくあなたのクエリは、あなたの文字列 のように、あなたは文字列として整数を与えている場所でエラーが含まれています「」。$ユーザ名。「『」 。「』」。$ "、" "" $ is_used "'

は次のようになります: '"。$ username。 "'、"。 。 $ date。 」、 ""。$ is_used。 "

整数は" ' "シングルqoutesで

ことshould'ntおそらくこれは間違いです!