如何在php for mysql中使用数组值或类似的东西选择数据?

时间:2017-10-21 23:28:41

标签: php html mysql sql

有人可以告诉我如何做到这一点,或者是否有可能向我展示另一种方式?

我试图获取用户输入的描述并切掉一些单词,然后获取第一个单词并搜索我的数据库中是否有另一个单词就像在与该单词相关联的单词的描述中那样

这整个事情有点像字典

$word = (isset($_POST['word']) ? $_POST['word'] : null);
$description = (isset($_POST['description']) ? $_POST['description'] : 
null);
echo "<br>" . "<br>";//this is why its showing
$Slicer = array( ' a ', 'A ', 'The ', ' the ', ' an ', ' this ', ' that 
',
' these ', ' those ', ' my ', ' your ', ' his ', ' her ', ' its ',
' it\'s ', ' our ', ' their ', ' few ', ' little ', ' much ', ' many ',
' lot ', ' of ', ' most ', ' some ', ' any ', ' enough ', ' all ', ' 
both ',
' either ', ' neither ', ' each ', ' every ', ' other ', ' another ',
' Here ', ' I ',    ' me ', ' mine ',   ' myself ', ' i ',
' you ', ' your\'s ', ' yourself ', ' he ', ' him ', ' his ',
' himself ', ' she ', ' her\'s ', ' herself ', ' itself ',
' we ', ' us ', ' our ', ' ours ', ' ourselves ', ' yourselves ',
' they ',   ' them ', ' theirs ', ' themselves ', ' no ', ' none ',
' not ', ' any ', ' few ', ' few ', ' several ', ' great ', ' deal ',
' lot ', ' lots ', ' large ', ' amount ', ' plenty ', ' more ',
' fewer ', ' fewest ', ' less ', ' least ', ' what ', 'she\'s',
'the ', ' to ', ' for ', ' something ', ' or ', ' used ',
' represent ', ' in ', ' by ', ' are ', ' often ', ' called ', 'a ', 
'.');

$sliced = str_replace($Slicer,' ',$description);
echo $sliced;
echo "<br>";
$SWords = (explode(" ",$sliced));
echo "<br>";

$FirstWord = $SWords[1];
echo "<br>";
echo $FirstWord;
echo "<br>";
$test = "test";

$sql = "SELECT * FROM WordDatabase WHERE description LIKE '" 
.$FirstWord."'"; 

我有更多的代码,我连接到我的数据库和一切

1 个答案:

答案 0 :(得分:0)

1不是php中数字数组的第一个索引。 php(以及几乎所有其他编程语言)中的所有索引都以0开头。

所以第一个单词将在

$FirstWord = $SWords[0];

你最有可能使用LIKE错误。就像没有通配符(%will in most cases (but not allways)一样,结果与=相同。因此WHERE description LIKE 'foo'可能会与WHERE description = 'foo'相同(只是可能更慢),这很可能是你想要的。

也许你想要这样的东西:

SELECT * FROM WordDatabase WHERE description LIKE 'foo%'

SELECT * FROM WordDatabase WHERE description LIKE '%foo%'

此外,您的代码可能容易受到SQL注入攻击。请不要自己将用户输入直接连接到查询。相反,使用mysqliPDO或使用这两者之一的框架,并使用他们的方法创建这样的预准备语句:

$mysqli = new mysqli($host, $user, $pass, $db);
if (mysqli_connect_errno()) {
  throw new Exception('Could not connect to database: ' . mysqli_connect_error());
}
if ($sql = $mysqli->prepare("SELECT description FROM WordDatabase WHERE description LIKE ?")) {
    $sql->bind_param("s", $FirstWord . '%');
    $sql->execute();
    $sql->bind_result($description);
    $sql->fetch();
    $sql->close();
} else {
    # ....
}
$mysqli->close();