将一个变量中的两个值插入数据库

mmvthczy  于 2021-08-01  发布在  Java
关注(0)|答案(1)|浏览(384)

我有两个不同的表'user'和'candidates',我试图通过用户选择将值从一个表添加到另一个表。
这是显示“user”表中的“name”和“lasname”行的代码:

echo "<select class='form-control custom-select' name='candid'>";
     while ($row = $result->fetch_assoc())
     {
      $candid = $row['name'] .' '. $row['surname'];
      echo "<option value='.$candid.'>".$candid."</option>";
     }
     echo "</select>";

我连接了两列并将它们的值赋给$candid变量。现在,我需要将这些值添加到“candidates”表中的“name”和“lasname”列中。我还尝试了此代码的其他版本:

while ($row = $result->fetch_assoc())
     {
      echo "<option value='candid'>".$row['name'] .' '. $row['surname']."</option>";
     }

使用此sql查询:

$sql = ("INSERT INTO candidates (name, surname) VALUES ('$row[name]', '$row[surname]')");

    if ($conn->query($sql) === TRUE)
    {
        echo "New record created successfully";
    }
    else
    {
        // $conn->error only for testing purposes
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

但它不起作用,所以我有个问题。是否可以只使用php和sql来实现这一点?

cu6pst1q

cu6pst1q1#

当用户提交表单时,所选值处于 $_POST['candid'] . 您可以在空格处拆分它,然后插入到表中。

list($name, $surname) = explode(' ', $_POST['candid'], 2);
$stmt = $conn->prepare("INSERT INTO candidates (name, surname) VALUES(?, ?)");
$stmt->bind_param("ss", $name, $surname);
if ($stmt->execute()) {
    echo "New record created successfully";
} else {
    echo "Record not created";
    error_log("candidate record not created: $conn->error");
}

相关问题