更新MySQL数据库中的数据

时间:2014-05-13 02:11:56

标签: php mysql

我在更新数据库中的现有行时遇到问题。我需要做的是将记录添加到名为“Time_Out”的字段中。该字段与“Time_In”,“username”和“date_added”位于同一行。 Time_In工作得非常好。这是我用过的代码:

date_default_timezone_set('Asia/Taipei'); 
$date_added = date ("Y-m-d");
$time_added = date ("h:i:s:a:");
$user = $_SESSION['xxxx']['xxxxx'];
$con = mysqli_connect("localhost", "xxxx", "xxxx", "test");
$save = mysqli_query($con, "INSERT INTO time_logs (username, date_added, Time_In) VALUES('$user', '$date_added', '$time_added')");
if(!$con) {
    die('Could not connect to the database' . mysql_error());
    mysql_close($con);
}
else
    header("Location: etc.php");

对于Time_Out,我已删除“INSERT INTO ...”行并将其更改为:

$save = mysqli_query($con, "UPDATE time_logs SET Time_Out = $time_added WHERE username = $user");

但我的数据库中Time_Out字段中的记录仍显示为0:00。 顺便说一下,我的date_added设置为Date,Time_In和Time_Out设置为Time。

如果有人能告诉我如何使用PHP做这件事我真的很感激。提前谢谢。

2 个答案:

答案 0 :(得分:3)

您的非数字数据周围缺少单引号。尝试:

$save = mysqli_query($con, "UPDATE time_logs SET Time_Out = '$time_added' WHERE username = '$user'");

答案 1 :(得分:0)

您的代码存在一些问题。首先在这个块中,当mysqli_*mysql_*扩展混合在一起时,它们应该是mysqli_*

date_default_timezone_set('Asia/Taipei'); 
$date_added = date ("Y-m-d");
$time_added = date ("h:i:s:a:");
$user = $_SESSION['xxxx']['xxxxx'];
$con = mysqli_connect("localhost", "xxxx", "xxxx", "test");
$save = mysqli_query($con, "INSERT INTO time_logs (username, date_added, Time_In) VALUES('$user', '$date_added', '$time_added');");
if (!$con) {
    die('Could not connect to the database' . mysqli_error($con));
    mysqli_close($con);
}
else
    header("Location: etc.php");

特别是在if (!$con) {检查中。现在看看清理过的例子。但是,您的更新没有围绕字符串值的单引号:

$save = mysqli_query($con, "UPDATE time_logs SET Time_Out = $time_added WHERE username = $user");

所以它应该是这样的:

$save = mysqli_query($con, "UPDATE time_logs SET Time_Out = '$time_added' WHERE username = '$user'");

但为了让您的生活更轻松,您可能希望重新格式化您的查询:

$query = "UPDATE time_logs SET Time_Out = '" . $time_added . "' WHERE username = '" . $user . "';";
$save = mysqli_query($con, $query);

请注意我是如何在单独的字符串&中设置查询的。然后为变量添加串联到字符串本身。这使我更容易在我的简单选项中在文本编辑器中发现这样的问题。我还用分号(;)结束了每个查询,因为这再次使我更清楚这是查询语句的真正结束。