制作一个搜索现有单词组合的小脚本。使用script.php获取AJAX?req =%param%其中%param%是DB中的条目。 对于单个请求,它工作正常,根据需要返回下一个值。但我根本无法理解如何找到按空格划分的条目:
$REQUEST = isset( $_GET['req'] )? $_GET['req']: false;
echo $REQUEST;
$mysqli = new mysqli("localhost", "username", "1337", "database");
$query = "SELECT `first_col` , `second_col` FROM `table` WHERE `first_col` = '" . $REQUEST . "'";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
$pieces = explode(", ", $row['second_col']); //explodes given data using comma and space
echo $pieces['0']; //prints out first part of req output
$result->free();
$mysqli->close();
但是当我要求某种形式的时候:
?REQ =单词+ another_word
脚本没有返回任何内容,因为它无法找到这样的条目" word another_word"。它必须打印出空格而不是逗号。
如何找到每个表的所有条目并将其打印在一个不带逗号的字符串中,仅用空格除外?
答案 0 :(得分:0)
如果只是'+',您想用空格str_replace()
代替:
$REQUEST = isset( $_GET['req'] )? str_replace('+', ' ', $_GET['req']): false;
请远离您的意见:
$query = "SELECT `first_col` , `second_col` FROM `table` WHERE `first_col` = '" . mysqli_real_escape_string($REQUEST) . "'";
答案 1 :(得分:0)
好的,你应该尝试这样的事情。基本上,您在查询中使用关键字IN,因此您准备了一个单词列表。之后,您将遍历结果。
$REQUEST = isset( $_GET['req'] )? $_GET['req']: false;
echo $REQUEST;
$words = "'" . str_replace(" ", "','", $REQUEST) . "'"; // you will have something like: 'word','another_word','etc'
$mysqli = new mysqli("localhost", "username", "1337", "database");
$query = "SELECT `first_col`, `second_col`
FROM `table`
WHERE `first_col` IN (" . $words .")
ORDER BY FIELD(first_col, $words)";
$result = $mysqli->query($query);
$output = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$pieces = explode(", ", $row['second_col']); //explodes given data using comma and space
$output[] = $pieces['0']; // adds first part of req output to the output array
}
$result->free();
$mysqli->close();
echo implode(" ", $output);