2014-02-27 72 views
0

我有一个程序,我需要根据需要插入单词,然后通过数据库检查这些单词,如果它存在于数据库中,它应返回多少在数据库中存在的词。 请告诉我,什么是错的这个代码,它是不相似的条目数返回数据库无法将数据库中的数据与字符串数组进行比较

<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> 
+0

你不是在你的查询中使用'$ s'运行在for循环的话,你可以试试下面的解决方案查询。 – Barmar

+0

它没有显示我在textarea中输入的单词数量已经在数据库中。 – Vivek

+0

$ array存储输入的单词。 – Vivek

回答

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; 
+0

它返回我在数据库中的条目数量,而不是匹配的条目数量。 – Vivek

+0

它不应该。它应该只计算匹配的条目。尝试打印'$ query'并确保它包含您在'LIKE'子句中所期望的内容。 – Barmar

0

$db->num_rows已经是行数......你并不需要手动计数。

0

其不可行

$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); 
相关问题