我有一个程序,我需要尽可能多地插入单词,然后通过数据库检查这些单词,如果它存在于数据库中,它应该返回数据库中存在多少单词。 请告诉我这段代码有什么问题,它没有向数据库返回类似条目的数量
<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+' ';
}
</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>
答案 0 :(得分:0)
$db->num_rows
已经是行数...您无需手动计算它们。
答案 1 :(得分:0)
$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;
答案 2 :(得分:0)
在for循环中运行查询是不可行的,所以你可以尝试下面的解决方案,
$array=array('abc','xyz','lmn','pqr');
$query="select word from collection where word LIKE '%".$s."%'";
$result=$db->query($query);
while ( $row = mysql_fetch_array($result) )
{
$tblarray[] = $row['word'];
}
foreach($tblarray as $k => $v)
{
foreach($array AS $key => $value)
{
if (strpos($v, $value) !== false)
{
$finalarray[] = $v;
}
}
}
echo sum($finalarray);