2011-08-15 39 views
0

我有以下的PHP/SQL的例子,當編輯一行&保存更改時可以很好地工作。PHP/MYSQL/XHTML FORM。如何一次更新多行表?

它基於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"); 

} 

?> 

我的問題是如何更新多行表/格式如this one

+0

2件小事。 1)對於你的cookie,輸入這個等式的結果並且評論它正在做什麼。無需每次加載都要進行計算。 2)有沒有你不使用BEGIN - COMMIT/ROLLBACK的原因?你可能想這樣做,因爲它確實失敗。 – afuzzyllama

+0

@afuzzyllama - 原因是我剛開始使用PHP/MYSQL。我不知道所有的選項。 – Iladarsda

+0

@afuzzyllama - cookie被設置爲'remeber me'字段 - 「登錄」系統的一部分。不是SQL查詢的一部分。 – Iladarsda

回答

1

最好的辦法是用簡單的for loop

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. 
} 

由於您只設置一個布爾字段,你也可以做這樣的事情:

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

但我建議你做循環,因爲你將不可避免地需要更新,在其他領域有一點與此查詢。

+0

行數不確定。你能舉一個在這個例子中使用for循環的例子嗎? – Iladarsda

+0

我們的情況'somefield = 1'會代表什麼?這是否意味着這行ID中的'somefield = 1'? – Iladarsda

+0

您的案例中的'somefield'將會是'live' – afuzzyllama