我有一个表单,每个用户只能有一个记录。由于某些原因,我用来确定用户是否有先前提交的条件没有写入数据库。任何帮助是极大的赞赏。
代码如下:
<?php
$user_id = $_SESSION['user_id'];
$anthem1 = null;
$cointoss2 = null;
$firstscore3 = null;
//$query
$query = "SELECT * ";
$query .= "FROM mypicks ";
$query .= "WHERE user_id = {$user_id} ";
$result = mysqli_query($connection, $query);
if (isset($result)) {
//existing submission - this is breaking it
if (isset($_POST['submit'])) {
if (isset($_POST['anthem1'])) {
$anthem1 = $_POST['anthem1'];
}
if (isset($_POST['cointoss2'])) {
$cointoss2 = $_POST['cointoss2'];
}
if (isset($_POST['firstscore3'])) {
$firstscore3 = $_POST['firstscore3'];
}
$query = "UPDATE mypicks SET";
$query .= "anthem1 = '{$anthem1}', ";
$query .= "cointoss2 = '{$cointoss2}', ";
$query .= "firstscore3 = '{$firstscore3}' ";
$query .= "WHERE user_id = {$user_id} ";
$result = mysqli_query($connection, $query);
}
}else{
//new submission
if (isset($_POST['submit'])) {
if (isset($_POST['anthem1'])) {
$anthem1 = $_POST['anthem1'];
}
if (isset($_POST['cointoss2'])) {
$cointoss2 = $_POST['cointoss2'];
}
if (isset($_POST['firstscore3'])) {
$firstscore3 = $_POST['firstscore3'];
}
$query = "INSERT INTO mypicks (";
$query .= " user_id, anthem1, cointoss2, firstscore3";
$query .= ") VALUES (";
$query .= " '{$user_id}', '{$anthem1}', '{$cointoss2}', '{$firstscore3}'";
$query .= ")";
$result = mysqli_query($connection, $query);
}
}
?>
最佳答案
首先,您在 SET 之后缺少一个空格
$query = "UPDATE mypicks SET";// Concats as SETanthem1
$query .= "anthem1 = '{$anthem1}', ";
$query .= "cointoss2 = '{$cointoss2}', ";
$query .= "firstscore3 = '{$firstscore3}' ";
$query .= "WHERE user_id = {$user_id} ";
其次,根据 v7d8dpo4 所说的内容,您需要执行 $result->num_rows 之类的操作,或者如果您需要 fetch 和 rowCount。但这与您关于更新的问题无关
第三,您可以通过简单地通过 phpmyadmin 的 UI 或您喜欢的任何方式测试查询来防止将来出现此类错误
关于php - 数据库不更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36298290/