如何像这样转换字符串:
"joe,anna,kwame,kofi"
自:
"joe","anna","kwame","kofi"
我正在尝试在带有 IN 子句的 sql 语句中使用它,但不断收到如下所示的错误:
上次 SQL 查询失败:
SELECT * FROM view_salesreport WHERE deleted =0 AND saletype IN (dropoff,pickup)
谁能帮忙
// split string into array based on commas
// result: array("joe","anna","kwame","kofi")
$arr = explode(",","joe,anna,kwame,kofi");
// create a string with a "?" for each item in the array
// result: ?, ?, ?, ?
$in = str_repeat('?,', count($arr) - 1) . '?';
// insert $in in SQL query
// result: SELECT * FROM view_salesreport WHERE deleted = 0 AND saletype IN (?, ?, ?, ?)
$sql = "SELECT * FROM view_salesreport WHERE deleted = 0 AND saletype IN ($in)";
// prepares a statement for execution
$stm = $db->prepare($sql);
// executes a prepared statement with array of parameters
$stm->execute($arr);
http://php.net/manual/de/function.explode.php
尝试这样的事情:
$output = ''
foreach (explode(',' , $yourString) as $name) {
$output . = $name
}
你可以试试这个:
$string = "joe,anna,kwame,kofi";
$string = str_replace("'","'''",$string);
$string = "'".str_replace(',',"','",$string)."'";
您可以轻松地使用 explode()
和 implode()
来获取所需的字符串格式。 例如:
$initial_string = "joe,anna,kwame,kofi";
// split string into array based on commas
$names = explode(',', $initial_string);
// combine back into string using implode
$query = "SELECT * FROM view_salesreport WHERE deleted =0 AND saletype IN ('" . implode("','", $names) . "')";