我正在尝试使用表单上的选择框的name属性来使用更新查询。一切都传递到$ _POST并且INSERT查询工作正常,但我无法弄清楚为什么我的if语句的更新部分没有进入我的数据库。任何建议都非常感谢。
<?php
global $wpdb;
$Call_Number = $_POST['Call_Number'];
$datas = $_POST['REG'];
$columns = implode(",",array_keys($datas));
$values = implode("','",$datas);
$result = $wpdb->get_results ("SELECT Call_Number FROM DG_Pro_Coach WHERE Call_Number = '".$Call_Number."'");
if (count ($result) > 0) {
$row = current ($result);
$wpdb->query ("UPDATE DG_Pro_Coach SET ".$columns."='".$values."' WHERE Call_Number = '".$Call_Number."'");
} else {
$wpdb->query("INSERT INTO DG_Pro_Coach (".$columns.",Call_Number ) VALUES ('".$values."','$Call_Number' )");
}
?>
答案 0 :(得分:2)
<强>问题强>
您的查询应如下所示:
UPDATE database SET column1=value1, column2=value2(...) WHERE condition
但它看起来像这样:
UPDATE database SET column1,column2(...) = value1,value2(...) WHERE condition
<强>解决方案强>
<?php
global $wpdb;
$Call_Number = $_POST['Call_Number'];
$datas = $_POST['REG'];
$columns = implode(",",array_keys($datas));
$values = implode("','",$datas);
$updatelist = "";
foreach($datas as $key=>$value){
$updatelist .= $key."=".$value.",";
}
$updatelist = substr($updatelist,0,strlen($updatelist)-1);
$result = $wpdb->get_results ("SELECT Call_Number FROM DG_Pro_Coach WHERE Call_Number = '".$Call_Number."'");
if (count ($result) > 0) {
$row = current ($result);
$wpdb->query ("UPDATE DG_Pro_Coach SET ".$updatelist."' WHERE Call_Number = '".$Call_Number."'");
} else {
$wpdb->query("INSERT INTO DG_Pro_Coach (".$columns.",Call_Number ) VALUES ('".$values."','$Call_Number' )");
}
?>
答案 1 :(得分:1)
您的更新查询语法错误,因为您以错误的方式包含PHP数组中的数据。
对于那些输入参数:
$Call_Number = '123456789';
$datas = array('one' => 1, 'two' => 2);
创建此查询:
UPDATE DG_Pro_Coach SET one,two='1','2' WHERE Call_Number = '123456789'
可能的解决方案:
$update_array = array();
foreach ($datas as $column=>$value) {
$update_array[] = "$column = '$value'";
}
$update_string = implode(', ', $update_array);
$wpdb->query ("UPDATE DG_Pro_Coach SET ".$update_string.' WHERE Call_Number = '".$Call_Number."'");
答案 2 :(得分:0)
非常感谢所有的帮助,这是工作代码。
<?php
global $wpdb;
$Call_Number = $_POST['Call_Number'];
$datas = $_POST['REG'];
$columns = implode(",",array_keys($datas));
$values = implode("','",$datas);
$updatelist = "";
foreach($datas as $key=>$value){
$updatelist .= $key."='".$value."', ";
}
$updatelist = substr($updatelist,0,strlen($updatelist)-2);
$result = $wpdb->get_results ("SELECT Call_Number FROM DG_Pro_Coach WHERE Call_Number = '".$Call_Number."'");
if (count ($result) > 0) {
$row = current ($result);
$wpdb->query ("UPDATE DG_Pro_Coach SET ".$updatelist." WHERE Call_Number = '".$Call_Number."'");
} else {
$wpdb->query("INSERT INTO DG_Pro_Coach (".$columns.",Call_Number ) VALUES ('".$values."','$Call_Number' )");
}
?>