连接到服务器并选择正确的数据库后,我在 php 代码中收到一个名为 $temp 的 GET 变量,并且我能够使用以下方法将其传递到表中:
mysql_query("INSERT INTO Temperature (Temperature) VALUES ($temp)");
但是,如果我使用以下方法保存时间变量:
$time = date('G:i', time());
并尝试将其与以下内容混为一谈:
mysql_query("INSERT INTO Temperature (Temperature) VALUES ($temp)");
甚至:
mysql_query("INSERT INTO Temperature (Time,Temperature) VALUES ($time,$temp)");
我无法将其传递到我的表中。
我正在回显这两个变量,所以我知道它们被正确保存到变量中。此外,在我的表中有两列名为"时间"和"温度"。该表的名称是"温度"。如果 $time 变量与变量的代码行完全相同,为什么$temperature变量除了更改列名之外不会传入?此外,两列都设置为接收 varchar (20),这可能是问题所在吗?
你非常
接近在你的例子中得到它。在此行中,您需要在查询中围绕您的值使用引号。
mysql_query("INSERT INTO Temperature (Time,Temperature) VALUES ($time,$temp)");
所以它看起来像这样:
mysql_query("INSERT INTO Temperature (Time,Temperature) VALUES ('$time', '$temp')");
但是,这种创建查询的方式很快就会被弃用,因为它是更易于使用和更现代的PDO方法。使用 PDO 将如下所示:
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare('INSERT INTO Temparature (`time`, `temperature`)
VALUES (:time, :temperature)');
$stmt->bindParam(':time', $time);
$stmt->bindParam(':temperature', $temp);
// insert a row
$temp = "34";
$time = date('G:i', time());
$stmt->execute();
MySQL中的time
列需要一个格式为"hh:mm:ss"的字符串。
为此,您可以执行以下操作:
$timestamp = time();
$time = date('G:i', $timestamp); // assuming you need $time somewhere else
mysql_query("INSERT INTO Temperature (Time,Temperature) VALUES ( ".date('H:i:s', $timestamp).", $temp)");
如果除了将其插入数据库之外不需要$time
用于任何其他目的,则可以使用:
mysql_query("INSERT INTO Temperature (Time,Temperature) VALUES (NOW(), $temp)");
让MySQL为您创建时间。
要仅选择小时和分钟,请执行以下操作:
SELECT TIME_FORMAT(Time, '%H:%i') FROM Temperature;
有关将日期和时间格式化为字符串的更多信息,请参阅 MySQL 文档。