它的代码无法更新或插入到mysql db中的数据

时间:2014-07-04 05:40:20

标签: mysql

$retval = mysql_query("
IF EXISTS(SELECT * FROM config WHERE distance1 = '{$distance1}')

    UPDATE config SET distance2 = $distance2, distance3 = $distance3, totaldistance = $totaldistance, passengers = $passengers, chairwell = $chairwell, babychairs = $babychairs, companions = $ppc, luggage = $ppl, pet = $ppp, insurance = $in, stopinway = $siw where distance1 = $distance1

    ELSE

    INSERT into config(distance1, distance2, distance3, totaldistance, passengers, chairwell, babychairs, companions, luggage, pet, insurancestopinway) values('$distance1', '$distance2', '$distance3', '$totaldistance', '$passengers', '$chairwell', '$babychairs', '$ppc', '$ppl', '$ppp', '$in', '$siw')
    ");

1 个答案:

答案 0 :(得分:0)

我认为最好使用INSERT INTO ... ON DUPLICATE KEY UPDATE语法。 但您必须先将列距离1设置为“唯一”。 这将是您的新查询:

INSERT into config (
distance1, distance2, distance3, 
totaldistance, passengers, chairwell, 
babychairs, companions, luggage, 
pet, insurancestopinway) 
values (
'$distance1', '$distance2', '$distance3', 
'$totaldistance', '$passengers', '$chairwell', 
'$babychairs', '$ppc', '$ppl', 
'$ppp', '$in', 
'$siw' #ATTENTION: you have 8 columns but 9 values, this will be generate an error
)
    ON DUPLICATE KEY UPDATE
    distance2 = '$distance2',
    distance3 = '$distance3'
    #...
    #and so on
");