2017-08-01 33 views
-2

我試圖使用PHP MySQL數據庫更新表,但我不斷收到以下錯誤:試圖更新表字段在PHP

Error:Database query failed.You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE student_id = 4, student_forename = 'Alex', student_surname = 'Lee', studen' at line 1.

我不知道故障是否更新從結果僅僅是語法錯誤,還是這個問題涉及另一個或許更嚴重的問題。這裏是我的代碼:

<?php 

    $student_id = 4; 
    $student_forename = 'Alex'; 
    $student_surname = 'Lee'; 
    $student_year = 12; 

    $query = "UPDATE students SET "; 
    $query .= "WHERE student_id = {$student_id}, "; 
    $query .= "student_forename = '{$student_forename}', "; 
    $query .= "student_surname = '{$student_surname}', "; 
    $query .= "student_year = {$student_year} "; 

    $result = mysqli_query($connection, $query); 

    //Test if there was a query error 
    if($result) { 
    echo "Success!"; 
    } else { 
    die("Database query failed." . mysqli_error($connection)); 
    } 
?> 
+3

您需要閱讀有關UPDATE和WHERE子句的手冊。 –

+0

As @ Fred-ii-暗示(我可以說是相當不錯的地方!)你的位置是不正確的 - [雖然W3Schools被詬病,但這些例子非常適合你的快速演示。](https://www.w3schools。 com/php/php_mysql_update.asp) – Script47

+2

@ slevy1重新打開,爲什麼?它也被問過很多次,它不會爲網站添加任何特別的東西,也不會給你任何其他答案。 –

回答

2

把最後的WHERE子句:

$query = "UPDATE students SET "; 
$query .= "student_forename = '{$student_forename}', "; 
$query .= "student_surname = '{$student_surname}', "; 
$query .= "student_year = {$student_year} "; 
$query .= "WHERE student_id = {$student_id}"; 

只是一個小紙條在這裏 - 如果你沒有使用準備好的陳述,你至少應該清理你的輸入。

參見手冊:

http://php.net/manual/en/function.filter-var.php

http://php.net/manual/en/filter.filters.sanitize.php

http://php.net/manual/en/filter.filters.validate.php

http://php.net/manual/en/function.htmlentities.php

http://php.net/manual/en/function.strip-tags.php

+0

你是絕對正確的:http://php.net/manual/en/mysqli.prepare.php,但實際上你應該消毒:) –

+2

所有那些你覺得會消毒輸入的鏈接,將無濟於事保護可能的SQL注入 –

0

你是不是「設置」任何東西。

你的MySQL查詢應該設置的東西:[source]

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"; 

你用錯誤行:

$query = "UPDATE students SET "; 
1

如果你看一下MySQL UPDATE手冊,你會發現你忘記了SET部分( - ;)。

UPDATE [LOW_PRIORITY] [IGNORE] table_reference 
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ... 
    [WHERE where_condition] 
    [ORDER BY ...] 
    [LIMIT row_count]