I made a search bar, for searching users in my database, and I will share my code below. But one problem is that, if I have 5 users in a table, it shows these 5 users, but if I have 1,000 than it shows all 1,000.
Whatever I tried to limit it, it did not work. Sometimes it completely kills the PHP script.
Does anyone know how to solve that and limit to only 5 results displayed per search query from the code below?
HTML INPUT AND AJAX SCRIPT:
<input id="text" type="text" name="text" onkeyup="showHint(this.value)" autocomplete="off" />
<div id="inner" class="inner"></div>
<script>
function showHint(str) {
if (str.length==0) {
document.getElementById("inner").innerHTML="You haven't search. Please have :D";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("inner").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("REQUEST","searchquery.php?text="+str,true);
xmlhttp.send();
}
</script>
AND searchquery.php:
<?
$text = $_REQUEST['text'];
$text = preg_replace('#[^a-z0-9]#i', '', $text);
function connect($database) {
mysql_connect('localhost','root','');
mysql_select_db($database);
}
connect('developing');
$query = "SELECT * FROM users WHERE first_name LIKE '%$text%' OR last_name LIKE '%$text%'";
$action = mysql_query($query);
$result = mysql_num_rows($action);
if ($result == 0) {
$output = "User does not exist...";
}else{
while ($row = mysql_fetch_array($action)) {
$output .= '<div class="output"><img src="/'.$row['avatar'].'"><a href="#">'.$row['first_name'].' '.$row['last_name'].'</div><br />';
}
}
echo $output;
?>
Can anybody see some solution on how to make that limit?
Use LIMIT in your query:
SELECT *
FROM users
WHERE first_name LIKE '%$text%'
OR last_name LIKE '%$text%
LIMIT 5'
Related
I am creating a simple order taking page. What I want is when I will start typing on the select customer input box , filtered based on my key stroke result will be shown below the input box.
As I am new in this field your advise / suggestion will be highly appreciated.
here is my javascript code :
function showCustomer(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","searchcustomer.php?q="+str,true);
xmlhttp.send();
}
}
Here is my searchcustomr PHP code
$q=$_GET["q"];
define('HOSTNAME', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DBNAME', 'order');
$conn = new mysqli(HOSTNAME, USERNAME, PASSWORD, DBNAME);
$sql = "SELECT cusname, cusarea, cusadd1,cusadd2,cusadd3,cuscity,cuspin,cusoldbal FROM tbl_customer where cusname like '%".$q."%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$data = $row['cusname'];
}
echo $data;
}
else
{
echo 'No Mach Found...';
}
$conn->close();
here is my HTML input file:
<h4>Order To</h4>
<div class="form-group">
<input type="text" class="form-control autocomplete_com" data-type="clientCompanyName" name="clientCompanyName" id="clientCompanyName" placeholder="Select Company" onkeyup="showCustomer(this.value)">
</div>
<div id="txtHint"></div>
This div txtHint just not working, I just want the result below my input box and able to select too.....What will be the best way to achieve that?
I have a problem with my code.
case like this:
I have a dropdown, if selected "personal" it appeared the new dropdown that contains the data that is retrieved from a database query, if selected "public", then the dropdown disappear.
HTML code like this:
<select name="use" class="dropdown" id="sender" onChange='changeSend()'>
<option value=1>Public</option>
<option value=0>Personal</option>
</select>
<div id='send2'></div>
Query like this:
<?php
$query = mysql_query("select * from data where id_user = '$id_user' order by date asc");
$i = 0;
$id = array();
$name = array();
while($data = mysql_fetch_array($query)){
//id from result database query
$id[$i] = $data['id'];
//name from result database query
$name[$i] = $data['name'];
$i++;
}
?>
JavaScript code like this:
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
$('#send2').html("<select class='dropdown'><option value='-id from result database-'>-name from result database query-</option></select>");
} else {
$('#send2').html('');
}
}
I dont know how to send value/result ($id[0],$name[0],$id[1],$name[1], etc..) to javascript code(value and name in select options).
In javascript you have to make an ajax call to your php file:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("send2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","yourFile.php",true);
xmlhttp.send();
And in your php file you have to echo your data in JSON format:
echo json_encode(array('id'=>$id,'name'=>$name));
UPDATE
in your case use the following code:
(not tested)
php code:
<?php
$query = mysql_query("select * from data where id_user = '$id_user' order by date asc");
$i = 0;
$options = array();
while($data = mysql_fetch_array($query)){
$options[$data['id']] = $data['name'];
}
echo json_encode($options);
?>
javascript code:
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var response = JSON.parse(xmlhttp.responseText);
var select = '<select class='dropdown'>';
for( var index in response ){
select = select + "<option value='"+ index +"'>"+response[index]+"</option>";
}
select += "</select>";
document.getElementById("send2").innerHTML= select;
}
}
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
xmlhttp.open("GET","yourFile.php",true);
xmlhttp.send();
}
else {
$('#send2').html('');
}
}
USING jQuery
javascript code:
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
$.get("yourFile.php", function(data){
var response = JSON.parse(data);
var select = '<select class='dropdown'>';
for( var index in response ){
select = select + "<option value='"+ index +"'>"+response[index]+"</option>";
}
select += "</select>";
$("#send2").html(select);
});
}
else {
$('#send2').html('');
}
}
The best way would probably be with an ajax call, anyway if you are declaring the script in the same page with the php, you can json encode the array with the options so that you will be able to access it into the javascript, like this:
var optionIds = <php echo json_encode($id); ?>
var optionNames = <php echo json_encode($name); ?>
i have this code below of javascript:
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","includes/get_user.php?q="+str,true);
xmlhttp.send();
}
</script>
and the php sql script is given below:
<?php
$testQrys = "SELECT * FROM test where status = 1";
$testdbResults = mysql_query($testQrys);
?>
<select size='5' width='925' style='width: 925px' name='users' onchange='showUser(this.value)' multiple>
<?php while($test = mysql_fetch_array($testdbResults )) { ?>
<option class='h4' value='<?php print($test[9]); ?>'>
<?php print($test[5]);echo" ( ";print($test[9]);echo" )"; ?>
</option>
<?php } ?>
</select>
<div id="txtHint"></div>
and the get_user.php code is:
<?php
$q=$_GET["q"];
$con = mysqli_connect('localhost','root','','airways');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM test WHERE m_email = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo "<input type='text' name='staff_no[]' value='".$row['m_staff_no']."'>";
}
mysqli_close($con);
?>
now what i want is when i select one user in the select option it shows the staff no of that user but when i select multiple users it does not show the staff no of other users i select.
please help me with the change in code so i can get the staff no of users like (22344, 44333, 33344, 55443, 11125, 25263) in the text box
waiting for the kind and prompt responses.
Thanks in advance
The error is coming from showUser(this.value). This returns only the first selected element's value. You need to cycle through all options and concatenate them together to make a string that you will be able to send as a parameter.
Change your javascript code to something along those lines. Note that you will need to change your PHP code in order to separate the emails, sanitize them and create a working WHERE m_email IN () query.
You will need to add id="users" to your HTML code first.
var usersList = document.getElementById('users');
var emailString = '';
for (user_counter = 0; user_counter < usersList.options.length; user_counter++) {
if (usersList.options[user_counter].selected) {
emailString += usersList.options[user_counter].value;
}
}
Then send emailString as the parameter to the PHP script. Test it again with log.txt in case you get an error.
I have a simple (or so I thought) PHP, MYSQL, AXAX system set up to register votes for items on my website. I'm only doing upVotes so there's only one button.
My issue is that when the page loads, the correct number of votes for the item is displayed, but upon the first click of the upVote button, the value does not change. I know I must be missing something, but I have no idea what. It's probably simple... but I just can't figure it out.
Everything connects to the DB just fine. That's why I left all that code out.
Any help is greatly appreciated.
This is the javascript I have:
<script type="text/javascript">
function voteButton(str)
{
if (str=="")
{
document.getElementById("voteUp").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("voteUp").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","vote?id="+str,true);
xmlhttp.send();
}
</script>
This is the php file used to query the database:
<?php
$id=$_GET["id"];
include("myDatabaseStuff.php");
include("global.php");
$result = mysql_query("UPDATE TABLE SET up_mod = up_mod + 1 WHERE img_id = $id");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while($row = mysql_fetch_array($getUpVoteResult))
{
echo $row['up_mod'];
}
?>
This is the HTML I use on the page to display the values/button:
<div class="span1" style="margin:30px 0 0 10px;">
<button onclick="voteButton('<?php echo $id;?>')" class="btn btn-large" type="button" style="margin-top:5px"><div id="voteUp"><?php echo $votes[0] ?></div><i class="icon-thumbs-up"></i></button>
</div>
Add:
$getUpVoteResult = mysql_query("SELECT up_mod FROM table WHERE img_id = $id") or die ("Invalid query: " . mysql_error());
before the while loop.
You also don't need a while loop, since there's just one row.
After your update, please do the separate SELECT.
I have this code:
$result = mysql_query("SELECT * FROM quote ORDER BY RAND() LIMIT 1") or die(mysql_error());
$row = mysql_fetch_array( $result );
echo $row['frase'];
It echo´s a random "frase" every time you query.
What I want to do is avoid having the same result in consecutive queries.
To make myself clear, if in my database I´ve got:
1 a
2 b
3 c
If from echo $row['frase']; I got a the the next result can´t be a.
I hope I made myself clear and if not please comment and I´ll expand!
Thanks in advance!
BTW: sorry to #deceze #zerkms #Dr.Molle because last question was a total mess! No harm ment, just a noob on a spree :)
EDIT:
To answer Jason McCreary I actually call it like this:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
Since this last query needs to persist across page refreshes, you need to use a session. Something along these lines:
session_start();
if (empty($_SESSION['lastresult'])) {
$_SESSION['lastresult'] = null;
}
$query = "SELECT * FROM `quote` WHERE `id` != '%s' ORDER BY RAND() LIMIT 1";
$query = sprintf($query, mysql_real_escape_string($_SESSION['lastresult']));
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$_SESSION['lastresult'] = $row['id'];
echo $row['frase'];
You may want to store the last x results in the session and use NOT IN () in your query to avoid every second (third, forth, ...) quote being the same.