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).
Related
I've been hanging on this problem for 3 days and just can't solve it. It seems relatively simple, but unfortunately, I can't do it, because I'm a noob.
I would like to use the button's onclick function to get its 2 pieces of information
```html
<input id="'.$row['id'].'" type="button" value="Pause" name="'.$row['name'].'" onclick="pushDataToDB()">```
name = "'. $ row [' name '].'" [the name reference from a database
table]
and value="Pause"
this two informations i would like to store in some other database table.
I have tried to solve this problem in different ways.
I have tried to store in different ways the event.target.name & event.target.event javascript output in PHP Variables and then use it in the mysql insert line but i failed.
I have tried to post the value to the ajax.php then store the value in a PHP variable and use this as Value to push it to the database, but this also doesn't work
index.php
<div class="button2">
<form action="ajax.php" method="POST">
<input id="'.$row['id'].'" type="button" value="Pause" name="'.$row['name'].'" onclick="pushDataToDB()">
</Form>
</div>'
script.js:
function pushDataToDB() {
$.get("ajax.php");
return false;
}
ajax.php
<?php
include_once ('dbh.php');
if(isset($_POST['name'])){
$sqlAufPause = "INSERT INTO aktuellaufpause (name, pausenart) VALUES ('$name', 'BP')";
}
if ($conn->query($sqlAufPause) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
I would say this is the reason, why the name Value is empty,
but i don't know how to fix ist..
emptyNameValue
You can use JQuery + AJAX to perform asynchronous POST
<?php
$con = mysqli_connect("localhost", "root", "", "testdb");
$query = mysqli_query($con, "SELECT * FROM mytable WHERE id = 1");
$row = mysqli_fetch_assoc($query);
print_r($row);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="button2">
<form id="frm">
<input id="<?php echo $row['id'] ?>" type="button" value="Pause" name="<?php echo $row['name'] ?>" onclick="pushDataToDB()">
</Form>
</div>
</body>
<script type="text/javascript">
function pushDataToDB() {
var name = "<?php echo $row['name'] ?>";
var value = "Pause";
$.ajax({
url: "ajax.php",
type: "POST",
data: {
"name": name,
"value": value
},
success: function(e) {
if (e == "1") {
alert("Success!");
} else {
alert("error!");
}
}
});
}
</script>
</html>
ajax.php
<?php
$con = mysqli_connect("localhost", "root", "", "testdb");
$name = $_POST['name'];
$value = $_POST['value'];
$query = "INSERT INTO mytable(name, value) values('$name','$value')";
$result = mysqli_query($con, $query);
if ($result) {
echo "1";
} else {
echo "Error!";
}
EDITTTT****
I changed
var name = "<?php echo $row['id'] ?>";
to
var name = "<?php echo $row['name'] ?>";
since it is the "name" you want stored in the database
I solved the problem this way.
Thank you so much!!!
index.php
<?php
$sql = "SELECT * FROM `DB-TABLENAME` ORDER BY `VALUE1`, `VALUE2`";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td>";
echo '<input style="margin: 0 auto 6px 17px;" type="checkbox" id="scales" name="scales">';
echo "</td>";
echo "<td>";
echo $row['VALUE1'];
echo "</td>";
echo "<td>";
echo $row['VALUE2'];
echo "</td>";
echo "<td>";
echo '<div class="button1">
<input id="'.$row['id'].'" type="button" value="BP" name="'.$row['VALUE2'].'" onclick="pushDataToDB()">
</div>';
echo "</td>";
echo "<td>";
echo '<div class="button2">
<form id="frm">
<input id="'.$row['id'].'" type="button" value="Mittagspause" name="'.$row['name'].'" onclick="pushDataToDB()">
</form>
</div>';
echo "</td>";
echo "</tr>";
}
} else {
echo "there are no comments";
}?>
<script type="text/javascript">
function pushDataToDB() {
var name = event.target.name;
var value = event.target.value;
$.ajax({
url: "ajax.php",
type: "POST",
data: {
"name": name,
"value": value
},
success: function(e) {
if (e == "1") {
alert("Success!");
} else {
alert("error!");
}
}
});
}
</script>
ajax.php
<?php
include_once('dbconnectioncredentials.php');
$con = mysqli_connect($servername, $username, $password, $dbname);
$name = $_POST['VALUE1'];
$value = $_POST['VALUE2'];
$query = "INSERT INTO aktuellaufpause (VALUE1, VALUE2) VALUES ('$name','$value')";
$result = mysqli_query($con, $query);
if ($result) {
echo "1";
} else {
echo "Error!";
}
?>
I have a script. It work fine with against & exact match, but when I search with multiple keywords, it returns null and black page against my query.
Here is my code:
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
</head>
<body>
<?Php
ini_set('display_errors', true);//Set this display to display all erros while testing and developing the script
error_reporting(0);// With this no error reporting will be there
include "include/z_db.php";
$todo=$_POST['todo'];
$search_text=$_POST['search_text'];
if(strlen($serch_text) > 0){
if(!ctype_alnum($search_text)){
echo "Data Error";
exit;
}
}
////////// Displaying the search box /////
echo "<table>
<tr><td colspan=2 align='center'>";
echo "<form method=post action=''><input type=hidden name=todo value=search>
<input type=text name=search_text value='$search_text'><input type=submit value=Search><br>
<input type=radio name=type value=any checked>Match any where
<input type=radio name=type value=exact>Exact Match
</form>
";
echo "</td></tr>";
/////////// if form is submitted the data processing is done here///////////////
echo "<tr><td width='600' valign=top>";
if(isset($todo) and $todo=="search"){
$type=$_POST['type'];
$search_text=ltrim($search_text);
$search_text=rtrim($search_text);
if($type<>"any"){
$query="select * from student where name='$search_text'";
}else{
$kt=split(" ",$search_text);//Breaking the string to array of words
// Now let us generate the sql
while(list($key,$val)=each($kt)){
if($val<>" " and strlen($val) > 0){$q .= " name like '%$val%' or ";}
}// end of while
$q=substr($q,0,(strLen($q)-3));
// this will remove the last or from the string.
$query="select * from student where $q ";
} // end of if else based on type value
echo "<span style='background-color= #FFFF00'>$query</span><br>";
$count=$dbo->prepare($query);
$count->execute();
$no=$count->rowCount();
if($no > 0 ){echo " No of records = ".$no."<br><br>";
echo "<table><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Sex</th></tr>";
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td>
<td>$row[mark]</td><td>$row[sex]</td></tr>";
}
echo "</table>";
}else {
echo " No records found ";
}
}// End if form submitted
echo "</td><td width='400' valign=top>";
echo " Full records here ";
$query="select * from student";
echo "<table><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Sex</th></tr>";
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td>
<td>$row[mark]</td><td>$row[sex]</td></tr>";
}
echo "</table>";
echo "</td></tr></table>";
?>
</body>
</html>
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>Demo of Search Keyword using PHP and MySQL</title>
</head>
<body>
<?Php
ini_set('display_errors', true);//Set this display to display all erros while testing and developing the script
error_reporting(0);// With this no error reporting will be there
include "include/z_db.php";
$todo=$_POST['todo'];
$search_text=$_POST['search_text'];
if(strlen($serch_text) > 0){
if(!ctype_alnum($search_text)){
echo "Data Error";
exit;
}
}
////////// Displaying the search box /////
echo "<table>
<tr><td colspan=2 align='center'>";
echo "<form method=post action=''><input type=hidden name=todo value=search>
<input type=text name=search_text value='$search_text'><input type=submit value=Search><br>
<input type=radio name=type value=any checked>Match any where
<input type=radio name=type value=exact>Exact Match
</form>
";
echo "</td></tr>";
/////////// if form is submitted the data processing is done here///////////////
echo "<tr><td width='600' valign=top>";
if(isset($todo) and $todo=="search"){
$type=$_POST['type'];
$search_text=ltrim($search_text);
$search_text=rtrim($search_text);
if($type<>"any"){
$query="select * from student where name='$search_text'";
}else{
$kt=split(" ",$search_text);//Breaking the string to array of words
// Now let us generate the sql
while(list($key,$val)=each($kt)){
if($val<>" " and strlen($val) > 0){$q .= " name like '%$val%' or ";}
}// end of while
$q=substr($q,0,(strLen($q)-3));
// this will remove the last or from the string.
$query="select * from student where $q ";
} // end of if else based on type value
echo "<span style='background-color= #FFFF00'>$query</span><br>";
$count=$dbo->prepare($query);
$count->execute();
$no=$count->rowCount();
if($no > 0 ){echo " No of records = ".$no."<br><br>";
echo "<table><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Sex</th></tr>";
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td>
<td>$row[mark]</td><td>$row[sex]</td></tr>";
}
echo "</table>";
}else {
echo " No records found ";
}
}// End if form submitted
echo "</td><td width='400' valign=top>";
echo " Full records here ";
$query="select * from student";
echo "<table><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Sex</th></tr>";
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td>
<td>$row[mark]</td><td>$row[sex]</td></tr>";
}
echo "</table>";
echo "</td></tr></table>";
?>
</body>
</html>
MySQL Connection:
<?php
global $dbo;
$info['dbhost_name'] = "localhost";
$info['database'] = "search"; // database name
$info['username'] = "root"; // userid
$info['password'] = ""; // password
$dbConnString = "mysql:host=" . $info['dbhost_name'] . "; dbname=" . $info['database'];
$dbo = new PDO($dbConnString, $info['username'], $info['password']);
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
//$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$error = $dbo->errorInfo();
if($error[0] != "") {
echo "string";
}
?>
Result after query submitted:
$q = array(); // create an array
$sq = ""; // this variable will be used in the query
if(isset($_POST['txt_projectname']) && !empty($_POST['txt_projectname'])){
$projectname = mysqli_real_escape_string($conn,$_POST['txt_projectname']);
$q[] = "db_projectname='".$projectname."' ";
} // take the variable from input after submit and put it in the array
if(isset($_POST['txt_location']) && !empty($_POST['txt_location'])){
$location = mysqli_real_escape_string($conn,$_POST['txt_location']);
$q[] = "db_location='".$location."' ";
}
$first = true;
foreach($q as $qu){
if($first){
$sq .= " where ".$qu;
$first = false;
}else{
$sq .= " and ".$qu;
} // for loop to use where and and in the query
}
$sql=mysqli_query($conn,"select * from table {$sq} ")or die(mysqli_error($conn));
You can do something like this
Hello friends this i am facing some problem...I have multiple check boxes and by selecting each check box i am inserting the users details to database by Ajax. the records records are inserting to database but my problem is that , suppose i have 5 users in the page, suppose i am selecting the 3 user check boxes and submit , and if the insertion succeed then i want that the 3 selected users will not shown on page. i use Google many tips but can't solve the problem.
//this is the menu.php
<li class="invitetab"><span>Invite</span></li>
$('.invitetab').one('click', function(){
var rp = '<?php echo $baseUrl ;?>/themes/gr-mist/pagemenu/parts/';
var v = '<?php echo $_GET['pageid'];?>';
var userid = '<?php echo $_SESSION['db_user_info']['id'] ?>';
$( document ).ready(function() {
$.ajax({
url: ""+rp+"invite.php?pageid="+v+"&userid="+userid,
type: 'POST',
beforeSend: function()
{
$("#loading_img").show();
},
success: function(data)
{
$("#loading_img").hide();
$("#Invite").append(data);
}
});
});
});
//And this is the invite.php
$('.gr-post-btn-submit').click(function(){ // when a feature button is selected
var rp = '<?php echo $config->baseUrl ;?>/themes/gr-mist/pagemenu/parts/';
var v = '<?php echo $_GET['pageid'];?>';
var userid = '<?php echo $user_id ?>';
var serialize = $('.abc').serialize(); // takes all the values of the filter
$.ajax({
type : 'POST',
url: ""+rp+"sendinv.php?pageid="+v+"&userid="+userid, // sends the values to ajax file
data : serialize,
beforeSend: function()
{
$("#loading_own").show();
$("#Invite").css({ opacity: 0.5 });
},
success: function(data)
{
$("#loading_own").hide();
$("#Invite").css({ opacity: 5.6 });
// $("#Invite").show();
//this is the portion where we have to do some thing to hide the inserting check boxes
}
});
});
<form method="post" class="abc" id="" name="inviteform"
enctype="multipart/form-data" action="#">
<?php
$sql = "select * from gr_user_friendships where toid=$user_id and status = 1";
$pagd = $_GET['pageid'];
$liked_users = $db->select($sql);
$count = 0;
for($i=0; $i<count($liked_users); $i++)
{
$extrct_fr = "select * from gr_page_likes where page_id=".$pagd." and receiver_id=".$liked_users[$i]['fromid'];
//echo $extrct_fr;
$frnd = $db->select($extrct_fr);
if(count($frnd)>0)
{
$invt = $db->select("select * from gr_user_friendships where toid=$user_id and fromid!=$frnd[0]['receiver_id']");
$invt_id = $invt[0]['fromid'];
}
else
{
$invt_id = $liked_users[$i]['fromid'];
}
if(!empty($invt_id))
$count = 1;
$user = "Select * from gr_users where id = $invt_id";
//echo $user;
$table = mysql_query($user);
$dbc = mysql_fetch_array($table);
$usid= $dbc['id'];
$bab = $dbc['name'];
$imgs = $dbc['avatar'];
$image_of_fr = $_SERVER['DOCUMENT_ROOT']."/uploads/users/".$usid."/profile/profile-pic/thumb/".$imgs;
$image_location_f = $config->baseUrl."/uploads/users/".$usid."/profile/profile-pic/thumb/".$imgs;
if(file_exists($image_of_fr))
{
$imgp = $image_location_f;
}
else
{
$imgp = $config->baseUrl."/themes/gr-mist/includes/images.jpg";
}
if(!empty($invt_id)){
?>
<style type="text/css">
#users_<?php echo $invt_id ?>
{
width:147px;
height:54px;
display:inline-block;
}
</style>
<input type="checkbox" class="checkbox1" id="gcc_<?php echo $invt_id ?>" name="pgliker[]" value="<?php echo $invt_id ?>"/>
<img width="30" height="30" src="<?php echo $imgp;?>"/>
<?php echo $bab; ?>
<?php
}
}//end of for
?>
<br>
<?php if($count){ ?>
<span style="color:blue; font-weight:bold;" >
<input type="checkbox" id="selecctall"/> Select All</span>
<input type="button" name="gr_submits" class="gr-post-btn-submit" value="invite" id="submits"/>
<?php } ?>
</form>
and this is the sendinv.php
global $db;
$myliker = $_POST['pgliker'];
$pageid = $_GET['pageid'];
$userid = $_GET['userid'];
foreach($myliker as $tps)
{
$sql = "Insert into gr_page_likes values('',$pageid,$userid,$tps,0)";
$db->insert($sql);
}
/**In you invite.php put the element which you want to hide after success
form submission into one div*//
//replace your one with this one.
<div id="gcc_<?php echo $invt_id ?>">
<input type="checkbox" class="checkbox1" name="pgliker[]" value="<?php echo $invt_id ?>"/>
<img width="30" height="30" src="<?php echo $imgp;?>"/>
<?php echo $bab; ?>
</div>
/**Now make an array in your sendinv.php and encode it with json incode***/
//replace your sendinv.php with this one.
$arr = array();
foreach($myliker as $tps)
{
$sql = "Insert into gr_page_likes values('',$pageid,$userid,$tps,0)";
$db->insert($sql);
$arr[] = $tps;
}
echo json_encode($arr);
exit;
/**After in your invite.php in the success block run
jquery foreach with the data and hide the checked boxes with the ids associted after submission. */
$.each( data, function( key, value ) {
// alert( key + ": " + value );
$("#gcc_"+value).hide();//the div for each checked user
});
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
}
});
});
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);