使用PHP将信息更新到MySQL数据库

时间:2012-10-24 20:47:51

标签: php mysql database web

在我的代码中,我正在尝试使用表单中可修改文本字段的值更新数据库。但是,当运行查询时,它会擦除​​与用户尝试编辑的记录相关的所有字段(将它们变为“”)。任何人都可以看到为什么吗?

<?php
$dbuser = 'test';
$dbpass = 'test';
$host = '127.0.0.1';
$db = 'test';
mysql_connect($host, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());

$result = mysql_query("SELECT * from characters");
$id = $_REQUEST['combo'];
while($row = mysql_fetch_array($result))
{
    if($id == $row['_Key'])
    {
        echo "<form action=\"webpagetests.php\" method=\'post\'>";
        echo "<strong>Player ID:</strong>    " . $row['_Key'] . "</br>";
        echo "<strong>Steam Name:</strong>   " . $row['_SteamName'] . "</br>";
        echo "<strong>Steam ID:</strong>     " . $row['_SteamID'] . "</br></br>";

        echo "Name: </br><input name = \"name\" type=\"text\" size=\"25\" value=\"" . $row['_Name'] . "\"></br></br>";
        echo "Cash: </br><input name = \"cash\" type=\"text\" size=\"25\" value=\"" . $row['_Cash'] . "\"></br></br>";
        echo "Flags: </br><input name = \"flags\" type=\"text\" size=\"25\" value=\"" . $row['_Flags'] . "\"></br></br>";
        echo "Gender:</br> <input name = \"gender\" type=\"text\" size=\"25\" value=\"" . $row['_Gender'] . "\"></br></br>";
        echo "Model:</br> <input name = \"model\" type=\"text\" size=\"50\" value=\"" . $row['_Model'] . "\"></br></br>";
        echo "Faction: </br><input name = \"faction\" type=\"text\" size=\"25\" value=\"" . $row['_Faction'] . "\"></br></br></br>";
        echo "Recognised Names: </br><input name = \"names\" type=\"text\" size=\"50\" value=\"" . $row['_RecognisedNames'] . "\"</br>";
        echo "<input name=\"submit2\" type=\"submit\" value=\"Update\" />";
        echo "</form>";
    }
}
if (isset($_POST['submit2'])) 
{
    //$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
    $name = "Test";
    $cash = (int)$_POST['cash'];
    $flags = mysql_real_escape_string(htmlspecialchars($_POST['flags']));
    $gender = mysql_real_escape_string(htmlspecialchars($_POST['gender']));
    $model = mysql_real_escape_string(htmlspecialchars($_POST['model']));
    $faction = mysql_real_escape_string(htmlspecialchars($_POST['faction']));
    $names = mysql_real_escape_string(htmlspecialchars($_POST['names']));

    mysql_query("UPDATE  `test`.`characters` SET  `_Name` =  '$name',
    `_Cash` =  '$cash',
    `_Model` =  '$model',
    `_Flags` =  '$flags',
    `_Gender` =  '$gender',
    `_Faction` =  '$faction',
    `_RecognisedNames` =  '$names' 
    WHERE  `characters`.`_Key` ='$id'") or die(mysql_error());
    echo '<META HTTP-EQUIV="Refresh" Content="0; URL=webpagetest.php">'; 
}?>

1 个答案:

答案 0 :(得分:0)

1)select语句中没有where子句,因此整个表从DB传输到PHP脚本。添加:

$id = mysql_real_escape_string($id);
$result = mysql_query("select * from characters where _Key = '$id'");

提高性能和带宽使用率。更好的是,使用mysqli,您可以使用预备语句。

2)我没有看到表单返回时设置$id的位置,所以这也可能是个问题。