使用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
最满意答案
您可以使用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.
相关问答
更多-
它被称为高级索引 。 从第一行选择第一列和第二列,从第二行选择第三列 你只需要在单独的迭代器(元组,列表)中传递相应的行和列: In [9]: a Out[9]: array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) In [10]: a[[0, 0, 1],[0, 1, 3]] Out[10]: array([0, 1, 8]) It's called advanced-indexing. to select first and second column ...
-
困惑于单热编码输出(confused on one-hot encoding output)[2024-02-13]
这是你的训练数据: A B C # <== feature names 0 0 3 1 1 0 0 2 1 1 0 2 现在,您在enc.n_values_ : array([2, 3, 4])看到array([2, 3, 4]) 第一个特征A有两个可能的值= 0和1.类似地,特征B有三个可能的值= 0,1,2 ... 现在在输出中,将根据上述值为每个功能分配列数。 像这样的东西: A_0 A_1 B_0 B ... -
你的问题来自你正在创建的vector对象来做一个热门的编码; 您创建了一个对象,然后构建了一个one_hot_list ,其中包含对同一对象的1460个引用。 在其中一行中进行更改时,它将反映在所有行中。 快速解决方案是为每行创建单独的vector副本(请参阅如何克隆或复制列表? ): one_hot_list.append(vector[:]) 你在功能上做的其他一些事情有点慢或迂回。 我会建议一些更改: def one_hot_encode(data_list, column): one_ho ...
-
Pandas sklearn one-hot编码数据帧还是numpy?(Pandas sklearn one-hot encoding dataframe or numpy?)[2022-04-12]
这个库提供了几个分类编码器,使sklearn / numpy与pandas很好地配合使用https://github.com/wdm0006/categorical_encoding 但是,他们还不支持“处理未知类别” 现在我会用 myEncoder = OneHotEncoder(sparse=False, handle_unknown='ignore') myEncoder.fit(df[columnsToEncode]) pd.concat([df.drop(columnsToEncode, 1), ... -
我想你可以使用get_dummies : df = pd.DataFrame({'ids':['a','b','c']}) print (df) ids 0 a 1 b 2 c print (df.ids.str.get_dummies()) a b c 0 1 0 0 1 0 1 0 2 0 0 1 编辑: 如果输入是带lists ,首先转换为str ,删除[] by strip并调用get_dummies : df = pd.DataFrame({'id ...
-
我认为你需要使用get_dummies map 。 也似乎第一次0:00需要0 : 0:30 - 1所以使用range(48) #convert to datetimes if necessary df['time'] = pd.to_datetime(df['time']) #create dictionary for map a = dict(zip(pd.date_range('2010-01-01', '2010-01-01 23:59:39', freq='30T').time, range(4 ...
-
你的主要问题似乎是二进制化的y不适合你的记忆。 您可以使用稀疏数组来避免这种情况。 >>> import numpy as np >>> from scipy.sparse import csc_matrix >>> y = np.random.randint(0, 10000, size=5000000) # 5M random integers [0,10K) 您可以将这些标签y转换为5M x 10K稀疏矩阵,如下所示: >>> dtype = np.uint8 # change to np.bool ...
-
如果我理解你的例子,你需要tf.gather_nd range = tf.range(tf.shape(examples)[0]) indices = tf.pack([range, examples], axis=1) result = tf.gather_nd(probs, indices) If I understood your example correctly, you need tf.gather_nd range = tf.range(tf.shape(examples)[0]) indi ...
-
您可以使用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 ...
-
创建一个热门的熊猫数据帧(Create a one-hot panda dataframe)[2022-12-21]
方法#1:这是NumPy broadcasting的一种方法 - In [143]: a = [2 ,7 ,5 ,3] In [144]: pd.DataFrame((np.asarray(a)[:,None] == np.arange(10)).astype(int)) Out[144]: 0 1 2 3 4 5 6 7 8 9 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 2 0 0 0 ...