2013-02-27 4 views
1

은 테이블이있다 :PHP는 MySQL을 업데이트 HTML 양식

|id name surname email | 
|1 john surjohn @mail.com| 
|2 peter pet @mail.com|     
|.........................| 

PHP : 내가 그렇지 않으면 업데이트 된 테이블이 null 값을 가질 수있는 모든 필드를 업데이트해야 할이 양식에서

<?php 
if(isset($_POST['update'])) 
{ 
... 
$conn = mysql_connect($dbhost, $dbuser, $dbpass); 
if(! $conn) 
{ 
    die('Could not connect: ' . mysql_error()); 

} 

$id = $_POST['id']; 
$name = $_POST['name']; 
$surname = $_POST['surname']; 
$mail = $_POST['mail']; 

$sql = "UPDATE emps ". 
     "SET name= '$name', surname'$surname', email='$mail' ". 
     "WHERE Id = $id" ; 
mysql_select_db('dbase'); 
$retval = mysql_query($sql, $conn); 
if(! $retval) 
{ 
    die('Could not update data: ' . mysql_error()); 
} 
echo "blablablabla ! \n"; 
mysql_close($conn); 
} 
else 

{ 
?> 
<form method="post" action="<?php $_PHP_SELF ?>"> 
    <fieldset style="width: 350px" > 
<table width="400" border="0" cellspacing="1" cellpadding="2"> 
<tr> 
<td width="100">Id </td> 
<td><input name="id" type="text" id="id" value=""></td> 
</tr> 
<tr> 
<td width="100">name</td> 
<td><input type="text" maxlength="15" name="name" value="" ></td> 
</tr> 
<tr> 
<td width="100">surname</td> 
<td><input type="text" maxlength="40" name="surname" value="" ></td> 
</tr> 
<tr> 

<td width="100"> </td> 
<td> 
<input name="update" type="submit" id="update" value="update"> 
</td> 
</tr> 
</table> 
     </fieldset> 
</form> 
<?php 
} 
?> 
    } 

. 예를 들어 이름 필드를 업데이트하고 싶지만 성을 남겨두고 기존 값을 전자 메일로 보냅니다. 아이디어?

+0

당신이 무엇을 요구하고 있는지 잘 모름. – MeLight

+2

가장 좋은 방법은 입력 값을 데이터베이스의 값으로 채우는 것입니다. 누군가가 정보를 변경하면 업데이트하고, 그렇지 않으면 데이터베이스에있는 정보로 업데이트됩니다. – Karl

+0

질문을 해결할 수 있습니까? 이해하지 못 했어. –

답변

0

은 다음과 같이 뭔가를 시도 할 수 :

$id = $_POST['id']; 
$name = $_POST['name']; 
$surname = $_POST['surname']; 
$mail = $_POST['mail']; 

$sql = "UPDATE emps SET"; 
$moresql = ''; 

if(isset($name) && !empty($name)) { 
    $moresql .= " name = '$name'"; 
} 

if(isset($surname) && !empty($surname)) { 
    if ($moresql) $moresql .= ','; 
    $moresql .= " surname = '$surname'";  
} 

if(isset($mail) && !empty($mail)) { 
    if ($moresql) $moresql .= ','; 
    $moresql .= " mail = '$mail'"; 
} 

$sql .= $moresql; 
$sql .= " WHERE Id = '$id'"; 

이 비록 안된이다.

+0

내 대답, 테스트 및 작동 업데이트. – Karl

0

칼의 생각은 갈 수있는 방법이지만이 방법 리팩토링 할 수 있습니다

$id = $_POST['id']; 

$sql = "UPDATE emps SET"; 
$fieldValuePairs = array(); 

foreach($_POST as $key => value) 
    if($key != 'id') 
     $fieldValuePairs[] = "'$key' = '$value'"; 

$sql .= " ". implode(',', $fieldValuePairs)." WHERE id = $id"; 

참고 : 데이터베이스에서 (열 이름을 (형태) 입력 이름을 사용하는 동일있을 경우에만 작동을).

멋진 하루 되십시오.