无法将字段记录到数据库中(php,SQL)

时间:2014-07-29 18:47:18

标签: php mysql sql

我正在尝试从HTML网站获取用户输入的表单并将信息发送到SQL数据库。我能够在提交后打印出变量,所以我至少知道变量设置正确。所以我必须假设我的代码将内容发送到数据库是错误的。

以下是代码:

//Taking variables from HTML input
if (isset($_POST['group'])) {
    $group = $_POST['group'];
} else {
    echo $error;  return;
}
if (isset($_POST['game'])) {
    $game = $_POST['game'];
} else {
    echo $error;  return;
}
if (isset($_POST['platform'])) {
    $platform = $_POST['platform'];
} else {
    echo $error;  return;
}
if (isset($_POST['player'])) {
    $player = $_POST['player'];
} else {
    echo $error;  return;
}
if (isset($_POST['play'])) {
    $play = $_POST['play'];
} else {
    echo $error;  return;
}
if (isset($_POST['timezone'])) {
    $timezone = $_POST['timezone'];
} else {
    echo $error;  return;
}
$error = 0;
//Retrieving Databse
try {
    //userID and password is defined, just hiding it here
    $dbh = new PDO("mysql:host=localhost;dbname=userID", "userID", "password");
} catch (Exception $ex) {
    die("<p>($e->getMessage())</p></body></html>)");
}
//Inputting content into MySQL
$command = "INSERT INTO teams ( group, game, platform, player, play, timezone ) 
            VALUES ( '$group','$game','$platform','$player','$play','$timezone')";
$stmt = $dbh -> prepare($command);
if ( ! $stmt->execute() ) {
    $error = "<b>ERROR:</b> Could not record fields";  echo $error;  return;
}

我不确定我哪里出错了,可能是最小的东西,或者是我忽略的东西。

先谢谢你们的帮助,伙计们!

1 个答案:

答案 0 :(得分:1)

这就是我为我的作业做的事情: 连接MySQL(注意我没有任何 mysql:host = ):

$mysqli = new mysqli("localhost", "username", "pass", "database_name");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

然后在您的代码中,从POST初始化变量标签时,转义字符串。这将为您提供针对SQL注入的一些保护:

$Name = $mysqli->real_escape_string($_POST["txtName"]);
$Street = $mysqli->real_escape_string($_POST["txtStreet"]);
$City = $mysqli->real_escape_string($_POST["txtCity"]); 

现在,准备一个SQL代码来插入你的参数:

$input = $mysqli->query("INSERT INTO customer (MembershipID, Name, Street, City, PostCode, Email, Password, DateJoin, Salt) 
    VALUES ('". $MembershipID."','".$Name."','".$Street."','". $City."','". $PostCode."','". $Email."','". $Password."','". $DateJoined."','". $Salt."')");

我希望它有所帮助,祝你好运。