使用PHP var时数据库不更新

时间:2014-02-02 14:41:08

标签: php

我在很长一段时间内第一次做了一些简单的PHP和SQL,但由于某些原因我没有让它工作。当我提供固定值时,一切正常,但是一旦用变量替换它们,我的代码就失败了。我检查过,看起来变量中有适当的值:

这有效:

<?php
    $con=mysqli_connect("localhost","xxx","xxx","xxx");

    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

     if(isset($_GET['id'])){
        $ID = $_GET['id'];
        $newStock = $_GET['stockcount'] - 1;
        mysqli_query($con,'UPDATE products SET stockcount = "3" WHERE id = "1"');   
     }
    else
        echo "Invalid item";


    mysqli_close($con);

    header('Location: browse.php');
?>

但不是这样:

<?php
    $con=mysqli_connect("localhost","xxx","xxx","xxx");

    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

     if(isset($_GET['id'])){
        $ID = $_GET['id'];
        $newStock = $_GET['stockcount'] - 1;
        mysqli_query($con,'UPDATE products SET stockcount = "'+$newStock+'" WHERE id = "'+$ID+'"'); 
     }
    else
        echo "Invalid item";


    mysqli_close($con);

    header('Location: browse.php');
?>

我需要对变量做些什么,还是我做错了什么?一如既往,我们将非常感谢任何建议:)

2 个答案:

答案 0 :(得分:1)

“+”不用于PHP中的连接字符串

 mysqli_query($con,'UPDATE products SET stockcount = "'+$newStock+'" WHERE id = "'+$ID+'"');

它应该是

 mysqli_query($con,'UPDATE products SET stockcount = "'.$newStock.'" WHERE id = "'.$ID.'"');  

答案 1 :(得分:0)

mysqli_query($con,'UPDATE products SET stockcount = "'.$newStock.'" WHERE id = "'.$ID.'"'); 

这不是javascript。隐含.而非+。更好的是,只需使用双引号将其传递给字符串!

mysqli_query($con,"UPDATE products SET stockcount = '$newStock' WHERE id = '$ID'");