I found one of basic php live search using ajax from youtube.com please see the sample at
http://www.youtube.com/watch?v=3fS4Ys_ZEKw that video speaking different language but i manager to type all of codes exactly of what you see from youtube.com , but different is the database name and table name, however, when I run is not showing anything to bring from mysql database even if pressed any key still not showing anything and not even errors. Can you see if i missed anything on this code compare to what you see from youtube!
search.php
<body>
<form name"form1" action="" method="post">
Enter name<input type="text" name="t1" onKeyUp="aa();"/><br />
<div id="dl"></div>
</form>
<script type="text/javascript">
function aa()
{
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","sea.php?nm="+document.forml.t1.value,false);
xmlhttp.send(null);
document.getElementById("dl").innerHTML=xmlhttp.responseText;
}
</script>
</body>
</html>
sea.php
<?php
$nm=$_GET("nm");
$mysqli = new mysqli("localhost", "root", "password", "table");
// Check connection
if (mysqli_connect_errno($mysqli))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($result = $mysqli->query("select * FROM product WHERE product_name like('$nm%')"))
echo"<table>";
{
echo "<tr>";
echo "<td>";?><img src="../<?php echo $row["screenshot"];?>" height="100" width="100" <?php echo "</td>" ;
echo "<td>"; echo $row["product_name"]; echo "</td>";
echo "<tr>";
}
echo "</table>";
?>
you need to get the response on onreadystatechange, do:
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) { //4:: request finished and response is ready
document.getElementById("dl").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","sea.php?nm="+document.forml.t1.value);
xmlhttp.send(null);
Related
***UPDATE
I've done away with table elements as suggested and am using CSS. I've also seen that there's a "form" attribute, I've tried that, too. When I submit, it is still acting as it did before - sending the wrong value because it was sending the whole table. I've updated the below with the updated HTML output and the PHP code. It looks correct, this is my latest attempt. What am I missing?
I am using PHP to create a form for each row of data. I call to PHP via AJAX. The form builds correctly. Each row correctly lists its values and is in its own form. In this example, there are three rows, thus three forms. When I submit a username on the first row, the ID being sent is from the third row. Not sure what is going on.
AJAX call to PHP FORM - Home Page
<script>
window.onload = function signupForm() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("signupForm").innerHTML = this.responseText;
}
}
xmlHttp.open("GET", "ajaxInput.php", true);
xmlHttp.send();
}
</script>
PHP FORM - signupForm.php
<?php
$con=mysqli_connect("localhost","xxxxxx","xxxxxxx","xxxxxxxx");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT id, DATE_FORMAT(startTime, '%b-%d-%Y') as eventDate, endTime FROM events
WHERE now() < endTime");
echo "
<style>
.table { display: table; }
.table>* { display: table-row; }
.table>*>* { display: table-cell; padding: 5px; border-style: inset;}
</style>
<div class='table'>
<div>
<div><b>Event Id</b></div>
<div><b>Date</b></div>
<div><b>#username</b></div>
<div><b>Sign Up!</b></div>
</div>";
while($row = mysqli_fetch_array($result))
{
//echo "<form action='ajaxSignup.php' method='post'>";
echo "<div>";
echo "<div>" . $row['id'] . "</div>";
echo "<div>" . $row['eventDate'] . "</div>";
echo "<div><form id='form" .$row['id']. "' method='post'><input class='formSignup' type='text' name='pi_username' id='pi_username' maxlength='20' placeholder='#username' form='form" .$row['id']. "'></div>";
echo "<div><input class='formSignup' type='hidden' name='event_id' id='event_id' value='" . $row['id'] . "' form='form" .$row['id']. "'>
<input name='submit". $row['id'] . "' type='submit' value='Sign up!' onclick='signup(); return false;'></form></div>";
echo "</div>";
}
//echo "</div>";
echo "</div>";
mysqli_close($con);
?>
The table draws correctly. I've put form tag in various places as well. Below, I'm using the form attribute in the input tags. The table is being drawn with CSS instead of the table elements.
<html>
<head></head>
<body>
<p>Something here</p>
<div id="signupForm">
<style>
.table { display: table; }
.table>* { display: table-row; }
.table>*>* { display: table-cell; padding: 5px; border-style: inset;}
</style>
<div class="table">
<div>
<div><b>Event Id</b></div>
<div><b>Date</b></div>
<div><b>#username</b></div>
<div><b>Sign Up!</b></div>
</div>
<div>
<div>11</div>
<div>Feb-25-2021</div>
<div><input class="formSignup" type="text" name="pi_username" id="pi_username" maxlength="20" placeholder="#username" form="form11"></div>
<div>
<input class="formSignup" type="hidden" name="event_id" id="event_id" value="11" form="form11">
<form id="form11" method="post"><input name="submit11" type="submit" value="Sign up!" onclick="signup(); return false;"></form>
</div>
</div>
<div>
<div>12</div>
<div>Feb-26-2021</div>
<div><input class="formSignup" type="text" name="pi_username" id="pi_username" maxlength="20" placeholder="#username" form="form12"></div>
<div>
<input class="formSignup" type="hidden" name="event_id" id="event_id" value="12" form="form12">
<form id="form12" method="post"><input name="submit12" type="submit" value="Sign up!" onclick="signup(); return false;"></form>
</div>
</div>
<div>
<div>13</div>
<div>Feb-27-2021</div>
<div><input class="formSignup" type="text" name="pi_username" id="pi_username" maxlength="20" placeholder="#username" form="form13"></div>
<div>
<input class="formSignup" type="hidden" name="event_id" id="event_id" value="13" form="form13">
<form id="form13" method="post"><input name="submit13" type="submit" value="Sign up!" onclick="signup(); return false;"></form>
</div>
</div>
</div>
</div>
As can be seen in the PHP, each row is its own form. But looking at the Elements in developer tools, the form is closing early. I think this is related to the issue.
Elements
When I enter a username on row one (top row), the username doesn't seem to make it and the ID that does make it is 13 instead of 11.
AJAX Script to process Submit button onclick (Home page)...
<script>
function signup() {
var elements = document.getElementsByClassName("formSignup");
var formData = new FormData();
for(var i=0; i<elements.length; i++) {
formData.append(elements[i].name, elements[i].value);
}
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("signupSuccess").innerHTML = this.responseText;
}
}
xmlHttp.open("post", "ajaxSignup.php");
xmlHttp.send(formData);
}
</script>
PHP code on signup page. I have some echos early on that show the id is 13, not 11 and no username is present.
<?php
$pi_username = $high_score = $attempts = $event_id = "";
echo $event_id;
echo $pi_username;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$pi_username = test_input($_POST["pi_username"]);
$event_id = test_input($_POST["event_id"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
echo $event_id;
echo $pi_username;
if($_SERVER["REQUEST_METHOD"] == "POST") {
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "xxxxxxx", "xxxxxxx", "xxxxxx");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
//check if user has already signed up for event
$alreadySignedUp = mysqli_query($link, "SELECT count(*) AS total FROM signup WHERE event_id = $event_id AND pi_username = '$pi_username'");
while ($worm = mysqli_fetch_array($alreadySignedUp)){
//echo $bird['total'];
if($worm['total'] >= 1 ){
echo "You have already signed up for this event.";
echo $event_id;
echo $pi_username;
echo $worm['total'];
mysqli_close($link);
return;
}
}
// Attempt insert query execution
$sql = "INSERT INTO signup (event_id, pi_username) VALUES ('$event_id', '$pi_username')";
if(mysqli_query($link, $sql)){
echo "You have been successfully added to event ".$event_id."!";
mysqli_close($link);
return;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
else {
echo "Don't forget to submit your high scores before you leave!";
}
?>
Where am I going wrong?
The signup() function was looking for elements with the same class (formSignup). All input fields had the same class name and were all being sent to the signup() function. I've updated the class name to be unique for each row. Now only a single row is being sent. The signup() function was updated to:
window.onload = function signupForm(getClass) {
var xmlHttp = new XMLHttpRequest(getClass);
Example of an input field with a unique class name:
<input class='formSignup" .$row['id']. "' type='hidden' name='event_id' id='event_id' value='" . $row['id'] . "' form='form" .$row['id']. "'>
Removed table elements and created a CSS-styled 'table' as suggested. All working now. Question updated with CSS-Styled table.
<?php
$link = mysqli_connect('localhost', 'root', '', 'slcsa');
?>
<form name="form1" action="" method="post">
<table>
<tr>
<td>Select State</td>
<td>
<select id="statedd" onchange="change_state()">
<!--we will add onchange to perform Ajax using function change_state()-->
<option value="">Select</option>
<?php
$res = mysqli_query($link,"SELECT * FROM state_code");
while($row = mysqli_fetch_array($res)){
?>
<option value="<?php echo $row["State Code"]; ?>"> <?php echo $row["State Name"]; ?> </option>
<?php
}
?>
</select><
/td>
</tr>
<!--create another dropdownlist-->
<tr>
<td>Select District</td>
<td>
<div id="districtdd">
<select>
<option>Select</option>
</select>
</div>
</td>
</tr>
</table>
</form>
<p id="demo"></p>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
function change_state()
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST", "ajax.php?state="+document.getElementById("statedd").value, false);
xmlhttp.send(null);
document.getElementById("districtdd").innerHTML=xmlhttp.responseText;
}
</script>
this is ajax.php
<?php
//$state=intval($_POST['state']);
$link = mysqli_connect('localhost', 'root', '', 'slcsa');
if (!$link) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connection to database established";
//$state = (isset($_POST['state']) ? $_POST['state'] : null);
//if(isset($_POST["state"])){
//$state=$_POST["state"];
//}
$state=$_POST['state']; //my query is not working. I am not able to get $sate value. here $sate value cannot get the value.
if ($state!=""){
$res = mysqli_query($link,"SELECT * FROM district_code WHERE State Code='".$state."'");
echo "<select>";
while($row = mysqli_fetch_array($res)){
echo "<option>"; echo $row["District Name"]; echo "</option>";
}
echo "</select>";
}
mysqli_close($link);
?>
use empty() to check value of state is empty or not use $_REQUEST[state] to get the value from url
$state=$_POST['state'] ;
if (!empty($state)){
$res = mysqli_query($link,"SELECT * FROM district_code WHERE State Code='".$state."'");
echo "<select>";
while($row = mysqli_fetch_array($res)){
echo "<option>".$row["District Name"]."</option>";
}
echo "</select>";
}
To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you want to send in the send() method:since you are using POST you must send value as argument in send()
function change_state(st)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST", "ajax.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");// without this line output will not change
xmlhttp.send("state="+st);
document.getElementById("districtdd").innerHTML=xmlhttp.responseText;
}
<select onchange=change_state(this.value)>’
Synchronous XMLHttpRequest (async = false) is not recommended because
the JavaScript will stop executing until the server response is ready.
If the server is busy or slow, the application will hang or stop.
Synchronous XMLHttpRequest is in the process of being removed from the
web standard, but this process can take many years.
Modern developer tools are encouraged to warn about using synchronous
requests and may throw an InvalidAccessError exception when it occurs.
check out this example
I have a MySQL Database on a Server. This is how my HTML stores thing in that DB
var shV = localStorage.getItem("PersName");
var idV = localStorage.getItem("codeQR");
var posV = localStorage.getItem("position");
window.open('http://*.es/insert.php?sh='+shV+'&id='+idV+'&pos='+posV,
'blank','location=no,hidden=yes,closebuttoncaption=Done,toolbar=no');
The Insert.PHP File
<?php
try {
$pdo = new PDO('mysql:host=mysql.**');
$shortV = $_GET['sh'];
$idnumberV = $_GET['id'];
$positionV = $_GET['pos'];
$statement = $pdo->prepare("INSERT INTO idtabelle (short, idnumber, position)
VALUES (:sh, :id, :pos)");
$statement->execute(array('sh' => $shortV, 'id' => $idnumberV, 'pos' => $positionV));
echo "$idnumberV eingetragen";
$pdo = null;
} catch (PDOException $e) {
die($e -> getMessage());
}
?>
I want to store them without opening a new Page or show them the Insert Url. After it is in the DB i want a Feedback like "Your Data has been entered" only when they are really in the DB.
In an other HTML I search the Position by entering an ID in an Textfield. It works like I want. In the Page and a Feedback is given.
Search.html
<form id="search" name="search" method="post">
<input type="text" id="txt1" name="search_input">
<button type="submit" class="btn btn-info" id="bt1">Get Position</button>
</form>
<div id="div1">Testing</div>
<div id="div2"> Here </div>
<script>
$(document).ready(function(){
$("#search").on("submit", function(e){
e.preventDefault();
$.post("/search3.php", $("#search").serialize(), function(d){
if (!$.trim(d)){
alert("Nothing found !"); }
else{
$("#div1").empty().append(d);
localStorage.setItem("PosGet",d);
document.getElementById("div2").innerHTML=(d);
}
});
});
});
The Search.PHP File
<?php
try {
$pdo = new PDO('mysql:host=mysql.**');
$pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$idV = (isset($_POST['search_input'])) ? $idV = $_POST['search_input'] : exit('The search was empty');
$statement = $pdo->prepare("SELECT position, short FROM idtabelle WHERE idnumber = ?");
$statement->bindParam(1, $idV);
$statement->execute();
foreach($statement -> fetchAll() as $row){
echo $row['position'];
}
$pdo = null;
} catch (PDOException $e) {
die($e -> getMessage());
}
?>
How can I do it that the Insert is like the Search above in the Page and with a Feedback?
Thank you.
in your first example the code runs a new window (but hidden), so you have no chance to get a result from the inital window. You should do it like in the second provided example.
If you can use jQuery ( your examples looks like) you can use the jQuery.ajax() function
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
You also can have a success and a failure callback. Example:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" },
function(){
console.log("success");
},
function(){
console.log("error")
}
})
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
$dbconn = pg_connect('localhost','peter','abc123','my_db');
if (!$con) {
die('Could not connect');
}
$query = "SELECT * FROM user WHERE id = $1";
$result = pg_prepare($dbconn, "my_query", $query);
$data = array($q);
$result = pg_execute($dbconn, "my_query", $data);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = pg_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>" . $row[3] . "</td>";
echo "<td>" . $row[4] . "</td>";
echo "</tr>";
}
echo "</table>";
pg_close($dbconn);
?>
</body>
</html>
The Html
<html>
<head>
<script>
function showUser(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","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
This is a simple example using PostgreSQL, for you to understand the basics. If you want more help start programming, and if you have any difficulties ask the community.
In the example above, when a user selects a person in the dropdown list above, a function called "showUser()" is executed.
The function is triggered by the onchange event.
Code explanation:
First, check if person is selected. If no person is selected (str == ""), clear the content of txtHint and exit the function. If a person is selected, do the following:
1) Create an XMLHttpRequest object
2) Create the function to be executed when the server response is ready
3) Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the dropdown list)
The page on the server called by the JavaScript above is a PHP file called "getuser.php".
The source code in "getuser.php" runs a preaper execute on a PostgreSQL database, and returns the result in an HTML table.
Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:
1) PHP opens a connection to a PostgreSQL server
2) The correct person is found
3) An HTML table is created, filled with data, and sent back to the "txtHint" placeholder.
I'm doing a program that would ask user to search from Mysql table based on onKeyup. But it seems that the response time is very slow while I don't have that much of data ~ 2873 records.
Here is my PHP code :
<?php
session_start();
if(isset($_SESSION['master'])){
require_once('connect_db.php');
require_once('output_fns.php');
<div id="openModal6" class="modalDialog6">
<div>
X
<h2><center>Search Item</center></h2>
<p>
<table>
<tr><td>
<b>Item No. :</b><br />
//User input and onKeyup
<input type="text" value="" id="item_s" autofocus required onKeyUp="related_item(document.getElementById('item_s').value,document.getElementById('store_s').value);">
<td><b>Stor</b><br />
//User select Store by default usually its first store
<select name='store_s' id='store_s'>
<?php
$query = "SELECT * from stores_list";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row = mysql_fetch_assoc($result);
echo "<option value='{$row['short']}'>{$row['short']}</option>";
}
echo "</select>";
}
else{
//No Stores Available
echo "No Stores Found !";
}
?>
</td>
</tr>
<tr><td align="center" colspan="3">
//Response Output Here
<div id="txtHint4">Waiting...</div>
</td></tr>
</table>
</p>
</div>
</div>
<?php
}
Of course this is a Modal dialogue so it basically opens up when user Click on |Search Button| and using Onclick=
As for Ajax get_item.php
<?php
require_once('connect_db.php');
$q=$_GET['q'];
$s=$_GET['s'];
if($_GET['q']=="---"){
return true;
exit();
}
//Select Result From table where item Like
$query="SELECT * FROM store_items WHERE item_no LIKE '".$q."%' AND store = '".$s."' ORDER by sub Asc";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
echo "<br />";
echo "<table width=100% height=% align=center border=1 bgcolor=white cellpadding=5 cellspacing=0 style='font-size:12px;'>";
echo "<tr><td align=center><b>Item Number</b><td align=center><b>QTY</b><td align=center><b>Unit Cost</b></td><td align=center><b>Unit Sell</b></td><td align=center><b>Cat</b></td><td align=center><b>Sub</b></td><td align=center><b>Description</b></td><td align=center><b>Store</b></td></tr>";
while($row = mysql_fetch_assoc($result)){
echo "<tr><td align=center>{$row['item_no']}</td><td align=center>{$row['qty']}<td align=center>{$row['actual_price']}</td><td align=center>{$row['selling_price']}</b></td><td align=center>{$row['cat']}</td><td align=center>{$row['sub']}</td><td align=center>{$row['short']}</td><td align=center>{$row['store']}</td></tr>";
//End of While loop
}
}
else{
echo "<br /><center><font color=red>Sorry Item Number Not Found !</font></center>";
}
?>
And finally the Function related_item
function related_item(str,str2)
{
if (str=="")
{
document.getElementById("txtHint4").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("txtHint4").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","get_item.php?q="+str+"&s="+str2,true);
xmlhttp.send();
}
What have I done wrong this far? it should fetch data quickly from the table, I don't understand like around 4-5 seconds waiting time to see data coming up inside <div id='txtHint4'>Response</div>
Please Note the items are only numbers , example (001200201000)
UPDATE :
I've checked chrome developer tool network to test out the delay part and it seems the delay goes on get_item.php file Here are the results
Query 0.36
Stalled 0.5
Request Sent 0.14ms
Waiting (TTFB) 77.555ms
Content Download 3.40s
So does it mean that there is something wrong with my PHP file? what other or better way to enhance the code? Its straight forward reading from table. Maybe I'm missing something here
It's all in the question really :)
It's clearer when I put it in bullet points what I want to do, so here it goes:
I have two forms on a page, a search form, and an 'edit profile' form. Both are in working order, individually.
The edit profile form paginates through the rows of my MySQL tbl, allowing my to edit the values for each column. Currently set up to include all rows (i.e. all stored profiles).
the search form takes any of 17 different search variables and searches that same table to find a profile, or a group of profiles.
I want to be able to enter a search term (e.g. Name: 'Bob'), query the tbl as I am doing, but use AJAX to return the unique ID's of the results as an an array stored within a variable. I then want to be able to asynchronously feed that variable to my edit profile form query (the search form would have a submit button...) so I can now page through all the rows in my table (e.g. where the Name includes 'Bob'), and only those rows.
Is the above possible with the languages in question? Can anyone help me piece them together?
I'm at an intermediate-ish stage with PHP and MySQL, but am an absolute novice with AJAX. I've only ever used it to display a text string in a defined area - as seen in demos everywhere :) Therefore, treating me like a five-year-old is greatly appreciated!
Here are my current search query, and the edit-profile form, if they help at all:
The Edit Profile form:
//pagination base
if (isset($_GET['page'])) { $page = $_GET['page']; }
else { $page = 1; }
$max_results = 1;
$from = (($page * $max_results) - $max_results);
$total_results = mysql_result(mysql_query("SELECT COUNT(*) as Num FROM profiles"),0);
$total_pages = ceil($total_results / $max_results);
echo '<span id="pagination">' . 'Record ' . $page . ' of ' . $total_results . ' Records Returned. ';
if($total_results > $max_results)
{
if($page > 1)
{ $prev = ($page - 1);
echo "<input type='submit' value='<<' />";
}
if($page == 1)
{ echo "<input type='submit' value='<<' />"; }
if($page < $total_pages)
{ $next = ($page + 1);
echo "<input type='submit' value='>>' />";
}
if($page == $total_pages)
{ echo "<input type='submit' value='>>' />";
}
}
echo '</span></p>';
?>
// the query, currently selecting all but which I would have include a WHERE clause (WHERE ProfileID = $profileid...)
<?php
$sql = ("SELECT * FROM profiles
ORDER BY ProfileID
LIMIT $from, $max_results");
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs))
{
$profile = $row['ProfileID'];
?>
<form id="profile-form" action="profile-engine.php" method="post">
<input type="hidden" name="formid" value="edit-profile">
<input type="hidden" name="thisprofile" value="<?php echo $profile; ?>">
<table id="profile-detail" class="profile-form">
<tr>
<td>
<label for="profile-name">Name:</label>
<?php
$nameresult = mysql_query("SELECT ProfileName
FROM profiles
WHERE ProfileID = '$profile'");
$row = mysql_fetch_array($nameresult);
?>
<input type="text" class="text" name="profile-name" id="profile-name" value="<?php echo $row['ProfileName']; ?>" />
</td>
//goes on in this vein for another 16 inputs :)
The Search Query:
//connection established
$query = "SELECT * FROM profiles";
$postParameters = array("name","height","gender","class","death","appro","born","tobiano","modifier","adult","birth","sire","dam","breeder","owner","breed","location");
$whereClause = " WHERE 1 = 1";
foreach ($postParameters as $param) {
if (isset($_POST[$param]) && !empty($_POST[$param])) {
switch ($param) {
case "name":
$whereClause .= " AND ProfileName LIKE '%".$_POST[$param]."%' ";
break;
case "height":
$whereClause .= " AND ProfileHeight='".$_POST[$param]."' ";
break;
case "gender":
$whereClause .= " AND ProfileGenderID='".$_POST[$param]."' ";
break;
//more cases....
}
}
}
$query .= $whereClause;
$result = mysql_query("$query");
$values = array();
while ($row = mysql_fetch_array($result)) {
$values[] = $row['ProfileID'];
}
/*
//just me checking that it worked...
foreach( $values as $value => $id){
echo "$id <br />";
}
*/
mysql_close($con);
So, there you have it! Thanks in advance for any help!
what about:
search copies search term to local variable, service returns an array of results that you hold, and then pagination uses JS to drop in the values into the appropriate fields. If you change one and save, it submits the edits, including the original search term, which is used to re-query the service, and returns the updated array...repeat as necessary
here's some sample code (here there's just two search fields, I know you need more):
<!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>Untitled Document</title>
<script type="text/javascript">
var query = new Object();
var resp;
var i;
function next(on){
i=on+1;
if(i==resp.results.length){i--;}
fillForm(i);
}
function prior(on){
i=on-1;
if(i<0){i++;}
fillForm(i);
}
function fillForm(i){
document.getElementById("paginate").innerHTML='<button onclick="prior('+i+')"><</button>'+(i+1)+' of '+resp.results.length+'<button onclick="next('+i+')">></button>';
document.getElementById("name").value=resp.results[i].name;
document.getElementById("height").value=resp.results[i].height;
document.getElementById("gender").value=resp.results[i].gender;
document.getElementById("class").value=resp.results[i].class;
document.getElementById("death").value=resp.results[i].death;
document.getElementById("appro").value=resp.results[i].appro;
document.getElementById("born").value=resp.results[i].born;
document.getElementById("tobiano").value=resp.results[i].tobiano;
document.getElementById("modifier").value=resp.results[i].modifier;
document.getElementById("adult").value=resp.results[i].adult;
document.getElementById("birth").value=resp.results[i].birth;
document.getElementById("sire").value=resp.results[i].sire;
document.getElementById("dam").value=resp.results[i].dam;
document.getElementById("breeder").value=resp.results[i].breeder;
document.getElementById("owner").value=resp.results[i].owner;
document.getElementById("breed").value=resp.results[i].breed;
document.getElementById("location").value=resp.results[i].location;
document.getElementById("id").value=resp.results[i].id;
document.getElementById("saveButton").innerHTML='<button onclick="save()">Save</button>';
}
function getData(){
query.name=document.getElementById('query_name').value;
query.gender=document.getElementById('query_gender').value;
var variables='';
variables+='name='+query.name;
variables+='&gender='+query.gender;
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)
{
resp = JSON.parse(xmlhttp.responseText);
fillForm(0);
}
}
xmlhttp.open("GET","searchNav.php?"+variables,true);
xmlhttp.send();
}
function save(){
var saving="";
saving+='?q='+query;
saving+='&name='+document.getElementById('name').value;
saving+='&height='+document.getElementById('height').value;
saving+='&gender='+document.getElementById('gender').value;
saving+='&class='+document.getElementById('class').value;
saving+='&death='+document.getElementById('death').value;
saving+='&appro='+document.getElementById('appro').value;
saving+='&born='+document.getElementById('born').value;
saving+='&tobiano='+document.getElementById('tobiano').value;
saving+='&modifier='+document.getElementById('modifier').value;
saving+='&adult='+document.getElementById('adult').value;
saving+='&birth='+document.getElementById('birth').value;
saving+='&sire='+document.getElementById('sire').value;
saving+='&dam='+document.getElementById('dam').value;
saving+='&owner='+document.getElementById('owner').value;
saving+='&breed='+document.getElementById('breed').value;
saving+='&breeder='+document.getElementById('breeder').value;
saving+='&location='+document.getElementById('location').value;
saving+='&id='+document.getElementById('id').value;
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)
{
resp = JSON.parse(xmlhttp.responseText);
fillForm(0);
}
}
xmlhttp.open("GET","saveEdits.php"+saving,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="search">
<table>
<tr><td>Name:</td><td><input type="text" id="query_name" /></td></tr>
<tr><td>Gender:</td><td><input type="text" id="query_gender" /></td></tr></table>
<button onclick="getData()">Search</button>
</div>
<div id="results">
<div id="paginate"></div>
<input type="hidden" id="id" />
<table>
<tr><td>Name:</td><td><input type="text" id="name" /></td></tr>
<tr><td>Height:</td><td><input type="text" id="height" /></td></tr>
<tr><td>Gender:</td><td><input type="text" id="gender" /></td></tr>
<tr><td>Class:</td><td><input type="text" id="class" /></td></tr>
<tr><td>Death:</td><td><input type="text" id="death" /></td></tr>
<tr><td>Appro:</td><td><input type="text" id="appro" /></td></tr>
<tr><td>Born:</td><td><input type="text" id="born" /></td></tr>
<tr><td>Tobiano:</td><td><input type="text" id="tobiano" /></td></tr>
<tr><td>Modifier:</td><td><input type="text" id="modifier" /></td></tr>
<tr><td>Adult:</td><td><input type="text" id="adult" /></td></tr>
<tr><td>Birth:</td><td><input type="text" id="birth" /></td></tr>
<tr><td>Sire:</td><td><input type="text" id="sire" /></td></tr>
<tr><td>Dam:</td><td><input type="text" id="dam" /></td></tr>
<tr><td>Breeder:</td><td><input type="text" id="breeder" /></td></tr>
<tr><td>Owner:</td><td><input type="text" id="owner" /></td></tr>
<tr><td>Breed:</td><td><input type="text" id="breed" /></td></tr>
<tr><td>Location:</td><td><input type="text" id="location" /></td></tr>
</table>
<div id="saveButton"></div>
</div>
</body>
</html>
and the search:
<?php
//connection established
$query = "SELECT * FROM profiles";
$postParameters = array("name","height","gender","class","death","appro","born","tobiano","modifier","adult","birth","sire","dam","breeder","owner","breed","location");
$whereClause = " WHERE 1 = 1";
foreach ($postParameters as $param) {
if (isset($_POST[$param]) && !empty($_POST[$param])) {
$whereClause .= " AND ".$param."='".$_POST[$param]."'";
}
}
$query .= $whereClause;
$result = mysql_query("$query");
echo "{\"results\":";
if($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
echo "[";
echo "{\"name\":\"".$row["name"]."\",";
echo "\"height\":\"".$row["height"]."\",";
echo "\"gender\":\"".$row["gender"]."\",";
echo "\"class\":\"".$row["class"]."\",";
echo "\"death\":\"".$row["death"]."\",";
echo "\"appro\":\"".$row["appro"]."\",";
echo "\"born\":\"".$row["born"]."\"";
echo "\"tobiano\":\"".$row["tobiano"]."\"";
echo "\"modifier\":\"".$row["modifier"]."\"";
echo "\"adult\":\"".$row["adult"]."\"";
echo "\"birth\":\"".$row["birth"]."\"";
echo "\"sire\":\"".$row["sire"]."\"";
echo "\"dam\":\"".$row["dam"]."\"";
echo "\"breeder\":\"".$row["breeder"]."\"";
echo "\"owner\":\"".$row["owner"]."\"";
echo "\"breed\":\"".$row["breed"]."\"";
echo "\"location\":\"".$row["location"]."\"";
//echo "\"id\":\"".$row["id"]."\"";
echo "}";
}
else{
echo "\"no\"}";
exit;
}
while($row = mysql_fetch_array($data,MYSQL_ASSOC)){
echo ",{\"name\":\"".$row["name"]."\",";
echo "\"height\":\"".$row["height"]."\",";
echo "\"gender\":\"".$row["gender"]."\",";
echo "\"class\":\"".$row["class"]."\",";
echo "\"death\":\"".$row["death"]."\",";
echo "\"appro\":\"".$row["appro"]."\",";
echo "\"born\":\"".$row["born"]."\"";
echo "\"tobiano\":\"".$row["tobiano"]."\"";
echo "\"modifier\":\"".$row["modifier"]."\"";
echo "\"adult\":\"".$row["adult"]."\"";
echo "\"birth\":\"".$row["birth"]."\"";
echo "\"sire\":\"".$row["sire"]."\"";
echo "\"dam\":\"".$row["dam"]."\"";
echo "\"breeder\":\"".$row["breeder"]."\"";
echo "\"owner\":\"".$row["owner"]."\"";
echo "\"breed\":\"".$row["breed"]."\"";
echo "\"location\":\"".$row["location"]."\"";
//echo "\"id\":\"".$row["id"]."\"";
echo "}";
}
echo "]}";
?>