连续更新多个列没有错误但不更新表

时间:2014-03-22 18:00:59

标签: php mysqli

我已经尝试过这段代码,但它没有更新我的桌子,有人能告诉我哪里出错了吗?

<?php
$TeamNow = $teams->TeamID->CurrentValue;
$GK1  = $teams->Keeper1->CurrentValue;
$GK2  = $teams->Keeper2->CurrentValue;
$link = mysqli_connect("localhost", "root", "", "soccer_team");
if (!$link) {
    printf("Connection to the database failed. Error: %s\n", mysqli_connect_error());
    exit();
} else {
/* update rows */
mysqli_query($link, "UPDATE teams SET ('keeper1_price', 'Keeper2_Price') VALUES ($GK1,$GK2) WHERE TeamID = $TeamNow");
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link));
/* close connection */
?> <script>  alert ( <?php echo 'Updated Team No:'; echo $TeamNow; ?>); </script>
<?php
mysqli_close($link);
}
?> 

1 个答案:

答案 0 :(得分:0)

您的主要问题是当前的SQL查询对于UPDATE查询是错误的,应该是:

UPDATE `teams` SET `keeper1_price` = '$GK1', `Keeper2_Price` = '$GK2' WHERE `TeamID` = '$TeamNow'

对于列和表名,您应该只使用反向标记,在大多数情况下不需要它,对于字段,如果它们是字符串,建议使用单引号,但是因为您使用MySQLi,所以应该高度使用准备好语句以防止SQL注入,这是一个例子:

<?php
// Your database info
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'soccer_team';

$con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if ($con->connect_error)
{
    die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}

// Here we prepare your query and make sure it is alright
$sql = "UPDATE `teams` SET `keeper1_price` = ?, `Keeper2_Price` = ? WHERE `TeamID` = ?";
if (!$stmt = $con->prepare($sql))
{
    die('Query failed: (' . $con->errno . ') ' . $con->error);
}

// Here we define the field types with 'ddi' which means double, double, integer
// and also set the fields values
if (!$stmt->bind_param('ddi', $GK1, $GK2, $TeamNow))
{
    die('Binding parameters failed: (' . $stmt->errno . ') ' . $stmt->error);
}

// Now we finally execute the data to update it to the database
// and if it fails we will know
if (!$stmt->execute())
{
    die('Execute failed: (' . $stmt->errno . ') ' . $stmt->error);
}

printf("Affected rows (UPDATE): %d\n", $stmt->affected_rows);
$con->close();

You can read more about bind_param and it's parameters here.

相关问题