php - 同一行插入两次

时间:2017-09-20 16:21:42

标签: php mysql sql

以下代码应该将值插入数据库:

$sql = "INSERT INTO savedtimes (username, session, value3, value4, value5)
          VALUES ('$user', '$q', '$value3', '$value4', '$value5')";
  mysqli_query($db, $sql);

它有效,但唯一的问题是该行被插入两次(每次!)。

因此,举例来说,我正在分析价值观' myUsername',' 1',' foo',' bar',& #39; fubar',这些值存储在数据库中,如:

| id |用户名|会议| value3 | value4 |价值5 |

| 1 | myUsername | 1 | foo |吧| fubar |

| 2 | myUsername | 1 | foo |吧| fubar |

我也尝试过更改浏览器,但这没有效果。我注意到有同样问题的另一个问题,但没有答案。有人可以帮帮我吗?

修改

我已经根据你们中的一些人的要求添加了一些我的代码:

session_start();
$q = $_GET['q'];
$user = $_SESSION['username'];
$db = mysqli_connect('localhost', 'username', 'password', 'databaseName');
$sql = "SELECT * FROM savedtimes WHERE username = '$user' AND session = '$q'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) == 1) {
  $sql2 = "SELECT time FROM savedtimes WHERE username = '$user' AND session = '$q'";
  $updateRequired = mysqli_query($db, $sql2);
  if ($updateRequired == "-:--.---") {
    $query = "UPDATE savedtimes
              SET value3 = '$value3', value4 = '$value5'
            WHERE session = '$q'";
    mysqli_query($db, $query);
  }
  else {
    $insert = true;
  }
}
if ((mysqli_num_rows($result) > 1) || ($insert == true)) {
  $sql = "INSERT INTO savedtimes (username, session, value3, value4, value5)
          VALUES ('$user', '$q', '$value3', '$value4', '$value5')";
  mysqli_query($db, $sql);
}

1 个答案:

答案 0 :(得分:-2)

$sql = "INSERT INTO savedtimes (username, session, value3, value4, value5) VALUES";
for($i=1;$i<=1;$i++){
$sql .="('$user', '$q', '$value3', '$value4', '$value5')";
}
mysqli_query($db, $sql);

试试此代码