【发布时间】:2020-03-09 13:52:08
【问题描述】:
我需要帮助来弄清楚为什么这不起作用。我显然不明白在数据库中插入变量的语法。如果没有数组中的变量,则此数据库插入正在运行,因此问题不会来自那里。我还在文件中进一步回显该变量,以便该变量存在并起作用。
if(isset($_POST['ticket_priority']))
{
// Get the nonce value for validation
$nonce = $_POST['ticket_nonce'];
// If the nonce does not verify, do NOT process the form.
if ( ! wp_verify_nonce($nonce, 'MyNonceAction')) {
// If this spits out an error, that means the nonce failed
echo 'Security error. Do not process the form.';
return;
}
insert_row();
}
$donneesPost = get_post();
echo $donneesPost->ID; //this works
function insert_row()
{
global $wpdb, $donneesPost;
$tablename = 'pp_candidates';
$data = array(
'candidate_email' => 'email@email.com', //just to see that without a variable it functions
'project_ID' => $donneesPost->ID,
'candidate_approved' => '1'
);
var_dump($data);
$formats = array(
// '%d', // ticket_id should be an integer
// '%s', // ticket_user_id should be an integer
// '%d', // ticket_description should be a string
// '%s' // ticket_user_id should be an integer
);
$wpdb->show_errors();
$wpdb->insert($tablename, $data, $formats);
}
function display_form(){
echo '
<form action="" method="post">';
// Add a nonce field
wp_nonce_field('MyNonceAction', 'ticket_nonce');
echo '
<input type="submit" name="ticket_priority" value = "Postuler pour ce projet" id="insertcandidatebutton">
</form>
';
}
display_form();
这是我得到的错误:
Erreur de la base de données WordPress : [列 'project_ID' 不能 为空] INSERT INTO
pp_candidates(candidate_email,project_ID,candidate_approved) 值('emqil@email.com',NULL,'1')
这里是grumpy提出的解决方案
// This is what it was like in the original post
insert_row();
}
$donneesPost = get_post();
// This is what I changed to get it to work
$donneesPost = get_post();
insert_row();
}
【问题讨论】:
-
$donneesPost->ID是null,这是表格不允许的。$donneesPost来自哪里?需要明确的是,您的问题不是因为您使用的是变量,而是因为您使用的变量不存在。 -
您可能只需将
$donneesPost = get_post();移动到您调用insert_row();的正上方。实际上,您应该将$donneesPost传递给函数insert_row(get_post()); -
@GrumpysaysReinstateMonica 我从没想过把 insert_row() 放在上面。那成功了。谢谢。由于您发表了评论但没有回答,我不知道如何接受您的解决方案。所以我改变了 $donneesPost = get_post();插入行(); } 再次感谢
标签: php mysql wordpress variables syntax