MySQL Insert语句未执行

时间:2014-11-10 20:56:45

标签: php mysql

我正在尝试像这样运行mySQL插入语句:

function insertAppointment($connection, $id, $firstname, $lastname, $email, $phone, $date, $time){

                $sql = "INSERT INTO `appointments` (firstname, lastname, email, phone, app_date, app_time) VALUES ('" . $id . "', '" . $firstname . "', '" . $lastname . "', '" . $email . "', " . $date . ", " . $time . ")";
                $connection->query($sql);

        }

$ connection是我的连接字符串,这不是问题。我可以将它用于select语句,如下所示:

function getTakenDates($connection){

                $query = mysqli_query($connection, "SELECT app_date, app_time FROM `appointments`");
                $results = array();
                while($row = mysqli_fetch_assoc($query)){
                        $results[] = $row;
                }
                return $results;

        }

1 个答案:

答案 0 :(得分:5)

您很容易受SQL injection attacks攻击,并且使用$ date / $ time值创建了错误的查询:

INSERT .... VALUES (..., 2014-11-10, 14:58:00)

由于您的日期值未加引号,您实际上会尝试插入该数学运算的结果(如果它不在字符串中,请记住-是SUBTRACTION),并且14: 58:00是一个完全无效的数字 - mysql不知道那些:字符是什么。

你想要

$sql = "[..snip..]  "', '" . $date . "', '" . $time . "')";    
                        ^-------------^--^-------------^----

代替。请注意额外的报价。那将产生

INSERT .... VALUES (..., '2014-11-10', '14:58:00')