我有来自一个简单插件的两段代码,它们彼此独立工作,但不能一起工作。
if(isset($_POST['submit'])){
if(has_presence($_POST['product_name'])){
insert_row_into_table('CAL_products');
show_errors();
if(has_presence($wpdb->last_query)) {
echo "Update Successful";
} else {
echo "Update Failed";
}
} else {
echo "The field 'Product Name' cannot be blank.";
}
}
还有这个
$results_array = $wpdb->get_results("SELECT * FROM wpCMS_CAL_products ORDER BY id ASC");
echo build_table_from_results_array($results_array);
这些功能包含在底部。
我遇到的问题是,当页面加载时没有 $_POST,因此它会跳过 if 语句并构建表。这个表构建得很好。
提交表单时,if 语句返回 true,并且新值已成功添加到数据库中,但在刷新页面之前不会构建表。如果构建表的代码放在 if 语句上方的顶部,它构建得很好,但在刷新页面之前不包含新值。
是否可以在将结果填充到 HTML 表之前向数据库表添加新项目?
function insert_row_into_table($table_name){
global $wpdb;
$prefix = $wpdb->prefix; //Define the wordpress table prefix
$table = $prefix . $table_name; //Build the table name
unset($_POST['submit']);
echo print_r($_POST);
$data = $_POST; //collect the data from post
$wpdb->insert( $table, $data ); //insert data into the table
}
function show_errors(){
echo $wpdb->show_errors();
echo $wpdb->print_error();
}
function has_presence($value) {
return isset($value) && $value !== "";
}
function build_table_from_results_array($results_array) {
$out = "";
$out .= "<table class=\"widefat\">";
$out .= "<thead>";
foreach($results_array[0] as $key => $element) {
if($key == "id") {
$out .= "<th class=\"id-column\">";
$out .= strtoupper($key);
$out .= "</th>";
} else {
$out .= "<th>";
$out .= ucwords(str_replace("_", " ", $key));
$out .= "</th>";
}
}
$out .= "</thead>";
$out .= "<tbody>";
$i = 0;
foreach($results_array as $key => $element){
if($i % 2 === 0) $extraclass= "alternate";
$out .= "<tr class=\"$extraclass\">";
$i++;
$extraclass="";
foreach($element as $subkey => $subelement){
$out .= "<td>$subelement</td>";
}
$out .= "<td><a href=\"#\">EDIT</a></td>";
$out .= "</tr>";
}
$out .= "</tbody>";
$out .= "</table>";
return $out;
}
最佳答案
此类页面的一般模式是 Post-Redirect-Get.例如,您可以将 if(isset($_POST['submit'])) block 提取到名为 processForm.php 的单独文件中。表单的操作参数更改为processForm.php。该表单将 $_POST 数据发送到 processForm,后者插入新的数据库记录,而 processForm 又将用户重定向回获取结果的原始页面。
如果您想要使用上述代码的单页解决方案,请在输出任何内容之前将此代码添加到文件的最顶部。这会启动输出缓冲区,如果您想使用 header() 命令进行重定向,这通常是必需的。
ob_start();
然后编辑 if(isset) block :
if(isset($_POST['submit'])){
if(has_presence($_POST['product_name'])){
insert_row_into_table('CAL_products');
show_errors();
if(has_presence($wpdb->last_query)) {
echo "Update Successful";
header("Location: index.php"); //change index.php to the current page
//header("Location: ".$from); //or use a variable
} else {
echo "Update Failed";
}
} else {
echo "The field 'Product Name' cannot be blank.";
}
}
最后,将其添加到脚本的最后以关闭输出缓冲区:
ob_end_flush();
本质上,此代码会在新条目插入数据库后成功刷新页面。这应该允许您的表包含新记录。
关于php - 在 WordPress 插件(PHP CRUD)中进行多个数据库调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22149314/