Search engine - how to handle empty queries - javascript

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
}
});
});

Related

Submit and POST "True" or "False" to a series of text questions presented one by one taken from a php array

new to forum, AJAX and JQuery. A little experience of PHP and JS.
I'm trying to present a long series of questions (400+) one by one in an input text field on a form with 2 submit buttons labelled "True" and "False". I need one question to be presented at a time, then record the True or False result as (1 or -1) sequentially into another text file. I cannot refresh the input field with the next question after 'Submit'. I believe that AJAX would be the answer.
This code is the first effort: (any later efforts are more complicated, but don't work any better) it opens the questions file (CPXQ.dat) into an indexed array, then places the first question into the input text field. When either of the submit buttons are pressed, the result is POSTed to data.cpx, and the next question appears, but it won't continue thereafter. I have tried various PHP loops and some javascript, but these don't work, either looping through immediately to the last question, or getting stuck in the loop. (The php includes just contain CSS and JQuery source.)
I'd also like to prevent the user from being able to go back over any of the questions, but that may be a query for another day!
Any advice much appreciated, and apologies if not clear. Happy to provide any further info.
<div class="container">
<?php include("top.php"); ?>
<div class="intro">
<p><h1>CPI TEST</h1></p>
<?php
$i = 0;
//file in to an array
$lines = file("CPXQ.dat");
?>
<?php
if(isset($_POST['submitT'])) {
//echo $_POST['submitT'];
$data="1";
//echo $data;
$fp = fopen('data.cpx', 'a') or die("Unable to open file!");
fwrite($fp, PHP_EOL);
fwrite($fp, $data);
fclose($fp);
++$i;
}
if(isset($_POST['submitF'])) {
//echo $_POST['submitF'];
$data="-1";
//echo $data;
$fp = fopen('data.cpx', 'a') or die("Unable to open file!");
fwrite($fp, PHP_EOL);
fwrite($fp, $data);
fclose($fp);
++$i;
}
?>
<form method = "post" action = "CPI_Test.php">
<input type="text" name="question" value="<?php echo $lines[$i];?>">
<input type="submit" name="submitT" value="True">
<input type="submit" name="submitF" value="False">
</form>
</div>
</body>
Here's the code for the preliminary page collecting user details:
<!DOCTYPE html>
<html>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PPCS CPI Information</title>
<?php include("head.php"); ?>
</head>
<body>
<?php
// define variables and set to empty values
$initdataErr = $surnamedataErr = $agedataErr = $gendataErr = "";
$initdata = $surnamedata = $agedata = $gendata = $codata = "";
function test_input(&$surnamedata) {
$surnamedata = trim($surnamedata);
$surnamedata = stripslashes($surnamedata);
//$data = htmlspecialchars($data);
$surnamedata = preg_replace('/\s+/', '', $surnamedata);
return $surnamedata;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['initdata'])) {
$initdataErr = "Initials are required";
} else {
$initdata = test_input($_POST['initdata']);
// check if name only contains letters and whitespace
if (!preg_match("/^[A-Z- ]*$/",$initdata)) {
$initdataErr = "Please use capital letters without spaces only";
}
}
if (empty($_POST['surnamedata'])) {
$surnamedataErr = "Surname is required";
} else {
$surnamedata = test_input($_POST['surnamedata']);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$surnamedata)) {
$surnamedataErr = "Please use letters only";
}
}
if (empty($_POST['agedata'])) {
$agedataErr = "Age is required";
} else {
$agedata = test_input($_POST['agedata']);
// check if name only contains letters and whitespace
if (!preg_match("/^[0-9]*$/",$agedata)) {
$agedataErr = "Only numbers and white space allowed";
}
}
if (empty($_POST['gendata'])) {
$gendataErr = "Gender is required";
}
}
?>
<div class="container">
<?php include("top.php"); ?>
<br><h1>CPI TEST INFORMATION</h1><br>
<b>Please fill in the form below carefully</b>
<p><span class="error">* required field</span></p>
<br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Initials: <span class="error">* <?php echo $initdataErr;?></span> <br>
<input type="text" name="initdata" value="<?php echo $initdata;?>"><br>
<br>
Surname: <span class="error">* <?php echo $surnamedataErr;?></span> <br>
<input type="text" name="surnamedata" value="<?php echo $surnamedata;?>" ><br>
<br>
Company (Optional):<br>
<input type="text" name="codata" value="<?php echo isset($_POST["codata"]) ? $_POST["codata"] : '';?>" ><br>
<br>
Age in Years: <span class="error">* <?php echo $agedataErr;?></span><br>
<input type="text" name="agedata" maxlength="2" min="0" max="99" step="1" pattern="[0-9]{2}"value="<?php echo $agedata;?>"><br>
<br>
Gender: <span class="error">* <?php echo $gendataErr;?></span><br>
<select name="gendata">
<option value="">Select...</option>
<option value="m" <?php echo (isset($_POST['gendata']) && $_POST['gendata'] == 'm') ? 'selected' : ''; ?>>Male</option>
<option value="f" <?php echo (isset($_POST['gendata']) && $_POST['gendata'] == 'f') ? 'selected' : ''; ?>>Female</option>
</select>
<br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
</body>
</html>
<?php
if(isset($_POST['submit'])){
// Fetching variables of the form which travels in URL
$initdata = $_POST['initdata'];
$surnamedata = $_POST['surnamedata'];
$codata = $_POST['codata'];
$agedata = $_POST['agedata'];
$gendata = $_POST['gendata'];
if($initdata !=''&&(preg_match("/^[A-Z]*$/",$initdata))
&& $surnamedata !='' && (preg_match("/^([A-Za-z \-]+(?:\'|&#0*39;)*)*[A-Za-z \-]+$/",$surnamedata)) && $agedata !='' && (preg_match("/^[0-9]*$/",$agedata)) && $gendata !='')
{
date_default_timezone_set("Europe/London");
//^['\a-zA-Z]*$/ This is the most recent
test_input($surnamedata);
$_POST['surnamedata'] = ucwords($_POST['surnamedata']);
$data = '"' . $_POST['initdata'] . ' ' . stripslashes($_POST['surnamedata']) . '","' . $_POST['agedata'] . '","'. $_POST['gendata'] .'","' . $_POST['codata'] . '","' . '","'. '","'. date("d/m/Y"). '","'. date("H:i:s"). '","';
//Create CPX filename
$fn = $_POST['initdata'] . $_POST['surnamedata'];
$fn = preg_replace('/\PL/u', '', $fn);
$fn = strtoupper($fn);
$fn = $fn . "XXXXXX";
$fn = substr($fn,0,8);
echo "$fn";
echo "$data";
//Create temp file for CPX filename
$fp = fopen($fn . '.temp', 'a') or die("Unable to open file!");
fwrite($fp, $fn);
fclose($fp);
//Create CPX file
$fp = fopen($fn . '.cpx', 'a') or die("Unable to open file!");
fwrite($fp, $data);
//Append new line
//fwrite($fp, "\ntest");
fclose($fp);
// Redirect
/header("Location:/CPI_Form_Trial/instructions.php");
}
else{
?>
<br><span class = "error"><?php echo "Please make sure that you have filled in all required fields and click 'Submit' again";?></span> <?php
}
}
?>
Using AJAX (fetch) is ideally suited to this type of problem where you do not wish to refresh the screen and want to present new data after submitting a http request. The following single page application shows how you might accomplish your stated goal but it does not take into account a couple of possible issues which are:
[a] multiple users participating in the questionnaire simultaneously
[b] a user abandoning the questionnaire and restarting, once or more than once.
The issues mentioned could be negated by using a database to store answers and assigning the users unique identifiers (ie: user id, username) which is used when sending the ajax request.
The demo that follows will write, to the answerfile, either 1 or 0 ( which is more common than -1 for false ) alongside the question line number ( which is sort of the ID )
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'] ) ){
ob_clean();
$file='CPXQ.dat';
$answerfile='data.cpx';
$lines=file( $file );
switch( $_POST['action'] ){
case 'start':
header('Content-Type: text/html');
exit( $lines[0] );
break;
case 'question':
$id=(int)$_POST['id'];
# increment ID value
$id++;
$question=isset( $lines[ $id ] ) ? $lines[ $id ] : false;
if( $question && $id < count( $lines ) ){
# log the current answer
file_put_contents( $answerfile, sprintf( 'q:%s,a:%s', $id, $_POST['answer'] ) . PHP_EOL, FILE_APPEND );
# the json payload
$data=array(
'id' => $id,
'question' => $question
);
} elseif( !$question && $id==count( $lines ) ){
# log the final answer
file_put_contents( $answerfile, sprintf( 'q:%s,a:%s', $id, $_POST['answer'] ) . PHP_EOL, FILE_APPEND );
$data=array(
'id' => 0,
'question' => 'End of questionnaire'
);
}
header('Content-Type: application/json');
exit( json_encode( $data ) );
break;
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Questions, questions, questions...</title>
</head>
<body>
<!--
a basic form: The question is rendered within the `fieldset`
element. Both buttons use datasets, the data-id refers to the
question number (line from source file) and data-value is the
boolean value indicating answer value.
-->
<form name='questions' method='post'>
<fieldset></fieldset>
<div>
<input type='button' data-value=1 data-id=0 value='True' />
<input type='button' data-value=0 data-id=0 value='False' />
</div>
</form>
<script>
const fs=document.querySelector('fieldset');
/*
When the page loads we fetch the first question ( ie: first line in source file )
and display on the page. The action parameter helps the backend determine what stage
we are at.
*/
let fd=new FormData();
fd.set('action', 'start');
// make the request an show question
fetch( location.href, { method:'post', body:fd })
.then(r=>r.text())
.then(text=>{
fs.innerHTML=text;
});
/*
The delegated event handler processes button clicks and sends the
data-id ( ie: line number ) and answer to the backend processing script.
Here this is all done on the same page for convenience - for your case
it would be CPI_Test.php
*/
const clickhandler=function(e){
if( e.target.tagName.toLowerCase()=='input' && e.target.type=='button' ){
// set a different `action` so that the backend knows what to do
fd.set('action','question');
fd.set('id',e.target.dataset.id);
fd.set('answer',e.target.dataset.value);
// send the request and display new question
fetch( location.href, { method:'post', body:fd } )
.then( r=>r.json() )
.then( json=>{
fs.innerHTML=json.question;
// update the buttons so that they have the new id assigned ready for next click
// or disable ( or remove ) when the questionnaire is over.
document.querySelectorAll('[type="button"][data-value]').forEach( bttn=>{
if( Number( json.id ) !==0 ) bttn.dataset.id=json.id;
else bttn.disabled=true;
});
})
}
};
// add a delegated event handler to process button clicks
document.forms.questions.addEventListener( 'click', clickhandler );
</script>
</body>
</html>
A sample of the answerfile:
q:1, a:1
q:2, a:0
q:3, a:1
q:4, a:1
q:5, a:0
q:6, a:0
q:7, a:1
q:8, a:0
q:9, a:1
q:10, a:0
q:11, a:1
q:12, a:1
q:13, a:1
q:14, a:1
q:15, a:0
q:16, a:1
q:17, a:0
q:18, a:1
q:19, a:1
q:20, a:0
I hope it helps you arrive at a solution but as mentioned it would be more robust / reliable with a database rather than simple text file.

How to search keywords in PHP?

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

Filtering PHP with checkboxes

I am working on this script that will filter sql results based on the which checkboxes are checked. My table is set up like so..
id venue imageurl showingads 2kandunder 2kto4k 4kandup
1 venue1 myurl.com yes yes
2 venue2 myurl.com yes yes
3 venue3 myurl.com no yes
4 venue4 myurl.com yes yes
All code is on the same page. Here is the html..
<form id="form" method="post" action="">
<input type="checkbox" name="2kandunder" class="checkbox" <?=(isset($_POST['2kandunder'])?' checked':'')?>/> 2kandunder<br>
<input type="checkbox" name="2kto4k" class="checkbox" <?=(isset($_POST['2kto4k'])?' checked':'')?>/> 2k to 4k<br>
<input type="checkbox" name="4kandup" class="checkbox" <?=(isset($_POST['4kandup'])?' checked':'')?>/> 4k and up<br>
</form>
Javascript code...
<script type="text/javascript">
$(function(){
$('.checkbox').on('change',function(){
$('#form').submit();
});
});
</script>
and php...
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST["2kandunder"])) {
$arguments[] = "`2kandunder` = 'yes'";
}
if (isset($_POST["2kto4k"])) {
$arguments[] = "`2kto4k` LIKE 'yes'";
}
if (isset($_POST["4kandup"])) {
$arguments[] = "4kandup LIKE '%yes%'";
}
if(!empty($arguments)) {
$str = implode(' or ',$arguments);
$qry = "SELECT id, venue, imageurl FROM ads where " . $str . "";
$paginate = new pagination($page, $qry, $options);
} else {
//Whatever happens when there's none checked.
$sql = "SELECT id, venue, imageurl FROM ads WHERE `showingads` = 'yes'";
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<table class='tablebox' width='940' border='1' cellspacing='5'>
<tr><td width='75'>".$row["venue"]."</td></tr>
<tr>
<td width='10'><a href='post_click.php?id=".$row["id"]."'> <img src='".$row["imageurl"]."'></a></td>
</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
When I run this page else query displays which is what I want to happen when page first loads. But when I check any of the checkboxes nothing happens. Here is entire code as it is on page.
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="JavaScript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
</head>
<html>
<body>
<form id="form" method="post" action="">
<input type="checkbox" name="2kandunder" class="checkbox" <?=(isset($_POST['2kandunder'])?' checked':'')?>/> 2k and under<br>
<input type="checkbox" name="2kto4k" class="checkbox" <?=(isset($_POST['2kto4k'])?' checked':'')?>/> 2k to 4k<br>
<input type="checkbox" name="4kandup" class="checkbox" <?=(isset($_POST['4kandup'])?' checked':'')?>/> 4k and up<br>
</form>
<script type="text/javascript">
$(function(){
$('.checkbox').on('change',function(){
$('#form').submit();
});
});
</script>
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST["2kandunder"])) {
$arguments[] = "`2kandunder` = 'yes'";
}
if (isset($_POST["2kto4k"])) {
$arguments[] = "`2kto4k` LIKE 'yes'";
}
if (isset($_POST["4kandup"])) {
$arguments[] = "4kandup LIKE '%yes%'";
}
if(!empty($arguments)) {
$str = implode(' or ',$arguments);
$qry = "SELECT id, venue, imageurl FROM ads where " . $str . "";
$paginate = new pagination($page, $qry, $options);
} else {
//Whatever happens when there's none checked.
$sql = "SELECT id, venue, imageurl FROM ads WHERE `showingads` = 'yes'";
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<table class='tablebox' width='940' border='1' cellspacing='5'>
<tr><td width='75'>".$row["venue"]."</td></tr>
<tr>
<td width='10'><a href='post_click.php?id=".$row["id"]."'> <img src='".$row["imageurl"]."'></a></td>
</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
My first thoughts is 1. The javascript isn't executing at all? 2. My $arguments is formatted wrong for how I have the database set up? (I have 3 different variations for the arguments to try and test out different formats to see if I could get one to work)
Note: The php portion from tutorial I learned from had the argument like if (isset($_POST["2kandunder"]). I have it like this: if (isset($_POST["2kandunder"])) with the extra parenthesis at the end because I was getting a syntax error for each if statement. If that could be the problem why was I getting syntax errors for each if statement line?
All this code and blabbering but I feel like I am close. Can someone PLEASE help me figure out what the problem is?
EDIT
columns are set up like this..
Field Type Null Key Default Extra
id int(5) NO PRI NULL auto_increment
venue varchar(100) NO NULL
imageurl varchar(150) NO NULL
showingads varchar(5) NO NULL
2kandunder varchar(5) NO NULL
2kto4k varchar(5) NO NULL
4kandup varchar(5) NO NULL
UPDATE
So I have the checkboxes working now but now when I load the page and click the top checkbox (2kandunder) it returns 0 results. The else sql still works for when no checkboxes are checked. I changed the first if statement to
if (isset($_POST["2kandunder"])) {
$arguments[] = "`showingads` = 'yes'";
which should make it the same query as the else sql query when the first (2kandunder) box is checked. Still 0 results shows. So I echoed the $qry to display what query was being run when the first checkbox is checked and it is the exact same as the else $sql query but still returns 0 results? How is this possible if that exact same query works for the else query?
Last Update
The problem was the if $results it was only showing results for the sql query thanks for anyone that helped!
http://api.jquery.com/on/
You are right. javascript isn't executed at all. You are using jquery 1.4.1. But "on" is available since 1.7
I hope this will help you.

Database table values not updating through AJAX & Jquery

My test.php page is as under:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h3>Setting</h3>
<form>
<p>Name:<input type="text" id="updatetherone1"/></p>
<p>Email:<input type="text" id="updateotherone2"/></p>
<p><input id="updateone" type="button" value="Save"/></p>
</form>
<span id="updateotherotherone"></span>
<script src="js/jquery.js"></script>
<script src="js/ajax.js"></script>
</body>
</html>
My ini.php page is as under:
<?php
session_start();
$_SESSION['state'] ='2';
$conn=new mysqli('localhost','root','','people');
?>
My test1.php page is as under:
<?php
include 'ini.php';
if (isset($_POST['name'], $POST['email'])){
$name = mysqli_real_escape_string(htmlentities($POST['name']));
$email = mysqli_real_escape_string(htmlentities($POST['email']));
$update = mysqli_query("UPDATE state SET Name='$name', email='$email' WHERE Id=".$_SESSION['state']);
if($update === true){
echo 'Setting have been updated.';
}else if ($update === false){
echo 'There was an error updating your setting.';
}
}
?>
My ajax.js page is as under:
$('[id=updateone]').click(function(){
var name=$('[id=updateotherone1]').val();
var email=$('[id=updateotherone2]').val();
$('[id=updateotherotherone]').text('Loading...');
$.post('test1.php',{name:name,email:email},function(data){
$('[id=updateotherotherone]').text(data);
});
});
Ultimately code is not working nor do it is displaying any error, I suspect there is something wrong with test1.php page, can anybody guide please:
Take note that the procedural interface of mysqli_query(), the first parameter need the connection.
$update = mysqli_query($conn, "UPDATE state SET Name='$name', email='$email' WHERE Id=".$_SESSION['state']);
If these are typos $POST, then it should be fixed in your code. It's supposed to read as $_POST. (unless its a typo on the question.) It is a superglobal.
I suggest you just use the object oriented interface. So that you wouldn't need to add it everytime:
<?php
include 'ini.php';
if (isset($_POST['name'], $_POST['email'])){
$name = $conn->real_escape_string(htmlentities($_POST['name']));
$email = $conn->real_escape_string(htmlentities($_POST['email']));
$update = $conn->query("UPDATE state SET Name='$name', email='$email' WHERE Id = " . $_SESSION['state']);
if($conn->affected_rows > 0) {
echo 'Setting have been updated.';
} else {
echo 'There was an error updating your setting.';
}
}
?>
Might as well use prepared statements since mysqli supports it:
if (isset($_POST['name'], $_POST['email'])){
$name = htmlentities($_POST['name']);
$email = htmlentities($_POST['email']);
$sql = 'UPDATE state SET Name = ?, email = ? WHERE Id = ?';
$update = $conn->prepare($sql);
$update->bind_param('ssi', $name, $email, $_SESSION['state']);
$update->execute();
if($update->affected_rows > 0) {
echo 'Setting have been updated.';
} else {
echo 'There was an error updating your setting.';
}
}
On the JS part:
You also have a typo on the form id and the JS:
<p>Name:<input type="text" id="updatetherone1"/></p> <!-- missing o -->
var name=$('[id=updateotherone1]').val();
Should be: <p>Name:<input type="text" id="updatetherone1"/></p>
Sidenote:
If you want to avoid those kind of silly typos, just id and label them properly. Example:
<p>Name:<input type="text" id="name_field"/></p>
<p>Email:<input type="text" id="email_field"/></p>

unable to compare data from database to array of strings

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);

Categories