Php 爆炸功能问题

Php explode function issue

我编写了这段代码,将来自 xml shoutcast 的歌曲信息放入 mysql 数据库中,例如: artist-album-title

它有效,但如果专辑不存在,则插入错误,如果专辑丢失,是否有办法只插入艺术家和标题。 我的代码:

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

array_pad (http://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)";

您的字符串 exploded 进入的数组将被传递给 array_pad,如果它不是您想要的项目数 (3),它会将数组填充到那么多.

尝试

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