Php爆炸功能问题

时间:2015-11-26 19:12:32

标签: php mysql shoutcast

我已经将这段代码放入一个mysql数据库中,来自xml shoutcast的歌曲信息如: 艺术家专辑标题

它有效,但如果专辑不在那里插入错误,有没有办法,如果缺少专辑只是插入艺术家和标题。 我的代码:

$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)";

3 个答案:

答案 0 :(得分: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)";

答案 1 :(得分: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进入的数组将传递给array_pad,如果它不是你想要的项目数(3)项,它将把数组填充到那么多。< / p>

答案 2 :(得分: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)";