使用PHP更新MySQL数据库

时间:2013-04-24 20:42:07

标签: php mysql

基本上我正在尝试使用PHP来更新MySQL数据库,我正在用HTML表单进行测试。

我打算在Android应用程序中使用它,这样就可以从中获取值,但目前我只是使用HTML表单进行测试来测试PHP代码。当我使用HTML表单进行测试时,当前没有更新相应的数据。

我的代码导致了什么问题?

PHP代码:

/*
* Following code will create a new product row
* All player details are read from HTTP Post Request
*/

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['PlayerID']) && isset($_POST['Score']) && isset($_POST['LastHolePlayed'])&&     
isset($_POST['Overall'])) {

$playerid = $_POST['PlayerID'];
$score = $_POST['Score'];
$lastholeplayed = $_POST['LastHolePlayed'];
$overall = $_POST['Overall'];

// include db connect class
require('db_connection.php');



// mysql inserting a new row
$result = mysql_query("UPDATE `week1` SET Score = `$score`, LastHolePlayed = `$lastholeplayed`, 

Overall` = $overall` WHERE PlayerID = `$playerid`");


// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Player successfully added.";

    // echoing JSON response
    echo json_encode($response);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "An error occurred.";

    // echoing JSON response
    echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}

html代码:

<form action="http://localhost/realdeal/updateplayer.php" method="POST">
PlayerID <input type="text" id='PlayerID' name='PlayerID'><br/><br/>
Score <input type="text" id='Score' name='Score'><br/><br/>
LastHolePlayed <input type="text" id='LastHolePlayed' name='LastHolePlayed'><br/><br/>
Overall <input type="text" id='Overall' name='Overall'><br/><br/>

    &nbsp;  <input type="submit" value="submit">

</form>

3 个答案:

答案 0 :(得分:2)

将您的查询更改为:

$result = mysql_query("UPDATE `week1` SET `Score` = '$score', `LastHolePlayed` = '$lastholeplayed', `Overall` = '$overall' WHERE `PlayerID` = '$playerid'");

答案 1 :(得分:0)

您的查询分隔符需要更正:

$result = mysql_query("UPDATE `week1` SET Score = '$score', `LastHolePlayed` = '$lastholeplayed', `Overall` = '$overall' WHERE `PlayerID` = '$playerid'");

注意围绕列和表名的反引号(`)和值周围的单引号(')。

此外,在调试查询时,请始终检查MySQL错误:

$result mysql_query(...) or die("Query failed: " . mysql_error() );

最后,您应该知道您的查询会让您对SQL注入攻击持开放态度。在将输入数据包含在查询中之前,请务必清理输入数据。

答案 2 :(得分:0)

您的sql语句错误。你可以像上面所说的那样写,或者你可以直接写下没有任何撇号的声明 - $ result = mysql_query(“UPDATE week1 SET Score = $ score,LastHolePlayed = $ lastholeplayed,Overall = $ total WHERE PlayerID = $ playerid”);

此外,你能解释一下“适当的数据没有被更新”是什么意思吗?如果你给出/陈述你得到的错误,那就更清楚了。