这段代码应该检查用户在发布输入时是否登录,如果是,它会检查ItemID和UserID是否已经在表中有一个条目,如果有,它会更新该条目,而不是创建一个重复条目。
这是我需要的输出:
+--------+-------+----------+
| ItemID | Price | user |
+--------+-------+----------+
| 1 | 20 | 27 |
+--------+-------+----------+
这就是我得到的:
+--------+-------+----------+
| ItemID | Price | user |
+--------+-------+----------+
| 0 | 0 | 27 |
+--------+-------+----------+
如果需要,以下是完整的功能:http://pastebin.com/W0UM68UT
if ( is_user_logged_in() ) {
$hf_user = get_current_user_id();
$hf_username = $hf_user->user_login;
global $quanid;
$inputValue = isset($_POST[$quanid]);
global $newdb;
$newdb = new wpdb( 'user', 'pass', 'db', 'localhost' );
$retval = $newdb->get_results("SELECT * FROM $table WHERE ItemID = '$quanid' AND user = '$hf_username' ");
if($retval > 0)
{
//If user exists, update
$newdb->replace($table,array(
'ItemID' => '$quanid',
'Price' => $inputValue,
'user' => $hf_username
)
);
}
else
{
global $table;
global $newdb;
$newdb->insert(
$table,
array(
'ItemID' => $quanid,
'Price' => $inputValue,
'user' => $hf_username
)
);
}
} else {
global $error;
$error = "Error: You must be logged in to submit prices";
return;
}
}
请不要使用全局变量。。。
如何避免使用PHP全局对象?
将SELECT语句更改为计数以获得更好的性能:
SELECT count( 1 ) FROM $table WHERE ItemID = '$quanid' AND user = '$hf_username'
关于你的问题:
global $quanid;
和isset($_POST[$quanid]);
似乎返回了意外值,因此您应该查看它们的设置位置。尝试使用:
var_dump就在这两行下面:
global $quanid;
$inputValue = isset($_POST[$quanid]);
var_dump( $quanid );
var_dump( $inputValue );
var_dump( $_POST);
die;