我正在尝试从我创建的简单html表单中将记录添加到数据库中。我一直在收到这个错误:
连接成功错误:您的SQL语法中有错误;检查与MySQL服务器版本对应的手册,以便在第1行的')'附近使用正确的语法
连接成功但sql语句出错了,我无法发现错误。
这是表格
<form action="addplayer.php"method "post"/>
<p> id: <input type="text" name="playerid"/></p>
<p> Name: <input type="text" name="name"/></p>
<p> Age: <input type="text" name="age"/></p>
<p> Position: <input type="text" name="position"/></p>
<p> Nationality: <input type="text" name="nationality"/></p>
<input type="submit" value="submit"/>
这是连接
<?php
define('DB_NAME', 'syokimaufc');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die ('could not connect: '. mysql_error());
}
$db_selected= mysql_select_db(DB_NAME, $link);
if (!$db_selected){
die('can\'t use' . DB_NAME .': ' . mysql_error());
}
echo 'connected successfully';
实施
<?php
require 'connection.php';
$id = filter_input(INPUT_POST, 'playerid');
$name = filter_input(INPUT_POST, 'name');
$age = filter_input(INPUT_POST, 'age');
$position = filter_input(INPUT_POST, 'position');
$nationality = filter_input(INPUT_POST, 'nationality');
$sql = "INSERT INTO players (playerid,Name,Age,Position,Nationslity) VALUES ('$id','$name','$age','$position',$nationality)";
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
答案 0 :(得分:1)
变化:
$sql = "INSERT INTO players (playerid,Name,Age,Position,Nationslity) VALUES ('$id','$name','$age','$position',$nationality)";
要:
$sql = "INSERT INTO players (playerid,Name,Age,Position,Nationality) VALUES ('$id','$name','$age','$position','$nationality')";
<强>更新强> 正如Jeff Puckett II在下面的评论部分中正确指出的那样,我匆匆给出了我的初步答案,应该提到你通过不清理数据来打开SQL注入和其他令人讨厌的问题。
为了更安全地做事,请改变:
$sql = "INSERT INTO players (playerid,Name,Age,Position,Nationslity) VALUES ('$id','$name','$age','$position',$nationality)";
要:
$_id = mysql_real_escape_string( $id );
$_name = mysql_real_escape_string( $name );
$_age = mysql_real_escape_string( $age );
$_position = mysql_real_escape_string( $position );
$_nationality = mysql_real_escape_string( $nationality );
$sql = "INSERT INTO players ( playerid, Name, Age, Position, Nationality ) VALUES ( '$_id', '$_name', '$_age', '$_position', '$_nationality' )";