0

我应该能够弄清楚这一点,但我一直在绕圈子。我有一个带有复选框的表格。当复选框被选中时,它们被标记为被删除。

我用 foreach 处理那些选中的复选框:

foreach (array_keys($_POST['checkboxselect']) as $k) {
    $str .= $k.',';
}

这是我将视频列表放在一起的蹩脚尝试。我正在使用的 sql delete 是:

DELETE FROM `videos` WHERE `video_name` IN ($str)

所以我在这里错过了很多东西。$str需要具备:

  1. 只返回一个复选框,因此返回带引号的字符串(即“myvideo.mp4”)
  2. 选择了多个复选框,因此使用引号和逗号构建一个字符串(即“myvideo.mp4”、“myvideo2.mp4”、“myvideo3.mp4”)

谢谢您的帮助。

4

2 回答 2

2

像这样使用implode()

$str = '"' . implode('","', array_keys($_POST['checkboxselect'])) . '"';

implode()将采用一个数组并将数组中的每个值与“胶水”字符串连接起来。在这种情况下,“胶水”是","并且数组由 中的键组成$_POST['checkboxselect']。最后,生成的字符串被包裹在".

这将产生您想要的示例字符串"myvideo.mp4","myvideo2.mp4","myvideo3.mp4"

于 2012-04-25T03:31:37.377 回答
2

尝试使用 PHP 的implode

// Init links
$mysqliLink = mysqli_connect('host', 'user', 'password') or die('Could not connect: ' . mysqli_error());

$mysqlLink = mysql_connect('host', 'user', 'password') or die('Could not connect: ' . mysql_error());

//-----
// Prep values for query
//-----

// Only pick one of the following depending upon the mysql library you are using

// If using mysql, passing the 2nd argument is not necessary, but for 
// clarity, adding it
$deleteNames = array_map('mysql_real_escape_string', array_keys($_POST['checkboxselect']), array_fill(0, count($_POST['checkboxselect']), $mysqlLink));

// If using mysqli
// This will ensure that $mysqliLink will be passed in as first arg for 
// every iteration satisfying the function signature
$deleteNames = array_map('mysqli_real_escape_string', array_fill(0, count($_POST['checkboxselect']), $mysqliLink), array_keys($_POST['checkboxselect']));
//-----


// Because you are passing strings, we need to ensure each is wrapped in quotes
$deleteNames = "'" . implode("','", $deleteNames) . "'";

// Construct query using implode
$sql = sprintf('DELETE FROM `videos` WHERE `video_name` IN (%s)', $deleteNames); 

- 更新 -

使用 Joomla API:

$db = &JFactory::getDBO();

// Localize and sanitize each individual value
foreach (array_keys($_POST['checkboxselect']) as $element) {
    $deleteNames[] = $db->quote($element);
}

// Because you are passing strings, we need to ensure each is wrapped in quotes
// No longer true because $db->quote taking care of quoting out each name for us
$deleteNames = implode(',', $deleteNames);

// Construct query using implode
$sql = sprintf('DELETE FROM `videos` WHERE `video_name` IN (%s)', $deleteNames);
于 2012-04-25T03:35:57.267 回答