【问题标题】:How to INSERT value to MYSQL如何将值插入 MYSQL
【发布时间】:2015-10-29 16:34:44
【问题描述】:

当每个选民都用他的 ID 投票时,我正在尝试为数据库增加价值。 我的 db 得到了值,但它下降了一行,我希望 db 将值 1 获取到 ID 行而不是下降一行。

请有任何解决方案!!!

这是我的代码

$before1    = $row['vote_one_before'];
$after1     = $row['vote_one_after'];
$before2    = $row['vote_two_before'];
$after2     = $row['vote_two_before'];
$before3    = $row['vote_three_before'];
$after3     = $row['vote_three_after'];

$vote = 1;

if(($before1 == 0) and ($after1 == 0) and ($before2 == 0) and ($after2 == 0) and ($before3 == 0) and ($after3 == 0)){
    $stmt = $conn->prepare("INSERT INTO DB (vote_one_before) VALUES(':vote_one_before')");
    $stmt->execute(array(':vote_one_before'=> $vote));
}

【问题讨论】:

标签: php mysql pdo insert


【解决方案1】:

问题 1:如果/否则

AND 不是可用于IF/ELSE 函数的运算符 - 您需要&&。将您的 IF 行更改为:

if(($before1 == 0)&&($after1 == 0)&&($before2 == 0)&&($after2 == 0)&&($before3 == 0)&&($after3 == 0)){

问题 2:查询

您的查询也不正确。对于INSERT,格式为:

INSERT INTO `table_name` (`column_name`) VALUES (`new_value`);

除非“DB”是您的表名,否则您需要将查询修改为以下内容:

    $stmt = $conn->prepare("INSERT INTO `table_name` (vote_one_before) VALUES (:vote_one_before)");

另请注意,当使用占位符时,您不需要单引号或双引号 - 因此 ':vote_one_before' 变为 :vote_one_before

【讨论】:

  • 你在问题​​ 1 中错了:PHP 中有一个 and 运算符,由于括号,它在这里可以很好地工作。但是当然,and 将用于例如当您希望赋值运算符的优先级高于逻辑运算时——$a = $b or something() 只有在 $b 为假时才会执行某些操作——并且在if 子句中通常会使用&&。但是您在这里提供的信息根本不正确。咨询php.net/manual/en/language.operators.logical.php
猜你喜欢
  • 2021-02-07
  • 2011-10-31
  • 1970-01-01
  • 2020-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多