This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center
                            
                        
                    
                
                                6年前关闭。
            
                    
通过网站上我不打算离开家用计算机的两个页面,我想使用一种表单将项目输入到我的计算机上还托管的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>


它将发送到addclothes.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 - 从表单将项目插入MySQL数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15549587/

10-14 14:55
查看更多