我需要通过本地python脚本在wordpress中设置一些用户元。因此,我不能对它使用WPupdate_user_meta
,它必须手动完成
import mysql.connector as mysql
cnx = mysql.connect(host=HOST, database=DATABASE, user=USER, password=PASSWORD)
cursor = cnx.cursor()
get_meta = ("SELECT * FROM `ff_usermeta` WHERE `user_id`= 1 AND (`meta_key`='nickname' OR `meta_key`='info' OR `meta_key`='bg' OR `meta_key`='avatar' OR `meta_key`='profile_updated')")
cursor.execute(get_meta)
meta = cursor.fetchall()
#some processing of the result
cursor.execute(q, (...))
cnx.commit()
cursor.close()
cnx.close()
现在我需要检查每个键的结果是否都有meta。 如果此用户的密钥已存在,则需要为此元运行更新。 如果此用户仍然没有此键的meta,则必须插入新行
if(there's no 'nickname' in meta_key on either of 5 or less rows):
q = ("INSERT INTO `ff_usermeta` ...")
else:
q = ("UPDATE `ff_usermeta` ...")
…还有4次这样的事?。。似乎是一个循环的好地方,但我不太喜欢将其设为5倍队列的想法,特别是因为将来可能会有更多字段
我一直在考虑在fetchall结果中搜索meta_键中的匹配项,如果找到,则将所需数据添加到一个数组中,如果没有,则添加到另一个数组中。然后在最后运行一个更新和一个插入,假设两者都不是空的。如果我用半php风格编写,它大致如下所示:
if(in_array("nickname", meta))
for_update .= "`nickname`='"+data[0]+"', "
else:
fields .= "`nickname`, "
vals .= "'"+data[0]+"', "
if(in_array("bg", meta)):
for_update .= "`bg`='"+data[1]+"', "
else:
fields .= "`bg`, "
vals .= "'"+data[1]+"', "
if(for_update):
update = ("UPDATE `ff_usermeta` SET "+for_update+" WHERE 1")
if(fields):
insert = ("INSERT INTO `ff_usermeta`("+fields+") VALUES ("+vals+")")
但绝对不知道如何正确地将其翻译成python。我不得不在谷歌上搜索“为什么dot不把一个字符串添加到另一个”之类的东西。有什么建议吗?或者也许有更好的方法?谢谢
我尽了最大的努力去适应上面的建议,但不知道如何使它起作用。最后我换了一种方式,它似乎以某种方式工作,所以我将发布完整的代码,以防有人发现它有用
它的作用:使用验证请求检查表中的队列,然后解析页面(单独的函数)并相应地更新用户配置文件
它不完整,不能以这种方式更新行
但有了这个,你就可以开始提问了
如果用户id存在,则第一个select正好得到1行
对于这一点,用户id似乎不是正确的选择,但要获得您所能做的就足够了
如果查询没有条目,它将插入从任何地方获得的一些数据
插入时的更新是错误的,因为您必须插入5个新ORW或最多更新5行,但这对您编程来说更重要
相关问题 更多 >
编程相关推荐