我想将两个变量的数据插入MySQL。
这是我的代码:
<?php
// Prepare variables for database connection
$dbusername = "arduino"; // enter database username, I used "arduino" in step 2.2
$dbpassword = "arduinotest"; // enter database password, I used "arduinotest" in step 2.2
$server = "localhost"; // IMPORTANT: if you are using XAMPP enter "localhost", but if you have an online website enter its address, ie."www.yourwebsite.com"
// Connect to your database
$dbconnect = mysql_pconnect($server, $dbusername, $dbpassword);
$dbselect = mysql_select_db("test",$dbconnect);
// Prepare the SQL statement
$sql = "INSERT INTO test.sensor (homero, parat) VALUES ('".$_GET["homero"].", ".$_GET["parat"]."')";
// Execute SQL statement
mysql_query($sql); ?>
当我点击http://localhost/write_data.php?homer=32¶t=43时,它不会将任何数据发送到我的数据库。你能帮帮我吗? $ sql行是否正确?感谢
答案 0 :(得分:0)
您的SQL语句中有错误,您没有正确的引号 另外:请使用围绕变量的反引号。
在我提出解决方案之前,我需要警告你其他一些事情 首先:您的代码易受SQL注入攻击 有关SQL注入的更多信息:What is SQL injection?
其次:Mysql_ *在PHP5中已弃用,在PHP7中已删除。您可以切换到更好的Mysqli_ *:PDO。请对此进行一些研究。
有关此内容的更多信息:Why shouldn't I use mysql_* functions in PHP?
无论如何:这是修补你的代码片段的代码行,但它不是那么好:
$sql = "INSERT INTO `test`.`sensor` (`homero`, `parat`) VALUES ('".$_GET["homero"]."', '".$_GET["parat"]."')";
答案 1 :(得分:0)
您有两个缺失的引号首先是".$_GET["homero"]."
之后,第二个是".$_GET["parat"]."
之前。所以尝试使用以下查询:
$sql = "INSERT INTO test.sensor (homero, parat) VALUES ('".$_GET["homero"]."', '".$_GET["parat"]."')";
答案 2 :(得分:0)
试试这个:
<?php
// Prepare variables for database connection
$dbusername = "arduino"; // enter database username, I used "arduino" in step 2.2
$dbpassword = "arduinotest"; // enter database password, I used "arduinotest" in step 2.2
$server = "localhost"; // IMPORTANT: if you are using XAMPP enter "localhost", but if you have an online website enter its address, ie."www.yourwebsite.com"
$db = "test";
// Connect to your database
$mysqli = mysqli_connect($server,$dbusername,$dbpassword,$test) or die("Error " . mysqli_error($mysqli));
// Prepare the SQL statement
$sql = "INSERT INTO test.sensor (homero, parat) VALUES ('".$_GET['homero']."', '".$_GET['parat']."')";
// Execute SQL statement
mysqli_query($mysqli, $sql) ?>
使用mysqli而不是mysql,因为后者是被删除的