Foreach变量更新数据库wordpress

时间:2014-11-04 13:49:56

标签: php wordpress variables foreach

如何给变量更新wordpress数据库?

如果不是变量,我给数字是好的,我认为这是一个错误。

    global $wpdb;
    $wpdb->teams = $wpdb->prefix.'teams';
    $retrieve_data = $wpdb->get_results( "SELECT * FROM $wpdb->teams WHERE moder = 'nie'" );

    foreach ($retrieve_data as $retrieved_data){
        echo "<form method='post'><table><tr>";
        echo "<td>".$retrieved_data->id."</td>";
        echo "<td>".$retrieved_data->nazwa."<input type='hidden' name='id'>".$retrieved_data->id."</input><input type='submit' value='OK' /></td>";
        echo "</tr></table></form>";
    }

    $id = $_POST['id'];
    settype($id, 'int');
    $wpdb->update( 'teams', array( 'moder' => 'tak' ), array( 'id' => $id ));

3 个答案:

答案 0 :(得分:0)

你所做的基本上是错的。您显示表单,然后您只更新您的表没有值。提交表单后,然后更新表。但是,如果有人加载页面,并且不提交表单,那么您将再次使用0更新。

我认为,您还需要验证id字段。

以这种方式尝试:

global $wpdb;
$wpdb->teams = $wpdb->prefix . 'teams';

//Do this before any output in the buffer...

//Check is there is a $_POST["id"]. And move this update block to the top of your file
if (isset($_POST["id"])) {
    $id = $_POST['id'];
    settype($id, 'int');
    $wpdb->update('teams', array('moder' => 'tak'), array('id' => $id));
    //redirect the user to somewhere
    header ("Location: " . $_SERVER["PHP_SELF"]);
}


$retrieve_data = $wpdb->get_results("SELECT * FROM $wpdb->teams WHERE moder = 'nie'");

foreach ($retrieve_data as $retrieved_data) {
    echo "<form method='post'><table><tr>";
    echo "<td>" . $retrieved_data->id . "</td>";
    echo "<td>" . $retrieved_data->nazwa . "<input type='hidden' name='id'>" . $retrieved_data->id . "</input><input type='submit' value='OK' /></td>";
    echo "</tr></table></form>";
}

答案 1 :(得分:0)

错误:&#34;无法修改标头信息 - 已在C:\ wamp中发送的标头(输出从C:\ wamp \ www \ mtb \ wp-content \ themes \ seebcioo \ header.php:16开始)第17行&#34; \ www \ mtb \ wp-content \ themes \ seebcioo \ panel-adm-teams.php

第17行:标题(&#34;位置:&#34;。$ _SERVER [&#34; PHP_SELF&#34;]);

答案 2 :(得分:0)

OK!完了:) 谢谢 :) 最终代码

  global $wpdb;
$table = $wpdb->prefix . "teams";
$retrieve_data = $wpdb->get_results( "SELECT * FROM $table WHERE moder = 'nie'" );

foreach ($retrieve_data as $retrieved_data) {
    echo "<form method='post'><table><tr>";
    echo "<td>".$retrieved_data->id."</td>";
    echo "<td>".$retrieved_data->nazwa."<input type='text' name='id' value='$retrieved_data->id' /><input type='submit' name='test' value='OK' /></td>";
    echo "</tr></table></form>";
}

print_r($_POST);
$id = $_POST['id'];
$table = $wpdb->prefix . "teams";
$wpdb->update( $table, array( 'moder' => 'tak' ), array( 'id' => $id ));