在连接到服务器并选择正确的数据库后,我在我的 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 变量是完全相同的代码行(除了更改列名称之外),为什么不会传入 $time 变量?此外,两列都设置为接收 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();
关于php - 如何使用 php 将使用 date() 函数创建的变量传递到 MYSQL 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36107018/