警告:切勿直接从$ _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