在连接到服务器并选择正确的数据库之后,我在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),这是问题吗?
发布于 2016-03-19 21:14:48
在你的例子中,你已经很接近了。在这一行中,围绕值的查询需要引号。
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();https://stackoverflow.com/questions/36107018
复制相似问题