猿问

仅执行插入时无法更新城市

<?php

session_start();

include_once 'DBconfig.php';

extract($_GET);

$CityName = $_POST['CityName'];


if (isset($CityID))

{

    $sql = "UPDATE city SET CityName = '$CityName', Modified = NOW() WHERE city.CityID = $CityID;";

}

else

{

    $sql = "INSERT INTO city (CityID, CityName, Created, Modified) VALUES (NULL, '$CityName', NOW(), NOW());";

}


$result = mysqli_query($con, $sql);

if ($result)

{

    header('location: ListCity.php');

}

else

{

    header('location: AddEditCity.php');

}

?>

仅执行插入块更新不起作用 $CityID 变量来自提取函数,因此没有命名约定问题无法解决它请帮助


MMMHUHU
浏览 78回答 1
1回答

哈士奇WWW

您正在从 中提取$_GET(这始终是要避免的),然后$CityName从 中获取$_POST。这是不一致的,因为请求不能同时是 GET 和 POST。它肯定必须是 POST 请求,否则插入根本无法工作。正如所评论的,您应该使用准备好的语句来避免 SQL 注入攻击:<?phpsession_start();include_once 'DBconfig.php';$CityName = $_REQUEST['CityName'];&nbsp; &nbsp;&nbsp;if (isset($_REQUEST['CityID'])){&nbsp; &nbsp; $CityID = $_REQUEST['CityID'];&nbsp; &nbsp; $sql = "UPDATE city SET CityName = ?, Modified = NOW() WHERE city.CityID = ?";&nbsp; &nbsp; $stmt = mysqli_prepare($con, $sql);&nbsp; &nbsp; mysqli_stmt_bind_param($stmt, "si", $CityName, $CityID);}else{&nbsp; &nbsp; $sql = "INSERT INTO city (CityID, CityName, Created, Modified) VALUES (NULL, ?, NOW(), NOW())";&nbsp; &nbsp; $stmt = mysqli_prepare($con, $sql);&nbsp; &nbsp; mysqli_stmt_bind_param($stmt, "s", $CityName);}$result = mysqli_stmt_execute($stmt);if ($result){&nbsp; &nbsp; header('location: ListCity.php');}else{&nbsp; &nbsp; header('location: AddEditCity.php');}
随时随地看视频慕课网APP
我要回答