使用switch case, PHP函数以数组作为参数更新MySQL数据库


using switch case the PHP function with array as parameters which updates the MySQL db

HTML CODE:-

<form action="run.php" method="post">
Ambulance ID:<input type="text" name="amb_id">
Select the any of the point and submit:
<input type="radio" name="tposition" value="1">t1  (1 km away from the signal)
<input type="radio" name="tposition" value="2">t2 (before 500 mtrs point) 
<input type="radio" name="tposition" value="3">a3 (500 Mtr from signal)
<input type="radio" name="tposition" value="4">t3 (before signal, after 500 mtrs)
<input type="submit" value="Submit">
</form>
PHP代码

: -

<?php
$ambid = $_POST['amb_id'];
//lattitude array
$lat=array(13.092593,13.092781,13.093126,13.09344,13.093889,13.094349,13.094882,13.095485,13.096575);
//longitude array
$lon=array(77.586415,77.585009,77.583454,77.58251,77.581598,77.580793,77.580096,77.57946,77.578486);
//connect to the db
$con = mysql_connect('localhost', 'root','');
mysql_select_db('traffic', $con);
//check the radio button
  if (isset($_POST['tposition'])) {
     switch($_POST['tposition']) {
    case 1:
        updateDb($lat[0],$lon[0]);
        break;
    case 2:
        updateDb($lat[1],$lon[1]);
        break;
        }
}
    else { echo "Please select any of the tpositon radio button"; }
function updateDb($lati,$longi)
{
$query = "UPDATE emergency SET e_latitude=$lati,e_longitude=$longi WHERE amb_id=$ambid ";
$res= mysql_query($query) or die("Unable to update the latlong values because : " . mysql_error());
}
mysql_close($con);
?>

在运行上面的脚本时,我得到一个错误"无法更新latlong值,因为:您的SQL语法有错误;查看与MySQL服务器版本对应的手册,以确定在" at line 1"附近使用的正确语法。

而不是function if,在所有情况下使用相同的代码行。为什么呢?

try this

function updateDb($lati,$longi)
{
global $ambid;
$lati = mysql_real_escape_string($lati);
$longi = mysql_real_escape_string($longi);
$ambid = mysql_real_escape_string($ambid);
$query = "UPDATE emergency SET `e_latitude`='$lati',`e_longitude`='$longi' WHERE `amb_id`='$ambid' ";
$res= mysql_query($query) or die("Unable to update the latlong values because : " . mysql_error());
}

这个错误是可能发生的,因为你插入'字符没有使用mysql_real_escape_string()周围的值插入到你的MySQL查询。我建议你像这样封装你的值

$ambid = mysql_real_escape_string($_POST['amb_id']); 

但是,我不建议你使用mysql_函数,因为它非常弱,容易受到mysql注入的攻击,就像你的代码一样。学习PDO。