비교

2014-03-27 3 views
0

나는이 정말 (a,b,c,d)비교

+0

편집 해 주셔서 감사합니다. 이제 우리는 이해할 수 있습니다 :) – mesutozer

+9

이런 식으로 문제는 데이터베이스에 이런 식으로 목록을 저장해서는 안된다는 것입니다. – Barmar

+0

데이터베이스에서 이전 값을 가져오고, 괄호를 제거하고, 문자열을 배열로 분해하고, 새 값을 배열과 병합하고, 배열을 문자열로 implode하고, 괄호로 묶은 다음 DB를 업데이트합니다. – Barmar

답변

0

당신과 열을 업데이트 할 항목 (b,c,d) 을 가지고 MySQL의에서 문자열 $string = (a,b,c)

나는 열이 쉼표로 구분 PHP는 한 필드에 여러 값을 데이터베이스에 저장하면 안됩니다. 원하는대로 할 수는 있지만 매우 비효율적입니다. 스키마를 정규화하고 두 테이블과 일대 다 관계를 사용하는 방법에 대해 생각해보십시오.

그러나해야한다면 다음과 같이 할 수 있습니다. 은이 코드에 오류 처리를 추가해야합니다.

//connect to the database and read existing data 
$dbh = new PDO(CONNECT_STRING, USERNAME, PASSWORD); 
$dbs = $dbh->query("select data_string from my_table where id=1"); 
$row = $dbs->fetch(PDO:FETCH_NUM); 
$dbs->closeCursor(); 

//strip parentheses and convert string to array 
$cur_data = str_getcsv(substr($row[0], 1, -1)); 

//strip parentheses and convert new data to array 
$string = "(a,b,c)"; 
$add_data = str_getcsv(substr($string, 1, -1)); 

//merge existing and new data eliminating duplicates 
$new_data = array_unique(array_merge($cur_data, $add_data)); 

//create new csv string for the merged data 
$output = fopen('php://output', 'w'); 
ob_start(); 
fputcsv($output, $new_data); 
fclose($output); 
$value = ob_get_clean(); 

//update database table with new csv string with parentheses 
$dbs = $dbh->prepare("update my_table set data_string=? where id=?"); 
$dbs->execute(array("($value)", 1)); 
$dbs->close(); 

얼마나 많은 불필요한 작업이 필요합니까? 나는 당신이 당신의 스키마를 재 설계 할 것을 정말로 촉구한다.

0

나는 이것이 당신이 원하는 것이라고 생각합니다.

<?php 
$string = "b, c, d"; 
$pieces = explode(",", $string); 

for($index=count($pieces); $index>0; $index--){ 
    $pieces[$index] = $pieces[$index-1]; 
} 

$pieces[0] = "a"; 
$string = implode(", ", $pieces); 
echo $string; 
?> 
0
$string = '(a,b,c)'; 
$column = '(b,c,d)'; 

$string = substr($string, 1, -1); 
$column = substr($column, 1, -1); 

$string = explode(',', $string); 
$column = explode(',', $column); 

$result = array_unique(array_merge($string, $column), SORT_STRING); 
$result = '(' . implode(',', $result) . ')'; 

이제 실마리를 얻을.

+0

감사합니다 ... – user3462665