简体   繁体   English

PHP / SQL从不更新仅插入

[英]PHP/SQL never updates only inserts

For some reason my insert/update check only ever inserts. 由于某种原因,我的插入/更新检查仅进行过插入。 the value userID does have a value so i dont know what is up with this. 值userID确实有一个值,所以我不知道这是怎么回事。 Any ideas? 有任何想法吗?

$result = mysql_query("SELECT * FROM users where userID = $userID ");
if (mysql_num_rows($result) > 0) {
   mysql_query("UPDATE users SET firstName='$firstName', lastName='$lastName', 
             birthday='$birthday', update='$today', accessToken='$accessToken', emailOne='$emailOne' WHERE userID='$userId'");
} else {
   mysql_query("INSERT INTO users (userID, firstName, lastName, birthday, updated, accessToken, emailOne ) 
               VALUES ('$userId', '$firstName', '$lastName','$birthday', '$today', '$accessToken', '$emailOne')");
}

You'd be far better off doing INSERT ... ON DUPLICATE KEY UPDATE . INSERT ... ON DUPLICATE KEY UPDATE进行INSERT ... ON DUPLICATE KEY UPDATE会更好。 Your version is subject to race conditions. 您的版本取决于比赛条件。 It's entirely possible that between the time you do the SELECT * and then attempt the update/insert queries, ANOTHER script has already inserted the same ID number and then your script breaks. 在执行SELECT *并尝试更新/插入查询之间,完全有可能ANOTHER脚本已经插入了相同的ID号,然后脚本中断。 This also reduces the database load by one query. 这也减少了一个查询的数据库负载。

As well, unless you've passed all those variables in the query through mysql_real_escape_string() , you'll probably be getting a visit from Little Bobby Tables . 同样,除非您已通过mysql_real_escape_string()在查询中传递了所有这些变量,否则您可能会从Little Bobby Tables获得访问。

From the way you're inserting the records, it seems that your userId field is a varchar (or alphanumeric) field. 从插入记录的方式来看,您的userId字段似乎是varchar (或字母数字)字段。 So your query NEVER reads the data that matches it since it is searching for it as a numeric. 因此,您的查询从不读取与其匹配的数据,因为它正在以数字形式搜索它。 You've got to re-write the first line as: 您必须将第一行重写为:

$result = mysql_query("SELECT * FROM users where userID = '$userID' ");

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM