我正在尝试从wordpress自定义表中读取数据。我创建了表并从中获取数据。现在我需要为表中的每一行创建链接,当我点击链接时,它应该只删除一行。
global $wpdb;
$table_name = $wpdb->prefix . 'customtable';
$sql = "SELECT * FROM $table_name";
$check = $wpdb->get_results($sql);
echo '<div class="col-lg-2">';
foreach ($check as $loc){
echo $loc->row1;
echo '<br>';
echo '<form action="" method="post" enctype="multipart/form-data">';
echo '<input type="submit" name="delete" value="Delete" />';
echo '</form>';
echo '<br>';
}
echo '</div>';
if( isset( $_REQUEST['delete'] ))
{
$wpdb->delete( $table_name, [ 'id' => $loc->id] );
}
链接正常,但我无法删除特定的行。
我尝试创建函数删除
function delete($id){
global $wpdb;
$table_name = $wpdb->prefix . 'customtable';
$wpdb->delete( $table_name, [ 'id' => $id] );
}
然后在foreach循环之外我定义了
if (isset($_REQUEST['delete'])){
$this->delete($loc->id);
}
但同样只删除最后一行。
答案 0 :(得分:0)
所以我找到了这个解决方案。如果我在foreach循环中调用delete链接,它将删除整个表,如果我在外面调用它,则只删除最后一行。 我在插件文件夹中创建了php脚本并将id发布到其中。
$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$url = $_SERVER['REQUEST_URI'];
$my_url = explode('wp-content' , $url);
$path = $_SERVER['DOCUMENT_ROOT']."/".$my_url[0];
include_once $path . '/wp-config.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';
if (isset($_REQUEST['ID'])){
$id = $_REQUEST['ID'];
delete_row($id);
}
function delete_row($id){
global $wpdb;
$table_name = $wpdb->prefix . 'customtable';
$wpdb->query(
$wpdb->prepare(
"
DELETE FROM $table_name
WHERE id = %d",
$id
)
);
}
和内部函数,从数据库读取所有数据并生成删除链接:
foreach ($check as $loc){
echo $loc->location;
echo '<br>';
echo '<a name="delete" href="'.$dir.'delete_loc.php?ID=' . $loc->id . '">delete</a>';
echo '<br>';
}