从窗体将项插入MySQL数据库


Inserting Items into a MySQL Database from Form

通过一个网站上的两个页面,我不打算离开我的家用电脑,我想使用一个表单将项目输入到我电脑上托管的MySQL数据库中。我以前用过几乎相同的东西,但由于某种原因,这个不起作用。我不担心这个或那个的安全性,因为它不会离开我自己的电脑,我只希望它能真正工作。

形式:

<form action='addclothes.php' method='post'><table style="font-family:verdana;font-size:14px;color:#004766;"><tr><td>
Type of clothing:</td><td><select name="type">
<option value="0">---</option>
<option value="dresses">Dress</option>
<option value="tops">Top</option>
<option value="bottoms">Bottom</option>
<option value="shoes">Shoes</option>
<option value="accessories">Accessory</option></select></td></tr>
<tr><td>Name:</td><td><input type="text" name="name"></td></tr>
<tr><td>Path to full image:</td><td><input type="text" name="largeimagepath"></td></tr>
<tr><td>Path to thumbnail:</td><td><input type="text" name="smallimagepath"></td></tr>
<tr><td colspan="2"><center><input type="submit" value="Submit" name="submit"></center></td></tr>
</table></form>

这会发送到addcloths.php,它看起来像这样,封装在html中以保持相同的布局:

<?php
$name = $_POST['name'];
$table = $_POST['type'];
$largepath = $_POST['largeimagepath'];
$thumbpath = $_POST['smallimagepath'];
    $db = mysql_connect("localhost", "root", "******") or die(mysql_error());
    mysql_select_db("Default") or die(mysql_error());
    $query = "INSERT INTO clothes."{$table}" (name, imagepath, thumbimagepath)
 VALUES("{$name}", "{$largepath}", "{$thumbpath}")";
    mysql_query($query) or die(mysql_error()); ?>
<p>Item Added!</p>

不管怎样,它都会进入下一页,只显示"添加了项目"。如果我试图在创建变量后立即回显查询,但该变量也没有显示。

这是错误的:

$query = "INSERT INTO clothes."{$table}" (name, imagepath, thumbimagepath)
            VALUES("{$name}", "{$largepath}", "{$thumbpath}")";

您需要在查询中使用单引号来避免破坏它(您不引用表名;如果它可以是mysql中的保留字,则使用反引号(:

$query = "INSERT INTO clothes.`{$table}` (name, imagepath, thumbimagepath)
            VALUES('{$name}', '{$largepath}', '{$thumbpath}')";

还要注意,安全/sql注入不仅仅是为了保护您免受恶意人员的攻击;如果您没有正确准备数据以在sql查询中使用,即使是您自己输入的有效数据,如果名称包含'字符(例如O'Neill…(,也可能会破坏查询/应用程序。

所以安全性总是很重要的,这就是为什么你应该切换到PDO(或mysqli(和准备好的语句。除此之外,不推荐使用mysql_*函数。

最后一条评论:如果你向外界开放你的网站,任何准备或转义都不会确保查询中的表名安全;您需要对照允许的表名列表进行检查,以避免sql注入。

<?php
    $name = $_POST['name'];
    $table = $_POST['type'];
    $largepath = $_POST['largeimagepath'];
    $smallpath = $_POST['smallimagepath'];
    $name = htmlentities($name);
    $table = htmlentities($table);
    $largepath = htmlentities($largepath);
    $smallpath = htmlentities($smallpath);
    $connection = new PDO('mysql:host=localhost;dbname=Default','root','*****');
    $query = $connection->prepare('INSERT INTO :table (name,imagepath,thumbimagepath) VALUES (:name,:image,:thumb)';
    $query->bindParam(':table', $table);
    $query->bindParam(':name', $name);
    $query->bindParam(':image',$largepath);
    $query->bindParam(':thumb',$smallpath);
    $query->execute();
    if($query->rowCount()) {
        echo "Inserted correctly";
    } else {
        echo "Failure inserting";
    }
?>

正如其他人所说,你真的不应该允许别人通过表单输入表名