2015-11-26 126 views
1

我有此代碼放在一個MySQL數據庫從XML Shoutcast的喜歡的歌信息: 藝術家曲集標題PHP的爆炸功能的問題

它的工作原理,但如果這張專輯是不存在的插入是錯誤的,如果只是爲了插入藝術家和標題而缺少專輯,是否有辦法? 我的代碼:

$artist = $xml->SERVERTITLE; 
$title = $xml->SONGTITLE; 
$pieces = explode("-", $title); 

$pieces[0] = trim($pieces[0]); 
$pieces[1] = trim($pieces[1]); 
$pieces[2] = trim($pieces[2]); 
$sql = "INSERT INTO test_xml (`title`, `album`, `artist`) VALUES ('$pieces[2]', '$pieces[1]', '$pieces[0]') ON DUPLICATE KEY UPDATE time = now(), album = VALUES(album)"; 

回答

0
$artist = $xml->SERVERTITLE; 
$title = $xml->SONGTITLE; 
$pieces = explode("-", $title); 

if (count($pieces) < 3) { 
    $pieces[0] = trim($pieces[0]); 
    $pieces[2] = trim($pieces[1]); 
    $pieces[1] = ""; 
} else { 
    $pieces[0] = trim($pieces[0]); 
    $pieces[1] = trim($pieces[1]); 
    $pieces[2] = trim($pieces[2]); 
} 
$sql = "INSERT INTO test_xml (`title`, `album`, `artist`) " 
    . "VALUES ('$pieces[2]', '$pieces[1]', '$pieces[0]') " 
    . "ON DUPLICATE KEY UPDATE time = now(), album = VALUES(album)"; 
+0

謝謝哈塞,它的工作原理,越簡單最好。 –

0

array_padhttp://php.net/array_pad)可能是你想要什麼:

$artist = $xml->SERVERTITLE; 
$title = $xml->SONGTITLE; 
$pieces = array_pad(explode("-", $title), 3, ''); 

$pieces[0] = trim($pieces[0]); 
$pieces[1] = trim($pieces[1]); 
$pieces[2] = trim($pieces[2]); 
$sql = "INSERT INTO test_xml (`title`, `album`, `artist`) VALUES ('$pieces[2]', '$pieces[1]', '$pieces[0]') ON DUPLICATE KEY UPDATE time = now(), album = VALUES(album)"; 

數組的字符串是explode d成將被傳遞到array_pad,如果它不是號你想要的物品(3)它會將數組填充到那麼多。

+0

問題是,如果有專輯,你會得到'藝術家[0],專輯[1],標題[2]'。如果沒有專輯,你最終會得到一個空的標題和專輯中的標題,比如'artist [0],title [1],album [2]'! –

+0

謝謝你的時間Jeffwa,並指出我有關array_pad,目標永遠在學習。 –

0

嘗試

for ($i = 0; $i < 3; $i++) { 
    $pieces[$i] = empty(trim($pieces[$i])) ? 'NULL' : "'".trim($pieces[$i])."'"; 
} 
$sql = "INSERT INTO test_xml (`title`, `album`, `artist`) VALUES ($pieces[2], $pieces[1], $pieces[0]) ON DUPLICATE KEY UPDATE time = now(), album = VALUES(album)"; 

,而不是

$pieces[0] = trim($pieces[0]); 
$pieces[1] = trim($pieces[1]); 
$pieces[2] = trim($pieces[2]); 
$sql = "INSERT INTO test_xml (`title`, `album`, `artist`) VALUES ('$pieces[2]', '$pieces[1]', '$pieces[0]') ON DUPLICATE KEY UPDATE time = now(), album = VALUES(album)"; 
+0

謝謝你mnv,我會稍後再試,但哈斯先回復。 –