警告:切勿直接從$ _POST使用任何東西! Sanitize和驗證所有用戶輸入。您在下面看到的僅用於演示目的。在查詢中沒有WHERE
子句,整個表將被更新。
當你做到這一點在你的HTML元素<input>
:
name="value[]"
$_POST
將收到的$_POST
元素值數組。因此,
$_POST['value'] //resolves to an array.
這就是爲什麼你得到一個錯誤(錯誤:注意:數組字符串轉換),當你這樣做:
$stmt = $conn->prepare("UPDATE `students` SET `value` = `value` +{$_POST['value']}");
牙套{}
期間內串插值通常用於雙引號。您的代碼試圖將數組轉換爲字符串。
你可能反而試試這個:
$stmt = $conn->prepare("UPDATE `students` SET `value1` = `value1` + ?");
或者,這...
$stmt = $conn->prepare("UPDATE `students` SET `value1` = `value1` + :value1");
不要把用戶直接輸入到一個事先準備好的聲明。 PHP PDO::prepare手冊頁狀態。
Prepares an SQL statement to be executed by the PDOStatement::execute() method. The SQL statement can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed. You cannot use both named and question mark parameter markers within the same SQL statement; pick one or the other parameter style. Use these parameters to bind any user-input, do not include the user-input directly in the query.
您需要先對數組$_POST['values']
進行一些處理。 消毒和驗證的數據是非常明智和最佳實踐。
您的<input>
元素的數據實際上就在這裏。
$_POST['values'][0] //Resolves to a string.
$_POST['values'][1] //Resolves to a string.
$_POST['values'][2] //Resolves to a string.
錯誤柱未發現:在「字段列表」 1054未知列「值」建議你應該在你的表使用實際的列名。用你自己的話說,這些字段名稱是value1
,value2
和value3
。
當您使用PDOStatement::execute
,你可以這樣做只是爲了看看事情正在?
方式工作....
$stmt->execute([$_POST['values'][0]]) //PHP 5.4+
或者
$stmt->execute(array([$_POST['values'][0])) //PHP 5.3 and below
如果使用命名參數,則可以試試這個。
$stmt->execute(['value1' => $_POST['values'][0]]) //PHP 5.4+
或者
$stmt->execute(array('value1' => [$_POST['values'][0])) //PHP 5.3 and below
....但我認爲這種生活危險。 首先消毒並驗證您的輸入。
如果你有機會使用MySQL stored procedures(比方說,對於電子商務網站)與您的PDO預處理語句的點,擡頭PDOStatement::bindParam(必須使用這個變量)和PDOStatement::bindValue(可以使用一般的值,比如字符串文字)。
$stmt->bindValue(1, $variable);
$stmt->execute();
或者......
$stmt->bindValue(:name, $variable);
$stmt->execute();
$stmt->bindParam(1, $variable);
或$stmt->bindParam(:name, $variable);
是使用IN/OUT
參數與存儲過程中最有用。
要小心。您將最終更新整個表格,因爲查詢中沒有WHERE
條件!但是,如果您希望所有記錄具有相同的值,那麼您可以這樣做。 :-) Edgar F. Codd會說什麼?
儘管可以使用循環來解決使用全部三個假設的$ _POST ['value']元素的問題,但仍然需要問爲什麼整個表需要爲每次迭代更新。
我編輯了你的答案,看起來像這樣。
if(isset($_POST['value']) && is_array($_POST['value']) && !empty($_POST['value']) && (count($_POST['value']) === 3)){
foreach($_POST['value'] as $key => $value) {
$num = ($key + 1);
$stmt = $conn->prepare("UPDATE `students` SET value{$num} = ? + value{$num}");
$stmt->bindValue(1, $value);
$stmt->execute();
}
}
雖然不全面,但至少有更好的檢查正在完成。但是,這樣的事情可能會更好。
if(!isset($_POST['value']) || !is_array($_POST['value']) || empty($_POST['value']) || (count($_POST['value']) !== 3)){
throw new UnexpectedValueException("Something is wrong with the input in $_POST.");
}
foreach($_POST['value'] as $key => $value) {
$num = ($key + 1);
$stmt = $conn->prepare("UPDATE `students` SET value{$num} = ? + value{$num}");
$stmt->bindValue(1, $value);
$stmt->execute();
}
http://bobby-tables.com/ – GordonM