网页中出现MySQL UPDATE查询错误


MySQL UPDATE query Error in Web Page

我的UPDATE查询失败了,尽管语法对我来说很好(我有另一个更新查询在同一页面上运行良好)。

mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("sitename") or die(mysql_error());
$id = $_GET['id'];
if (isset($_POST['submit'])){                           
        $b = mysql_real_escape_string(trim($_POST['body']));
        //**You have an error in your SQL syntax;** --> ?
        mysql_query ("UPDATE body SET body= $b WHERE id = $id") or die (mysql_error() );
        // $b is fine 
        echo "$b";          
    }

HTML审阅表单的呈现方式。。

// Puts SQL Data into an array
$q = mysql_query("SELECT * FROM vote") or die (mysql_error());
// Now we loop through the database
echo "<br />";
while ($ratings = mysql_fetch_array($q))
{
    //This outputs the doctors's name
    echo "Doctor's name:" . $ratings['doctor_name'] ."<br />";
        //This outputs a textarea for the user to submit comments
        echo "<b>Your Experience: </b>";
        echo "<form method='post' action='review_doctors.php'> 
                <textarea name='body'></textarea>
                <input type='submit' name='submit' value='Send' id='submit'/>
             </form>
             "; 
        echo "<br />";
echo "<p> </p>";
}

为什么每当提交评论时都会出现SQL语法错误?

因此,您正在从$_GET数组中设置$id,这可能不会在通过post提交表单时设置。

您正在运行的更新查询在POST检查中(检查是否设置了$_POST['submit'])。

您可能想要在post正文中发送$id的值,并从post数组中提取它。

我将其修复为:

// If submitted 
if (isset($_POST['id'])){       
            //Capture what was typed in textarea
            $b = mysql_real_escape_string(trim($_POST['body']));
            $id = $_POST['id'];
            mysql_query ("UPDATE vote SET body = '$b' WHERE id = $id") or die (mysql_error() );
            // $b and $id are still fine 
            echo "$b";  
            echo "$id";
        }

还修复了隐藏的输入值:

while ($ratings = mysql_fetch_array($q))
{
    //This outputs the doctors's name
    echo "Doctor's name:" . $ratings['doctor_name'] ."<br />";
        $id = $_POST['id'];    
        //This outputs a textarea for the user to submit comments
        echo "<b>Your Experience: </b>";
        echo "<form method='post' action='review_doctors.php'> 
                <textarea name='body'></textarea>
                <input type='submit' name='submit' value='Send'/>

                <input type='hidden' name='id' value='$ratings[id]' />
             </form>
             ";
        echo "<br />";