php-sql语法错误

eaf3rand  于 2021-06-21  发布在  Mysql
关注(0)|答案(4)|浏览(334)

我正在尝试将表单数据插入到数据库中的一个表中。要插入的数据包括姓名、电子邮件、当前日期和用户兴趣。这是密码。

if (isset($_POST['name'])) {
   $name = $_POST['name'];
   $email = $_POST['email'];
   $intrests = $_POST['intrests'];
   $default_intrests = array("mob","pcs","scm","oth");
   $interests = "";
   if (count($intrests) == 0) {
      $interests = implode(",", $default_intrests);
   }
   else {
          $interests = implode(",", $intrests);
   }

   $sqll="insert into subscriptions (name,email,subdate,intrests) values ($name,$email,CURRENT_DATE, $interests)";
   $insert = mysqli_query($link, $sqll);
   if (!$insert) {
      echo mysqli_error($link);
   }
}

在表单提交时,将显示以下错误:
sql语法有错误;查看与您的mariadb服务器版本相对应的手册,以获取正确的语法dsa,asdf@qwer.com,当前日期,mob),第1行

axzmvihb

axzmvihb1#

mysql_query("insert into table values('data1', 'data2' )");
elcex8rz

elcex8rz2#

// User Entered fields
    //***This is dangerous, it is subject to sql injection, 
    $query = "insert into subscriptions(name,email,subdate,intrests)
             values ('$name','$email',CURRENT_DATE, '$interests')";

    $result = mysqli_query( $link, $query);

    //***Error checking, what if !$result? eg query is broken

    $row = mysqli_fetch_array($result);

    if(!$row){

        echo "No Row inserted";
    }
    else {
       echo "OK";
    }

如果要使用任何php变量,则不应使用mysqli\u query(),而应始终使用准备好的语句,如下所示:

$stmt = $mysqli->prepare("insert into subscriptions name,email,subdate,intrests)
                             values (?,?,CURRENT_DATE, ?)");
$stmt->bind_param('sss', $class);
$stmt->execute();
$data = $stmt->get_result()->fetch_all();
jm81lzqq

jm81lzqq3#

添加 ' 因为其中有些是 string ```
$sqll="insert into subscriptions (name,email,subdate,intrests)
values ('$name','$email',CURRENT_DATE, '$interests')";

事实上,直接将参数写入sql是个坏主意,最好使用准备好的语句,避免sql注入
dgsult0t

dgsult0t4#

尝试将当前日期存储到变量中
像这样的

if (isset($_POST['name'])) {
            $name=$_POST['name'];
            $email=$_POST['email'];
            $intrests=$_POST['intrests'];
            $CURRENT_DATE = date("Y-m-d");
            $default_intrests=array("mob","pcs","scm","oth");
            $interests="";
            if(count($intrests)==0){
                $interests= implode(",", $default_intrests);
            }else{
                $interests= implode(",", $intrests);
            }

            $sqll="insert into subscriptions (name,email,subdate,intrests) values ('$name','$email','CURRENT_DATE', '$interests')";
            $insert= mysqli_query($link, $sqll);
            if (!$insert) {
                echo mysqli_error($link);
            }
        }
}

相关问题