javascript - 无法将数据库中的数据与字符串数组进行比较

标签 javascript php html mysql arrays

我有一个程序,我需要插入尽可能多的单词,然后这些单词将通过数据库进行检查,如果它存在于数据库中,它应该返回数据库中存在多少单词。 请告诉我这段代码有什么问题,它没有将类似条目的数量返回到数据库

<html>
<head>

<script language="javascript" type="text/javascript">
// Pre-defined text:
var newtext = "This is the new text";
// Drop-Menu:
var newtext = myform.mymenu.options[myform.mymenu.selectedIndex].value;
// Prompt:
var newtext = prompt('Enter New Text Here:', '');
function addtext() {
    var newtext = document.myform.inputtext.value;
    document.myform.outputtext.value += newtext+'&nbsp;';
}

</script>
</head>
<body>
<form name="myform" action="" method="post">
<table border="0" cellspacing="0" cellpadding="5"><tr>
<td><textarea name="inputtext"></textarea></td>
<input type="radio" name="placement" value="append" checked> Add to Existing Text<br>
<td><p><input type="radio" name="placement" value="replace"> Replace Existing Text<br>
<input type="button" value="Add New Text" onClick="addtext();"></p>
</td>
<td><textarea name="outputtext"></textarea></td>
</tr></table>
<input type="submit"/>
</form>
<?php
$string=$_POST['outputtext'];
$array=array();
$array=explode(';',$string);
@ $db=new mysqli('localhost','root','','words');
if(mysqli_connect_errno())
{
    echo 'Error:Could not connect to the database';
}
else
echo 'connected';
$db->select_db('words');
$count = 0;
foreach($array as $s)
{    
    $query="select * from collection where word LIKE '%".$s."%'";
    $result=$db->query($query);
    if($result)
    $count += $db->num_rows;    
}
echo $count;
$db->close();
?>
</body>
</html>

最佳答案

$count = 0;
foreach($array as $s)
{    
    $query="select count(*) as num_matched from collection where word LIKE '%".$s."%'";
    $result=$db->query($query) or die($db->error);
    $row = $result->fetch_assoc();
    $count += $row['num_matched'];
}
echo $count;

您还应该切换到参数化查询,而不是直接使用输入。

$stmt = $db->prepare("select count(*)
                      FROM collection
                      WHERE word LIKE CONCAT('%', ?, '%')");
$stmt->bind_param("s", $s);
$count = 0;
foreach ($array as $s) {
    $result = $stmt->execute();
    $stmt->bind_result($num_matched);
    $stmt->fetch();
    $count += $num_matched;
}
echo $count;

关于javascript - 无法将数据库中的数据与字符串数组进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22064475/

相关文章:

PHP 能够处理多个 TCP 连接吗?

javascript - 将列表传递给 Parse.Promise.when 但仅获取 promise 链中的第一个元素

JavaScript 递归计算重复字母

javascript - 如何将 javascript 和 css 文件添加到 magentomodule

javascript - 使用 Google Geocoding API 将命名实体识别标记文件链接到 Google map

javascript - 为什么不触发 ondrop html 事件?

javascript - 单击按钮刷新 <div id ="RefhreshableDiv"> 内容

javascript - jQuery 双对象构造函数 - 例如$($(这个))

php - 子域不适用于 CodeIgniter

php - 如何使用 PDO 通过 select 命令调用过程?