首页 \ 问答 \ 使用PHP非空的输入将数据插入MySQL数据库(Insert data into MySQL database from inputs that are not empty with PHP)

使用PHP非空的输入将数据插入MySQL数据库(Insert data into MySQL database from inputs that are not empty with PHP)

我有一个页面,用户可以更新或更改他的个人资料信息,例如他的位置或他的个人资料图片。 默认情况下,每个用户在其配置文件页面上获取占位符数据或信息,并且mysql数据库中的那些字段为空或者具有该用户ID的行不存在。 所以首先我要检查用户以前是否将他的个人资料信息输入到数据库中,如果数据存在,我将只使用非空的输入字段更新它,这部分有效。 但是,如果数据库或行中不存在数据,并且此用户ID不存在,那么我想插入数据,但只能输入非空的输入

但这是我得到的错误

带有消息'SQLSTATE [42000]的未捕获异常'PDOException':语法错误或访问冲突:1064 SQL语法中有错误; ...

这是我的代码( $userID是session $userID = $_SESSION['ID'];

if(isset($_POST['updateInfo'])) {
$userDesc = filter_var($_POST['description_update'], FILTER_SANITIZE_STRING);
$userLocation = filter_var($_POST['location_update'], FILTER_SANITIZE_STRING);
$userBirthDate = filter_var($_POST['birthDate_update'], FILTER_SANITIZE_STRING);
$user_picture_tmp = $_FILES['user_picture']['tmp_name'];
$user_picture_name = $_FILES['user_picture']['name'];


$checkInfo = $con->prepare("SELECT * FROM user_info WHERE userid=:userID");
$checkInfo->execute(array(':userID' => $userID));
$data = $checkInfo->fetch(PDO::FETCH_ASSOC);    
$count_rows = $checkInfo->rowCount();

//Here i am checking if data exists in mysql and UPDATING it    
if($count_rows > 0) {   

    if(!empty($userDesc)) {
        $query = $con->prepare("UPDATE user_info SET description=:description WHERE userid=:userID");
        $query->execute(array(':userID' => $userID, ':description'=> $userDesc));
    }   
    if(!empty($userLocation)) {
        $query = $con->prepare("UPDATE user_info SET location=:location WHERE userid=:userID");
        $query->execute(array(':userID' => $userID, ':location'=> $userLocation));
    }
    if(!empty($userBirthDate)) {
        $query = $con->prepare("UPDATE user_info SET birthDate=:birthDate WHERE userid=:userID");
        $query->execute(array(':userID' => $userID, ':birthDate'=> $userBirthDate));
    }
    if(!empty($user_picture_name)) {
        $query = $con->prepare("UPDATE user_info SET profile_pic=:profile_pic WHERE userid=:userID");
        move_uploaded_file($user_picture_tmp, 'user_pic/'.$user_picture_name);
        $query->execute(array(':userID' => $userID, ':profile_pic'=> $user_picture_name));

    }   
    //But if data doesn't exists i want to INSERT IT and here is error
}   else {

    if($userDesc AND $userLocation AND $userBirthDate AND $user_picture_name != '') {

        $query = $con->prepare("INSERT INTO user_info(userid) VALUES(:userID)");
        $query->execute(array(':userID' => $userID));

        if(!empty($userDesc)) {
            $query = $con->prepare("INSERT INTO user_info(description) VALUES(?) WHERE userid=?");
            $query->execute(array($userDesc, $userID));
        }   
        if(!empty($userLocation)) {
            $query = $con->prepare("INSERT INTO user_info(location) VALUES(?) WHERE userid=?");
            $query->execute(array($userLocation, $userID));
        }
        if(!empty($userBirthDate)) {
            $query = $con->prepare("INSERT INTO user_info(birthDate) VALUES(?) WHERE userid=?");
            $query->execute(array($userBirthDate, $userID));
        }   
        if(!empty($user_picture_name)) {
            $query = $con->prepare("INSERT INTO user_info(profile_pic) VALUES(?) WHERE userid=?");
            move_uploaded_file($user_picture_tmp, 'user_pic/'.$user_picture_name);
            $query->execute(array($user_picture_name, $userID));

        }
    } else {echo 'All fields are empty';} 

}                       
}

所以我的问题是为什么我得到这个错误,我也是这样做错误的方式或是否有其他更好的方法来做到这一点。 这仅用于学习目的。


I have page where user can update or change his profile information for example his location or his profile picture. By default every user get placeholder data or information on his profile page and those fields in mysql database are empty or row with that user id doesn't exists. So first i am checking if user previously entered his profile information into database and if data exist i will just update it with input fields that are not empty and this part works. But if data doesn't exists in database or row with this user id doesn't exist then i want to insert data but again only with inputs that are not empty.

But this is error i am getting

Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;...

This is my code ($userID is session $userID = $_SESSION['ID'];)

if(isset($_POST['updateInfo'])) {
$userDesc = filter_var($_POST['description_update'], FILTER_SANITIZE_STRING);
$userLocation = filter_var($_POST['location_update'], FILTER_SANITIZE_STRING);
$userBirthDate = filter_var($_POST['birthDate_update'], FILTER_SANITIZE_STRING);
$user_picture_tmp = $_FILES['user_picture']['tmp_name'];
$user_picture_name = $_FILES['user_picture']['name'];


$checkInfo = $con->prepare("SELECT * FROM user_info WHERE userid=:userID");
$checkInfo->execute(array(':userID' => $userID));
$data = $checkInfo->fetch(PDO::FETCH_ASSOC);    
$count_rows = $checkInfo->rowCount();

//Here i am checking if data exists in mysql and UPDATING it    
if($count_rows > 0) {   

    if(!empty($userDesc)) {
        $query = $con->prepare("UPDATE user_info SET description=:description WHERE userid=:userID");
        $query->execute(array(':userID' => $userID, ':description'=> $userDesc));
    }   
    if(!empty($userLocation)) {
        $query = $con->prepare("UPDATE user_info SET location=:location WHERE userid=:userID");
        $query->execute(array(':userID' => $userID, ':location'=> $userLocation));
    }
    if(!empty($userBirthDate)) {
        $query = $con->prepare("UPDATE user_info SET birthDate=:birthDate WHERE userid=:userID");
        $query->execute(array(':userID' => $userID, ':birthDate'=> $userBirthDate));
    }
    if(!empty($user_picture_name)) {
        $query = $con->prepare("UPDATE user_info SET profile_pic=:profile_pic WHERE userid=:userID");
        move_uploaded_file($user_picture_tmp, 'user_pic/'.$user_picture_name);
        $query->execute(array(':userID' => $userID, ':profile_pic'=> $user_picture_name));

    }   
    //But if data doesn't exists i want to INSERT IT and here is error
}   else {

    if($userDesc AND $userLocation AND $userBirthDate AND $user_picture_name != '') {

        $query = $con->prepare("INSERT INTO user_info(userid) VALUES(:userID)");
        $query->execute(array(':userID' => $userID));

        if(!empty($userDesc)) {
            $query = $con->prepare("INSERT INTO user_info(description) VALUES(?) WHERE userid=?");
            $query->execute(array($userDesc, $userID));
        }   
        if(!empty($userLocation)) {
            $query = $con->prepare("INSERT INTO user_info(location) VALUES(?) WHERE userid=?");
            $query->execute(array($userLocation, $userID));
        }
        if(!empty($userBirthDate)) {
            $query = $con->prepare("INSERT INTO user_info(birthDate) VALUES(?) WHERE userid=?");
            $query->execute(array($userBirthDate, $userID));
        }   
        if(!empty($user_picture_name)) {
            $query = $con->prepare("INSERT INTO user_info(profile_pic) VALUES(?) WHERE userid=?");
            move_uploaded_file($user_picture_tmp, 'user_pic/'.$user_picture_name);
            $query->execute(array($user_picture_name, $userID));

        }
    } else {echo 'All fields are empty';} 

}                       
}

So my question is why am i getting this error and also am i doing this the wrong way or is there some other better approach to do this. This is just for learning purposes.


原文:https://stackoverflow.com/questions/33022398
更新时间:2022-02-28 21:02

最满意答案

您可以使用scikit-learn CountVectorizer ,您需要覆盖令牌模式,因为默认情况下它只捕获2个或更多字符的单词。

import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer

s = """B, D, No
       A, C, Yes
       B, C, D, F, Yes"""

c = CountVectorizer(token_pattern='\w+')
values = c.fit_transform(s.split('\n'))

pd.DataFrame(values.toarray(), columns=c.vocabulary_)
   a  d  c  yes  f  b  no
0  0  1  0    1  0  1   0
1  1  0  1    0  0  0   1
2  0  1  1    1  1  0   1

您的数据格式实际上不是CSV,因此大熊猫可能不是读取它的最佳方式,最好只将其作为文本文件读取。


You could use a scikit-learn CountVectorizer, you'll need to override the token pattern since by default it only captures words of 2 or more characters.

import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer

s = """B, D, No
       A, C, Yes
       B, C, D, F, Yes"""

c = CountVectorizer(token_pattern='\w+')
values = c.fit_transform(s.split('\n'))

pd.DataFrame(values.toarray(), columns=c.vocabulary_)
   a  d  c  yes  f  b  no
0  0  1  0    1  0  1   0
1  1  0  1    0  0  0   1
2  0  1  1    1  1  0   1

Your data format isn't really a CSV, so pandas probably isn't the best way to read it in, better to just read it in as a text file.

相关问答

更多

相关文章

更多

最新问答

更多
  • 以编程方式创建视频?(Create videos programmatically?)
  • 为什么开机慢上面还显示;Inetrnet,Explorer
  • javascript数组,如何改变这个数组结构(javascript arrays, how to change this array structure)
  • 在ASP.NET Web API中使用多个Get方法进行路由(Routing with multiple Get methods in ASP.NET Web API)
  • 用于backbone.js验证的自定义验证器(Custom validator for backbone.js validation)
  • const char *与其他指针有什么不同?(Is const char * different from other pointers? [duplicate])
  • 无效的列索引,使用PreparedStatement更新(Invalid column index , update using PreparedStatement)
  • watchOS WCSession'已配对'和'watchAppAvailable'不可用(watchOS WCSession 'paired' and 'watchAppAvailable' are unavailable)
  • CalledFromWrongThreadException在Android上执行JUnit测试(CalledFromWrongThreadException exercising JUnit tests on Android)
  • 如何把文件保存到你的应用程序目录中?(How to put\save files into your application directory? (adobe air))
  • 美元符号在Java方法描述符中的含义?(Meanings of dollar sign in Java method descriptor?)
  • font-size的含义是什么:1em / 2em?(What doe the meaning of font-size:1em/2em?)
  • h2元素推动其他h2和div。(h2 element pushing other h2 and div down. two divs, two headers, and they're wrapped within a parent div)
  • 创建一个功能(Create a function)
  • Android - 检测与特定wifi ssid断开连接的正确方法?(Android - Correct way to detect disconnecting from a particular wifi ssid?)
  • 通过Shell脚本将文件转换为另一个文件(Convert File To Another File By Shell Script)
  • 我投了份简历,是电脑编程方面的学徒,面试时说要培训三个月,前面
  • 如何过滤magento废弃的购物车报告集合(How to Filter the magento abandoned cart report collection)
  • PDO语句不显示获取的结果(PDOstatement not displaying fetched results)
  • web api http post传递对象504接收失败(web api http post passing object 504 Receive Failure)
  • Rails从视图编辑模型上的多个属性的方法(Rails way to edit multiple attributes on a model from a view)
  • 总是用{}初始化对象是否是好习惯?(Is it good habit to always initialize objects with {}?)
  • 在方案中编写特殊字符到输出端口(编译器设计)(writing special characters to output port in scheme (compiler design))
  • 电脑等级考试得证有多大用处?
  • Qt冻结循环的原因?(Qt freezing cause of the loop?)
  • 第一次调用函数将无法按预期工作,但下一次工作正常(calling a function on the first time won't work as expected, but next time is working)
  • 如何优化使用BigInteger操作执行时间的代码(How to optimize the code that uses BigInteger operations for execution time)
  • TableView重复youtube-api结果(TableView Repeating youtube-api result)
  • 如何提供个人资料信息,以便Passport.js可以使用它?(how does Profile information should be provided so Passport.js can use it?)
  • 有没有办法初始化jquery数据表中的细节?(is there any way to initialize details in jquery datatable?)