我目前正在开发一个WordPress项目,该项目上面有商店的WooCommerce插件。但是,订单中的所有结算信息都会转到wp_postmeta表,其中所有信息都保存在同一列“meta_value”中。
我有一个表格,客户可以使用他们的订单号,名字和邮政编号填写,并在提交此字段后,他们的订单将显示在网站上。
因此,在我的查询中,我只想检查用户输入的订单号,名字和邮政编号是否为真,我不需要列中的任何其他内容。
我已经使用我的凭据制作了测试订单,目前我的查询看起来像这样,但它找到了两个结果,因为wp_postmeta表中有两个字段具有相同的订单号,并且它们的顺序与订单相同:
$ordernumber = $_POST['ordernmbr'];
$orderfirstname = $_POST['firstname'];
$orderpostnumber = $_POST['postnmbr'];
$sql = $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}postmeta
WHERE post_id = %d AND meta_value = %s",
$ordernumber, $orderfirstname);
$res = $wpdb->get_results($sql, ARRAY_A);
问我是否有什么不清楚,我很难解释事情!
编辑:从Vel获得帮助后更新了查询,仍未按预期工作,因为查询不希望找到任何结果。
$sql = $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}postmeta
WHERE post_id = %d AND (meta_value = %s AND meta_key ='_billing_first_name' AND meta_value = %s AND meta_key ='_billing_postcode') ",
$ordernumber, $orderfirstname, $orderpostnumber );
$res = $wpdb->get_results($sql, ARRAY_A);
以下SQL查询将检查给定订单ID,名字和邮政编码是否存在条目:
$ordernumber = $_POST['ordernmbr'];
$orderfirstname = $_POST['firstname'];
$orderpostnumber = $_POST['postnmbr'];
$result = $wpdb->get_col( $wpdb->prepare( "
SELECT pm.post_id
FROM $wpdb->postmeta as pm
JOIN $wpdb->postmeta as pm1 ON pm.post_id = pm1.post_id
WHERE pm.post_id = %d
AND pm.meta_key ='_billing_first_name'
AND pm.meta_value = %s
AND pm1.meta_key ='_billing_postcode'
AND pm1.meta_value = %s
", $ordernumber, $orderfirstname, $orderpostnumber ) );
if( sizeof($result) )
$result = true;
经过测试和工作。
它也可以用get_post_meta()
Wordpress函数这样做:
$firstname = get_post_meta( $_POST['ordernmbr'], '_billing_first_name', true );
$postnmbr = get_post_meta( $_POST['ordernmbr'], '_billing_postcode', true );
if( $firstname == $_POST['firstname'] && $postnmbr == $_POST['postnmbr'] ) {
// The data match
} elseif( $firstname == $_POST['firstname'] || $postnmbr == $_POST['postnmbr'] ) {
// The data match partially
else {
// The data don't match
}
谢谢大家的帮助,但实际上我自己设法解决了这个问题:
$sql = $wpdb->prepare("SELECT post_id FROM wp_postmeta
WHERE post_id = %d AND meta_key in ('_billing_first_name', '_billing_postcode')
and meta_value in ('%s', '%d')
group by post_id", $ordernumber, $orderfirstname, $orderpostnumber);
您需要使用meta_key。
$ordernumber = $_POST['ordernmbr'];
$orderfirstname = $_POST['firstname'];
$orderpostnumber = $_POST['postnmbr'];
$sql = $wpdb->prepare( "select * from (SELECT * FROM wp_postmeta WHERE ( meta_key = '_billing_first_name' AND meta_value =%s )
OR ( meta_key = '_shipping_postcode' AND meta_value =%s ) ) as p
where post_id=%s", $orderfirstname, $orderpostnumber, $ordernumber );
$res = $wpdb->get_results($sql, ARRAY_A);
更新的查询
select * from (SELECT * FROM wp_postmeta WHERE ( meta_key = '_billing_first_name' AND meta_value ='Gnanavel' ) OR ( meta_key = '_shipping_postcode' AND meta_value ='622222' ) ) as p where post_id=2899