PHP - A For Loop That Fetches Several Fields By Ajax From Database
hi every body.
i want a loop that takes and shows more than one record from database.
and then i want to show these to user by ajax.
indeed i made an html page that when user arrives at end it must do this.
first i made loop that took one record from database and it worked fine.
but for taking several records it went wrong.
this is my html file that has interact by user
webgoo-ajax.html 4.36KB
2 downloads
and this is my php file that interacts by database
ajax-get.php 1012bytes
3 downloads
when user arrives at end of page naturally ajax must be run and show several records to user.but it does'nt.
first it stays idle for 3 minutes and then loads my first record extremely.
and a point: if these pages does'nt work on IE it will work on Firefox because it did'nt worked in IE for me too.
i just want a for loop that work correctly for my need.
thank you for everything
Similar TutorialsHello, I've been trying this for hours now, looking at different examples and trying to change them to work for me, but with no luck... This is what I am trying to do: I have a simple form with: - 1 input field, where I can enter a number - 1 Submit Button When I enter a number into the field and click submit, I want that number to be send to the php file that is in the ajax call, then the script will take that number and run a bunch of queries and then return a new number. I want that new number to be used to call the php script via ajax again, until no number is returned, or something else is returned like the word "done" or something like that, at which point is simply makes an alert or populated a div with a message... The point is, that depending on the number entered it could take up to an hour to complete ALL the queries, so I want the script that is called to only run a fixed amount of queries at a time and then return the number it is currently at (+1), so that it can continue with the next number when it is called again. I would like to use jquery, but could also be any other way, as long as I get this to work. I already have the php script completed that needs to be called by the ajax, it returns a single number when being called. Thank you, vb Hi, I own a website called www.gpstudios.com, a flash games site. I didn't design it myself, but since having it built a year ago, I understand pretty much all of the inne workings. I'm a game coder so php makes good sense to me. Anyway, i woudl like to change the way a game info (instructions, description) is fetched. Currently, we have 650 games in our database. The way all the info is gotten is through mySQL. So, what I would like to do is take these lengthy instructions/description strings and put them each into a text file, within the folder destination of the game. Currently though, we don't even have a folder destination for each game, which is also a problem. Some games have extra files, which our site-developers didn't account for. There are several games that we've had to manually put into folders because of this problem (two .xml files cannot be named the same in the same folder) Also, if you go onto my website and click on a game, you get sent to playgame.php?id=xxx The main thing I would like to change though (which I have attempted before, but not succeeded with) would be to change the url adress of the games to something more like: www.gpstudios.com/games/game_name/ This is how most game websites do it. When I tried to do this myself, what I did was to simply create an index.php within the folder of one of the aforementioned games, and within this folder I wrote something as simple as: include("../../../playgame.php?id=xxx"); But upon loading this page, I would receive a load of error messages regarding all the other includes and requires in the playgame.php. So by inserting playgame.php?id=xxx in this deep folder, it destroys all other directory links elsewhere. I investigated and found that inserting set_include_path($_SERVER['DOCUMENT_ROOT']) would fix the problem with all these links, but it didnt - while the page loads, it appears to ignore anything that isn't in the root directory, including images. I tried the include method with loads of different files, and they just wouldn't load correctly if they used anything outside the root directory. And my final wish would be to do all of this automatically. To simply write a php file that I would run once and it would generate all the directories for me. It would need to copy every single description and instructions from mySQL and put them within text files within directories which are named after the game. I would then need to automatically create a load of index.phps for each individual game with some simple code similar to: include("../../../playgame.php?id=xxx"); Obviously it would be silly to create a load of unique index files with a hard copy of playgame.php, incase I want to give my site a makeover at some stage. I'm asking alot aren't I? Well I know that if I was given the code from another games website, I would understand it and it would be easy to implement, but unfortunately, despite searching, downloading and installing over 10 Flash Game arcade scripts, none of them used this method... despite their demo page showing that they do. Mainly, all I need to know is how to is how to generate a php/text file, and then I need to know what method I would use for getting the playgame.php running correctly from within a different folder. I'm pretty sure I could do the rest on my own then. Thanks! $query = "SELECT painting, date1, date2, date3 FROM paintings WHERE artist_id = '$ar' "; $result = mysql_query ($query) or die ("Invalid query: " . mysql_error ()); while ($row = mysql_fetch_assoc ($result)) { echo "The 3 sale dates for ".$row['painting']." are"$row['date......." echo "<br>"; } Now within this while loop for each painting I want to echo out the 3 dates in order (sometimes date3 may be earlier than date1 or vice-versa). How do I sort those three dates when I am already in the while loop? Also how this work if one of the dates was blank? Thanks. for($i=1; $i<=$round; $i++){ print "<tr><td align='left' valign='top'><input type='text' name='number$i' maxlength='2' size='2' /></td>\n "; print "<td align='left' valign='top'><input type='text' name='score$i' maxlength='1' size='1' /></td>\n "; print "<td align='left' valign='top'><select name='team$i'>\n"; print "<option value='-'>-<option>\n"; print "<option value='Home'>Home<option>\n"; print "<option value='Away'>Away<option>\n"; print "</select></td></tr>"; }What I'm having trouble with is that for every option tag there is an empty option tag added. How do I get rid of those empty option tags? Thankful for any help. Hi can anybody help I need to export and download tables from a database into a excel sheet. I have this code and it works what I need is to export specific fields and not just the whole table can anyone help modifying the code to export certain fields within the table please? Here is the code... Code: [Select] <?php $host = 'localhost'; $user = 'user'; $pass = 'password'; $db = 'qdbname'; $table = 'tablename'; $file = 'export'; $link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error()); mysql_select_db($db) or die("Can not connect."); $result = mysql_query("SHOW COLUMNS FROM ".$table.""); $i = 0; if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { $csv_output .= $row['Field']."; "; $i++; } } $csv_output .= "\n"; $values = mysql_query("SELECT * FROM ".$table.""); while ($rowr = mysql_fetch_row($values)) { for ($j=0;$j<$i;$j++) { $csv_output .= $rowr[$j]."; "; } $csv_output .= "\n"; } $filename = $file."_".date("Y-m-d_H-i",time()); header("Content-type: application/vnd.ms-excel"); header("Content-disposition: csv" . date("Y-m-d") . ".csv"); header( "Content-disposition: filename=".$filename.".csv"); print $csv_output; exit; ?> I am quite new to PHP and MySQL. I am trying to figure out what datatypes to use for different fields in a Database. For ID (Identification) I use INT, for name I use VARCHAR and for people to write text messages, I use LONGTEXT. For date and time I use DATETIME.
What I am unsure about, however, is what type to use for an email adress and for an IP address? I have been watching videos at Youtube about the Datatype for IP addresses, but they don't seem always to agree. I hope someone can put me in the right direction on those two.
Regards,
Erik
Hello all, I'm new to PHP and new to this forum (although I have benefitted from your help already -cheers!). However, this time I cannot find the answer I need/recognise/understand.. I have a form and want to conduct tests on each field returning an error message as a session variable if the test fails. The test will be different for some of the fields, and the error message is specific to each field. If there is an error in any one of the fields I want to be redirected to a failure page where all of the error messages are displayed, otherwise I am sent on to another page. I have already written and tested a function to sanitise the incoming form data, so that's not a problem - it's just how to loop through and test. I can guess that there are many ways to do this but I need to understand why one option is better than another, and follow the syntax used (it's all part of my steep learning curve) The approach I have thought to use is to create an array holding the field name, the test and the message, then loop through using foreach, applying the array values into the test and creating the error message....but it's not working for me. The other method is to declare a variable $Stop='No' and if the loop identifies an error, part of the output is to change this to 'yes' and through that redirect to the error page. I'd really welcome your advice and tuition....cheers.. my code so far is... Code: [Select] $Stop='No'; $StaffPassCheck=sanitisealphanum($_POST['PasswordCheck']); $Errors[0]['value']= sanitisealphanum($_POST['FirstName']); $Errors[0]['message']='Please re-enter your name'; $Errors[0]['test']=($StaffFname=""); $Errors[1]['value']= sanitisealphanum($_POST['Surname']); $Errors[1]['message']='Please re-enter your surname'; $Errors[1]['test']=($StaffSname=""); $Errors[2]['value']= sanitisealphanum($_POST['Post']); $Errors[2]['message']='You must select an option'; $Errors[2]['test']=($StaffPost="Select Value"); $Errors[3]['value']= sanitisealphanum($_POST['Username']); $Errors[3]['message']='You must select an option'; $Errors[3]['test']=($StaffUser=""); $Errors[4]['value']= sanitisealphanum($_POST['Password']); $Errors[4]['message']='Please re-enter your password'; $Errors[4]['test']=($StaffPass=""); $Errors[5]['value']= sanitisealphanum($_POST['PasswordCheck']); $Errors[5]['message']='Sorry, your passwords do not match'; $Errors[5]['test']=($StaffPass===$StaffPassCheck); foreach ($Errors as $key => $Value){ if ( $Errors['test']=true ){ $Stop='Yes'; return $_SESSION[$key]=$Value['message']; } } if ($Stop='Yes'){ header('Location.test.php'); die(); }else{ header('Location.indexp.php'); } Hiya I was wondering how one would get make dynamic url variable value pairs from a databases fields. I have a database that I want to use to store variable value pairs that will be used on my pages for dynamic content. It will check one thing for certain besides if the variable value pair match. The table looks like this rpg loc_type loc_type template I want it to check if the rpg is in an array and then check if the url variable and value pair match on from the database. I dont know much about auto code that would generate this on its own and I'm not sure if you can say $_GET[$location]; I dont want to hard code it so it only works with what i code I want the urls variable value pair to be based on the database info which determines which template to show based on those values. Hi all, I'm brand new to php / mysql and I'm trying to modify this script which currently runs a search on two fields "product_number" and "product_name". I also want the search to consider a third field "product_type". When I remove either product_name or product number from the following part of the code, it removes that field from being considered in the search: Code: [Select] $search_map = array($orderby, 'product_number','product_name',); So shouldn't I be able to just add the third field's name to this array and have it be considered too? I'm a complete beginner so I'm hoping this is a simple fix and I just dont get it. Here's the rest of what I think is the relevant code: Code: [Select] function load_all_products() { global $AppUI; global $sorted_item_list; global $additional_pfilter; load_type_list(); $orderby = 'product_id'; $search_map = array($orderby, 'product_number','product_name',); $where = $AppUI->getState( 'QuoteIdxWhere' ) ? $AppUI->getState( 'QuoteIdxWhere' ) : '*'; $not =" "; $op = " OR"; $check = substr(trim($where),0,4); if(stristr($check,"NOT")){ $op ="AND"; $not = " NOT "; $where = substr(trim($where),4); $where = trim($where); } // assemble the sql statement $q = new DBQuery; $q->addTable('products'); $q->addJoin('companies', 'com', 'products.product_company_id = com.company_id'); $q->addJoin('users', 'u', 'products.product_owner = u.user_id'); $q->addQuery('products.*, com.company_name, u.user_username'); $where_filter = " "; foreach($search_map as $search_name) $where_filter .=" $op $search_name $not REGEXP '$where'"; $where_filter = substr($where_filter, 5); // echo $where_filter; if($where != "*") $q->addWhere("($where_filter)"); $q->addOrder('product_id'); $sql = $q->prepare(); $q->clear(); $sql_list = db_exec( $sql ); if ($sql_list) $rn = db_num_rows( $sql_list ); else { echo db_error(); $rn = 0; } $product_list = array(); foreach ($sql_list as $item) { $product_list[ $item[ 'product_id' ] ] = $item; } // sort the list global $sort_state; if ( !isset( $sort_state ) ) $sort_state = getProductSortState(); if ( isset( $sort_state[ 'sort_item1' ] ) ) { if ( isset( $sort_state[ 'sort_item2' ] ) ) { $sorted_item_list = array_csort2( $product_list, $sort_state['sort_item1'], intval( $sort_state['sort_order1'] ) , $sort_state[ 'sort_item2' ], intval( $sort_state['sort_order2'] ) ); } else { $sorted_item_list = array_csort2( $product_list, $sort_state['sort_item1'], intval($sort_state['sort_order1']) ); } } else $sorted_item_list = array_csort2( $product_list, 'product_id' ); } Thanks! I wrote a piece of code that lists images that don't have a match in the database: Code: [Select] $dir_path = '../images/productImages'; $images = scandir($dir_path); $query = "SELECT image FROM Database_table ORDER BY name DESC"; $results = mysql_query($query); $output = "<h1>Missing Images</h1>"; $output .= "<div class=\"missingImages\">"; $output .= "<p>The following data was found in the Database_table.images field but not in /images/productImages:</p>"; $output .= "<div class=\"missingImg\">"; $output .= "<p class=\"fieldName\">Database_table.images:</p>"; while ($fetch = mysql_fetch_array($results)) { $clean_fetch = str_replace("productImages/", "", $fetch); $diff = array_diff($clean_fetch, $images); foreach (array_unique($diff) as $key => $value) { $output .= $value . "<br />"; } } $output .= "</div>"; $output .= "</div>"; echo $output; Works. Now I would like to check whether there are any files in the folder that are not in the database table. I thought it would be as easy as swapping the array_diff parameters around but it's not. When i swap the parameters like so - array_diff($images, $clean_fetch) it gives me a list of ALMOST all the images in the image folder, which i don't understand. Why does it not give me only the images that are present in the folder but not in the database? I have a relational table call sales with prodcut_id and custmer_id tables. I also have a product and customer tables. products table with product_id as an auto increment and customer with custumer_id I want to join through the sales tables all t he fields of row 1 from tables customer and products and pull it at once. This is a member login script and I want to display the products by members. So far I have this query to display the products once the member is login in. $userid is the id of the customer coming from the $userid= $_SESSION['customer_id']; $mysqlSales="SELECT products.* FROM products JOIN sales ON (products.product_id = procuct_id ) WHERE sales.customer_id = '$userid'"; so far that statement is not working where should I have some type of incoherance with the english statement above expressing what I want the query to do. Hi friends, a quick print_r() shows the following array while connecting to my database. How to get them as individual items and display on the website ? Array ( [0] => Array ( [id] => 52 [document_name] => xyz [document_ext] => gif [download_file_name] => ktm_impact.gif [upload_dt] => 2010-08-11 ) ) This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=352528.0 I am using ajax live search to retrieve data from MySQL table. It works fine. However I noticed that it only returns a single result that matches the entire word instead of multiple results that match only the first couple letters. For e.g. DB Table ---------------- 1. Foot 2. Foot Path 3. Football ---------------- If I type "foo" in the ajax search field, it won't return any results. But if I type "foot", it'll return "Foot". It won't return the other two results that contain the letters "Foot". Here's my query $param_term = $_POST["term"] . '%'; $get_data = $db->prepare("SELECT name FROM table WHERE title LIKE :param"); $get_data->bindParam(':param', $param_term); $get_data->execute();
I was wondering how can I improve the above query so that it looks for all potential results based on partial matching of letters? I'm using PHP and MySQL. I have an application where I'd like to keep certain database (character) fields encrypted when added to the database and stored, but when I need to display them at the appropriate time, I can call a function and quickly decrypt them for display. Does anyone know of a simple way to do this? Thanks! I can not get the values from the javascript add row to go dynamically as a row into MySql only the form values show up as the form below as one row. I made it as an array, but no such luck, I have tried this code around a multitude of ways. I don't know what I am doing wrong, kindly write out the correct way.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR...ransitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Dynamic Fields js/php to MySql need to submit dynamically to the database</title> <?php require ('database.php'); ?> <script type="text/javascript"> var counter = 1; var collector = ""; function addfields(indx) { var tbl = document.getElementById('table_id'); var newtr = document.createElement('tr'); counter = counter + indx; newtr.setAttribute('id','tr'+counter); newtr.innerHTML = '<td><input type="checkbox" name="checkb'+counter+'" id="checkb'+counter+'" value="'+counter+'" onclick="checkme('+counter+')"></td><td><input type="text" name="text1[]"></td><td><textarea name="textarea1[]"></textarea></td>'; tbl.appendChild(newtr); } function checkme(dx) { collector += dx+","; } function deletetherow(indx) { var col = collector.split(","); for (var i = 0; i < col.length; i++) { var remvelem = document.getElementById('tr'+col[i]); var chckbx = document.getElementById("checkb"+col[i]); if(remvelem && chckbx.checked) { var tbl = document.getElementById('table_id'); tbl.removeChild(remvelem); } } } </script> </head> <body> <form enctype="multipart/form-data" id="1" style="background-color:#ffffff;" action="<?php echo $_SERVER['PHP_SELF']; ?>"></form> <table id="table_id" > <tr id="tr1" class="trmain"> <td> </td> <td> <input type="text" name="text1[]"> </td> <td> <textarea name="textarea1[]"></textarea> </td> </tr> </table> <input type="button" value="Add" onClick="addfields(1);" /> <input type="button" value="Delete" onClick="deletetherow()" /> <input type="submit" value="Send" id="submit" name="submit"/> <?php if(isset($_POST['submit'])) { for ($i=0; $i < count($_POST['text1']); $i++ ) { $ced = stripslashes($_POST['text1'][$i]); $erg = stripslashes($_POST['textarea1'][$i]); } $bnt = mysql_query("INSERT INTO tablename (first, second) VALUES ('$ced', '$erg')")or die('Error: '. mysql_error() ); $result = mysql_query($bnt); } ?> </body> </html> Hello, I am trying to implement some code I found and downloaded he http://www.roscripts.com/Ajax_autosuggest_autocomplete_from_database-154.html When I try and run this I get no search results back when searching? I have entered data in the database and all connections seem good. Several people in the comments say they have problems, but no solution. Any one that can find the fault here? - THANKS <?php require_once('db.php'); include('classes/stem.php'); include('classes/cleaner.php'); if( !empty ( $_POST['search'] ) ): $string = $_POST['search']; $main_url = 'http://www.roscripts.com/'; $stemmer = new Stemmer; $stemmed_string = $stemmer->stem ( $string ); $clean_string = new jSearchString(); $stemmed_string = $clean_string->parseString ( $stemmed_string ); $new_string = ''; foreach ( array_unique ( split ( " ",$stemmed_string ) ) as $array => $value ) { if(strlen($value) >= 3) { $new_string .= ''.$value.' '; } } $new_string = substr ( $new_string,0, ( strLen ( $new_string ) -1 ) ); if ( strlen ( $new_string ) > 3 ): $split_stemmed = split ( " ",$new_string ); mysql_select_db($database); $sql = "SELECT DISTINCT COUNT(*) as occurences, title, subtitle FROM articles WHERE ("; while ( list ( $key,$val ) = each ( $split_stemmed ) ) { if( $val!='' && strlen ( $val ) > 0 ) { $sql .= "((title LIKE '%".$val."%' OR subtitle LIKE '%".$val."%' OR content LIKE '%".$val."%')) OR"; } } $sql=substr ( $sql,0, ( strLen ( $sql )-3 ) );//this will eat the last OR $sql .= ") GROUP BY title ORDER BY occurences DESC LIMIT 10"; $query = mysql_query($sql) or die ( mysql_error () ); $row_sql = mysql_fetch_assoc ( $query ); $total = mysql_num_rows ( $query ); if($total>0): echo ' <div class="entry">'."\n"; echo ' <ul>'."\n"; while ( $row = mysql_fetch_assoc ( $query ) ) { echo ' <li>'."\n"; echo ' <a href="'.$main_url.'articles/show/'.$row['id'].'">'.$row['title'].''."\n"; echo ' <em>'.$row['subtitle'].'</em>'."\n"; echo ' <span>Added on 2007-06-03 by roScripts</span></a>'."\n"; echo ' </li>'."\n"; } echo ' </ul>'."\n"; echo ' </div>'."\n"; endif; endif; endif; ?> The code can be found in attached zip file. this is my sql code Code: [Select] <?php $query = "SELECT Player, SUM(GLI) AS 'gli', SUM(Goals) AS 'goals', SUM(Saves) AS 'saves', SUM(SOG) AS 'sog', SUM(Assists) AS'assists', SUM(CK) AS 'ck', SUM(YC) AS 'yc', SUM(RC) AS 'rc' FROM pinkpanther_stats GROUP BY Player; "; ?> their are 11 separate players and i want to set variables $adam_glie and $tyler_glie equal to the glie column for that player(the player being the first part of the variable) and i dont have any idea how to go about doing this Hello forum. I'm new here, but I've been reading and finding useful things for a while now. I'm still new to PHP and I need a little help. I'm doing a school project and I have some things I want to do, but do not know how to write it down in PHP. I think I'll ask a lot of questions this week, and I hope I will get some help.. For start I want to ask this: I've been using Code: [Select] mysql_fetch_array() for doing loops and populating check-boxes. And everything's working fine.. but what I want is to control the actual loop by clicking buttons. Let's say first time a while-do is run, my check-boxes get populated from the database and every other loop the next data from the table is added.. pretty straightforward. I want to be able to populate once, then click "next" and the new data to be added and so on.. Code: [Select] <?php $tema = mysql_query("SELECT * from questions")or die(mysql_error()); function answer1($string) { $string1 = explode("/", $string); echo $string1[0]; } function answer2($string) { $string1 = explode("/", $string); echo $string1[1]; } while ($row=mysql_fetch_array($tema)) { echo mysql_fetch_array($tema); $tip=$row["tip"]; if ($tip==2) { $id=$row['prasanje_id']; $question=$row['question']; $answer=$row['answer']; ?> <label> <?php echo $question?></label><br> <input type="checkbox" name="CheckboxGroup1" value="checkbox" id="CheckboxGroup1_0" /> <?php answer1($tekst) ?></label> <label> <input type="checkbox" name="CheckboxGroup1" value="checkbox" id="CheckboxGroup1_1" /> <?php answer2($tekst) ?></label> <?php } } ?>I want an alternative to the while-do loop.. Is it possible to do this? Thanks!! Is it possible to use for loop to insert values into database using for loop? Or what would be the another way to insert these values into the database if the number of values being entered differs from one time to another? Here is basically what I am trying to do: mysql_query("INSERT INTO MaxMillionsNum SET Day='$weekday', DrawDate='$CompleteDate', DateTime='$timestamp', for($i=1; $i<=$SetNumber; $i+=1){ for($j=0; $j<7; j+=1){ $NumberName="Number".$i.$v[$j];//Generating name of database field $$NumberName=$Match[0][$j];//Here I would store the $Match value into the fieldname name created above } } Tries='$RunCounter'"); |