unable to compare data from database to array of strings - javascript

i have a program where i need to insert words as much as i wish and then those words will be checked through database, if it is present in database , it should return how many words where present in database.
please tell me what is wrong with this code, it is not returning the number of similar entries to database
<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>

$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;
You should also switch to parametrized queries instead of using the input directly.
$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;

$db->num_rows is already the number of rows... You don't need to manually count them.

its not feasible to run query in for loop so, you can try below solution,
$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);

Related

Issue when when PHP is used to load data from custom Date-time picker for dc.js chart

The HTML page contains the form for selecting dates and loads with the visualization with all the data. After selecting the date, the visualization must be updated. But, in this case, it is loading again with the same full data instead of selected data. The javascript file is written separately which calls the PHP file to fetch data.
PHP code get_JSON.php to obtain data from the database.
<?php
include_once("connection.php");
$tablename = "button_timeint";
if ((isset($_POST['in1'])) && (isset($_POST['in1']))) {
$from_lbl = isset($_POST['in1']) ? $_POST['in1']:"";
$to_lbl = isset($_POST['in2']) ? $_POST['in2']:"";
$d1 = date_create($from_lbl);
$from = date_format($d1, 'YmdHis.u');
$d2 = date_create($to_lbl);
$to = date_format($d2, 'YmdHis.u');
$myquery = "SELECT * FROM button_timeint WHERE buttonID = 5 and date
BETWEEN '$from' AND '$to' ORDER BY DATE";
$query = mysqli_query($connection,$myquery);
if ( ! $query ) {
echo mysqli_error($connection);
die;
}
$data = array();
for ($x = 0; $x < mysqli_num_rows($query); $x++) {
$data[] = mysqli_fetch_assoc($query);
}
echo json_encode($data);
}
else{
$myquery = "SELECT * FROM button_timeint";
$query = mysqli_query($connection,$myquery);
if ( ! $query ) {
echo mysqli_error($connection);
die;
}
$data = array();
for ($x = 0; $x < mysqli_num_rows($query); $x++) {
$data[] = mysqli_fetch_assoc($query);
}
echo json_encode($data);
}
mysqli_close($server);
?>
The code line where PHP file is called in the javascript where d3 takes its input.
var dataSet_selected = "get_JSON.php";
d3.json(dataSet_selected, function(err,data){}
HTML form for the date time picker.
<form method="post">
<table>
<tr>
<td><label>From: </label></td>
<td><input type="datetime-local" name="in1"></td>
</tr>
<tr>
<td><label>To: </label></td>
<td><input type="datetime-local" name="in2"></td>
</tr>
<tr>
<td><input id ="submit_btn" type="submit" value="submit" ></td>
</tr>
</table>
</form>

Sending two values to PHP via ajax POST to query SQL db

I'm trying to send two values from a form to another PHP using ajax post method. One value is the value that's already entered in an input box, and the other is a value that is being typed into another input box. It acts like a search box. I tried executing the SQL query in my SQL workbench and it returns the value properly. What am I doing wrong in my code?
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate},function(sbb){
$("#sbb").html(sbb);
//searchq7();
});
}
This is the input box where I search and get the value from:
<input type="text" name="region" list="state" value="<?php echo $region; ?>" placeholder="Select State" id="output">
Suburb:
<input type="text" name="suburb" list="sbb" value="<?php echo $suburb; ?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6" >
<option> </option>
</datalist>
This is the search-suburb.php file:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state="'.$st.'" AND `title` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
}else{
while($row = mysqli_fetch_array($query)){
$suburb = $row['title'];
?>
<option value="<?php echo $suburb; ?>"><?php echo $suburb; ?> </option>
<?php
} // while
} // else
} // main if
<input type="text" name="region" list="state" value="<?=(isset($_POST['region'])?$_POST['region']:'');?>" placeholder="Select State" id="output">
Suburb:
<input type="text" name="suburb" onkeyup="searchq6()" list="sbb" value="<?=(isset($_POST['suburb'])?$_POST['suburb']:'');?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6"></datalist>
Javascript:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate},function(sbb){
var decode = jQuery.parseJSON(sbb); // parse the json returned array
var str = ""; // initialize a stringbuilder
$.each(decode, function (x, y) {
str+="<option value='" + y.title +"'>";
});
$("#sbb").html(str);
}); // end of post
}// end of searchq6 function
Php:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='{$st}' AND `title` LIKE '%{$searchq}%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
} else{
$data = array();
while($row = mysqli_fetch_array($query))
$data[] = $row;
echo json_encode($data);
}
} // main if
Got the answer from small snippets gathered through the comments
Changed the query to:
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='".$st."' AND `title` LIKE '%".$searchq."%' LIMIT 10")or die("Could not search!");
And the ajax to:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate})
.done(function(sbb) {
$("#sbb").html(sbb);
});
//searchq7();
}
Thanks for all the comments guys

How to create search box in php?

I have implemented search box for my website by using php, html and jquery.
Firstly, I have created a database,
using php I have sorted the values and
using jquery and html I have shown the search result in a div below the search box.
My problem is that I am not able to select the result using down or up key, for this I also tried to make the result in list or drop box in php.
Please correct me if I am wrong some where. Below is the code which is I am using.
<body>
<h1>Search web page</h1>
<form action="search_demo.php" method="post" >
<input type="text" name="search" placeholder="search here" onkeydown="searchq();" />
<input type="submit" value=">>" />
<div id="output" style="z-index: 10; position: absolute ; background-color: yellow;">
</div>
<div id="stable" style="">
</div>
</form>
</body>
<script>
function searchq(){
var searchtxt = $("input[name='search']").val();
$.post("search_demo12.php", {searchval : searchtxt}, function(output) {
$("#output").html(output);
});
}
</script>
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST['searchval'])){
$search = $_POST['searchval'];
// $search = preg_replace("#[^0-9a-z]#i","",$search);
$pieces = explode(" ", $search);
$pieces_count = count($pieces);
// $pieces[0] = preg_replace("#[^0-9a-z]#i"," ",$pieces[0]);
// $pieces[1] = preg_replace("#[^0-9a-z]#i"," ",$pieces[1]);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select * from search_demo where fname like '%$search%' or lname like '%$search%'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$pname = $row['fname'];
$purl = $row['lname'];
//if($piece == $row['brand']){
$output .= '<option>'.$pname.' '.$purl.'</option>';
}
}
echo ($output);
Do you mean you cannot select results using up and down keys?
I think it is because you are not wrapping options in select list . Do this
while($row = $result->fetch_assoc()){
$pname = $row['fname'];
$purl = $row['lname'];
//if($piece == $row['brand']){
$output .= '<option>'.$pname.' '.$purl.'</option>';
}
echo "<select>".$output."</select>";
In this case I think that it's better to use onkeyup() JavaScript function as you are implementing live search and need output to be changed dynamically..

Search engine - how to handle empty queries

New to this group. Need tip to ignore empty search box queries. The following code works fine but when I click the search button with nothing in the text field, it gives me all my page links as results. I would want no action for an empty box search...thanks in advance folks!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<form action='./search.php' method='get'>
<input type='text' name='k' size='15' value='<?php echo isset($_GET['k']) ? $_GET['k'] : ""; ?>' placeholder=' ' />
<input type="image" src="images/magnifier.png" width="14" height="14" border="0" >
</form>
<h2>Search Results</h2>
<hr />
<?php
$k = isset($_GET['k']) ? $_GET['k'] : "";
$terms = explode(" ", $k);
$query = "SELECT * FROM search WHERE ";
$i = 0;
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
// connect to DB
mysql_connect("localhost", "root", "mypwd");
mysql_select_db("busqueda");
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo "<h2><a href='$link'>$title</a></h2>
$description<br /><br />";
//empty query variable before coming back to home page
$k = null;
}
}
else
echo "No results found for \"<b>$k</b>\"";
//empty query variable before coming back to home page
$k = null;
//disconnect from DB
mysql_close();
?>
</body>
</html>
Just don't do anything if you get an empty query
if (empty($_GET['k']) or trim($_GET['k']) == ''){
exit;// or something
}
also you can prevent the form from submitting an empty query with the required attribute
<form action='./search.php' method='get'>
<input type='text' name='k' required size='15' value='<?php echo isset($_GET['k']) ? $_GET['k'] : ""; ?>' placeholder=' ' />
<input type="image" src="images/magnifier.png" width="14" height="14" border="0" >
</form>
before getting to
$terms = explode(" ", $k);
check if $k is not empty
if($k !=''){
// put here your query structure and database stuff
// now we are sure that there is some content in the k field
}
Just wrap the rest of your code after defining $k with and if statement like so:
if($k != ""){
//execute search
}
If required='true' is not enough (at the client-side), as you might want to prevent a submit (codes assumes jQuery usage) and do some stuff:
$(document).ready(function() {
$('form').submit(function() { // replace by form #id selector
if ($(this).find('[name=k]').val().trim() == '') {
return false; // do other stuff, as warn user
}
});
});

Not going inside correct loop on checking two checkboxes

I have a code in which i am having checkboxes of two categories one of brand and and other of discount percentage.Based on those checkboxes,div s are getting filtered.Filteration of divs is happening ok but with a small issue.
Below is the firstphp page
<html>
<head>
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
#image{
width:250px;
height:250px;
border:1px solid black;
}
</style>
</head>
<body>
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="brand"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
function get_disc_value(){
var d_value=[];
$('input[name="discount"]:checked').each(function () {
d_value.push(this.value);
});
return d_value.join(',');
}
$(document).ready(function(){
checkboxValidate = function (e) {
if(e)e.preventDefault();
alert("hi");
//var os = $('#originState').val();
//var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
var disc=get_disc_value();
//var queryString = "os=" + os;
var data = "?ser=" + ser;
var queryString = "&ser=" + ser;
// alert(ser);
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: {ser:ser,disc:disc},
dataType : 'html',
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
}
$( "[type=checkbox]" ).change(checkboxValidate);
checkboxValidate();
});
</script>
brand
<input type="checkbox" name="brand" value="Sunbaby" id="check" />Sunbaby
<br/>
<input type="checkbox" name="brand" value="Advance Baby" id="check"/>Advance Baby
<br/>
store
<br/>
<input type="checkbox" name="discount" value="10" />10
<br/>
<input type="checkbox" name="discount" value="20" />20
<br/>
<input type="checkbox" name="discount" value="30" />30
<br/>
<button id="btnSubmit">sort</button>
<div id="image">
<img src="http://img5a.flixcart.com/image/sunglass/4/u/y/mb-d4-09b-miami-blues-free-size-275x275-imadzkhuchryqjgp.jpeg" width="250px" height="250px"/>
</div>
<div id="results">
sdfsdfsdfsdfdsfgsdgsbsfgvf
</div>
</body>
</html>
Asortingajax.php-where i m checking with database
<?php
include('connection.php');
$query=$_POST['ser'];
$query2=$_POST['disc'];
$query=explode(",",$query);
$query = array_filter($query);
$query2=explode(",",$query2);
$query2 = array_filter($query2);
$result=count($query);
$result1=count($query1);
//echo $result;
echo $query;
echo $query1;
echo $result1;
$parts = array();
$brandarray=array();
$discarray=array();
$limit = 10;
$offset = 0;
foreach( $query as $queryword ){
$brandarray[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
foreach( $query2 as $discword ){
$discarray[] = '`DPERCENT` < '.$discword.'';
}
if(!empty($query) && !empty($query2))
{
echo "both loops";
$countsql2='SELECT * FROM xml WHERE ('.implode ('OR',$brandarray).') AND ('.implode ('OR',$discarray).') ';
print($countsql2);
$combinesql=mysql_query($countsql2);
$androws123 = mysql_num_rows($combinesql);
$countArray1=array();
echo "<br />";
echo $androws123;
$totalrows=0;
$orsqlrows=0;
while($row = mysql_fetch_array($countsql3)) {
// Append to the array
$countArray1[] = $row;
//echo $row['PID']."<BR />";
}
if(empty($countArray1))
{
echo "or";
$orsql='SELECT * FROM xml WHERE ('.implode ('OR',$brandarray).') AND ('.implode ('OR',$discarray).') ';
$orsql1=mysql_query($orsql);
$orsqlrows = mysql_num_rows($orsql1);
$countArray2=array();
echo $orsqlrows;
while($row = mysql_fetch_array($countsql1)) {
// Append to the array
$countArray2[] = $row;
//echo $row['PID']."<BR />";
}
}
$totalrows=$orsqlrows+$androws123;
echo $orsqlrows;
echo "hi";
echo $androws123;
if($totalrows==$androws123)
{
echo "and";
foreach( $brandcheck as $queryword ){
$brandarray[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
$brandsql='SELECT * FROM XML WHERE ('.implode ('OR',$brandarray).') AND ('.implode ('OR',$discarray).') limit '.$offset.', '.$limit.' ';
$brandsql1=mysql_query($brandsql);
$numrows = mysql_num_rows($brandsql1);
$countArray=array();
//print($brandsql);
echo "<br />";
while($row = mysql_fetch_array($brandsql1)) {
// Append to the array
$countArray[] = $row;
//echo $row['PID']."<BR />";
}
}
else{
foreach( $brandcheck as $queryword ){
$brandarray[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
echo "orloop";
$brandsql='SELECT * FROM XML WHERE ('.implode ('OR',$brandarray).') AND ('.implode ('OR',$discarray).') limit '.$offset.', '.$limit.' ';
//print($brandsql);
$brandsql1=mysql_query($brandsql);
$numrows = mysql_num_rows($brandsql1);
$countArray=array();
//print($brandsql);
echo "<br />";
echo $numrows;
while($row = mysql_fetch_array($brandsql1)) {
// Append to the array
$countArray[] = $row;
//echo $row['PID']."<BR />";
}
}
}
?>
<?php
foreach($countArray as $array)
{
?>
<div>
<img src="<?php echo $array['IMAGEURL']?>"/></div>
<?php $i++; } ?>
I n the first php page.when i m checking one brand checkbox and one discount checkbox at a time,means one from both brand and discount are checked.div s are getting filtered correctly.but when i check two checkboxes out of discount checkboxes and one from brand,I am not getting divs filtered correctly whereas div s should get filtered.
Help me guys where i m doing wrong in above code...
Have you echoed the query to see what you get? It seems to me it's working fine as long as there's no actual implode 'glue' used (the 'OR'). I think you need to change the glue part to ' OR ' (notice the spaces around it).

Categories