当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Getting value from array in a for loop to use in MySQL

问题描述:

What I have is a custom admin page within Wordpress where the user can add names/titles/mp3's which all gets entered into the database. On the same page, I also have it select all the entries from the database and list them with checkboxes next to them and I'm trying to get it to delete the checked entries from the database using an array. This what I have so far:

$songs = $_POST['song'];

$num = count($songs);

for($i=0; $i < $num; $i++){

$sql = "DELETE FROM song_list WHERE title = '".$songs[]."'";

echo $sql;

var_dump($songs);

}

When I dump $songs, it has all the correct data, but when I try to pull it and add it to the query, I keep getting nothing. It's not an associative array, so I tried $songs[0] and $songs[1], but I get nothing.

Any insight would be appreciated, thank you.

EDIT:

var_dump

array(3) { ["Forget You"]=> string(2) "on" ["DJ Got Us Falling in Love"]=> string(2) "on" ["Blurred Lines"]=> string(2) "on" }

Also, I tried adding $i ($songs[$i]). It just comes out as title = ''

网友答案:

Your missing the array index:

$songs[$i]

Turns into:

$songs = $_POST['song'];
    $num = count($songs);
    for($i=0; $i < $num; $i++){
        $sql = "DELETE FROM song_list WHERE title = '".$songs[$i]."'";
        echo $sql;
    }

An more elegant way is to use a foreach loop:

$songs = $_POST['song'];
foreach($songs as $song) {
    $sql = "DELETE FROM song_list WHERE title = '".$song."'";
    echo $sql;
}

An even more elegant way is to use prepared statements (with PDO):

// Prepare statement
$stmt = $dbh->prepare('DELETE FROM song_list WHERE title = :song');

$songs = $_POST['song'];
foreach($songs as $song) {
    // Bind and execute
    $stmt->bindParam(':song', $song);
    $stmt->execute();
}
网友答案:

Just to make it much simpler and shorter - one-liner :)

$sql =  "DELETE FROM song_list " .
        "WHERE title IN ('" . implode("','", $_POST['song']) . "')";

Things to note:

  • Be aware of SQL injection attacks - never ever concatenate user input strings ($_GET, $_POST etc.) directly into SQL!
  • Deleting by title is very bad solution, because if you'll have in title for example symbol ', then your SQL will break. That's why in SQL id fields are invented :)
网友答案:

Adding $i to your array and you will get the value at the given place. But you can write your code like this :

if(isset($_POST['song']) {
    foreach($_POST['song'] as $key => $title) {
        $sql = "DELETE FROM song_list WHERE title = '".$title."'";
        echo $sql;
    }
}    
分享给朋友:
您可能感兴趣的文章:
随机阅读: