发布变量值而不是变量名称

时间:2013-02-02 14:19:34

标签: php html mysql sql database

我试图从文本框代码中获取条目以转到php表单并让php表单将其发送到数据库。我遇到的问题是发布文本框值而不是发布$ code。我使用的是mysql和php。

PHP:

<?
if( $_POST )
{
$username="***";
$password="***";
    $con = mysql_connect("***",$username,$password);

    if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }

    mysql_select_db("inmoti6_mysite", $con);

    $code = $_POST['code'];


    $code = htmlspecialchars($code); 


    $query = 'INSERT INTO `storycodes`.`storycodes` (`code`) VALUES ("$code");';


    mysql_query($query);

    echo "<h2>Thank you for your Comment!</h2>";

    mysql_close($con);
}
?>

怀疑这是个问题,但这里是html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Database</title>
</head>

<body>
<form id="form1" name="form1" method="post" action="/scripts/database2.php">
  <label>Code:
  <input name="code" type="text" id="code" value="" size="45" />
</label>
  <p>
    <label>
    <input type="submit" name="submit" id="submit" value="Submit" />
    </label>
  </p>
</form>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

您需要使用双引号来在字符串中识别变量,因此请更改:

$query = 'INSERT INTO `storycodes`.`storycodes` (`code`) VALUES ("$code");';

$query = "INSERT INTO `storycodes`.`storycodes` (`code`) VALUES ('$code');";

你也有一个SQL注入问题;我建议您使用预准备语句和绑定变量切换到PDO(或mysqli)。在将变量插入数据库之前,至少应该对变量使用mysql_real_escape_string,但正如您在手册中看到的那样,mysql_*函数已被弃用。

答案 1 :(得分:0)

它没有发布$ code,你使用$ code作为值而不是变量。问题与报价有关。

$query = "INSERT INTO `storycodes`.`storycodes` (`code`) VALUES (\"$code\");";

尝试这个。

相关问题