簡體   English   中英

PHP/MYSQL/XHTML 表格。 如何一次更新多行表?

[英]PHP/MYSQL/ XHTML FORM. How to update multi row table at once?

我有以下 PHP/SQL 示例,它在編輯一行和保存更改時運行良好。

它基於 POST/GET 方法工作 - 其中 URL 正在設置要編輯/保存的行 ID。

form -> post id & live values

seperate php file -> get 'id' and change row with this 'id'.

<?php

session_name('users');
session_set_cookie_params(2*7*24*60*60);
session_start();

define('INCLUDE_CHECK',true);

require 'connect.php';
require 'functions.php';

if(!$_SESSION['id']) {
    header ("Location: index.php"); 
}


//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
    $str = @trim($str);
    if(get_magic_quotes_gpc()) {
        $str = stripslashes($str);
    }

    return mysql_real_escape_string($str);
}

//Sanitize the POST values
$id = clean($_POST['id']);
$usr2 = $_SESSION['usr'];
$live = (isset($_POST['live']))?1:0;
$updated = date("F j, Y, g:i a",time()+60*60);
$title = clean($_POST['title']);
$content = clean($_POST['content']);

//Create INSERT query
$qry = "UPDATE table SET live = '$live' WHERE id='".mysql_real_escape_string($_POST['id']). "'  ";
$result = mysql_query($qry);
echo mysql_error();

//Check whether the query was successful or not
if($result) {
    header("location: notes.php");
    exit();
}else {
    die("Query failed");

}

?>

我的問題是如何像這樣更新多行表格/表格?

最好的方法是使用簡單的 for 循環

foreach ($_POST as $key=>$value) {
    // You didn't provide the names of the fields, so you will need to validate them here yourself.
    // I usually name them with a prefix, like somefield_3, and then I can use substr() to determine if the field is the one I'm looking for.

    $result=mysql_query("UPDATE whatever SET somefield=1 WHERE id=" . mysql_real_escape_string($key) . ";");

    //etc., etc.
}

由於您只設置了一個 boolean 字段,您還可以執行以下操作:

UPDATE table SET live=1 WHERE id IN (1,2,3,4,5);

但我建議執行循環,因為您將不可避免地需要在某些時候使用此查詢更新其他字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM