PHP - Looping Through A Database Table A Limited Number Of Times.
Hello,
I'm new! I am trying to populate a list of locations based on ratings. I can populate the list just fine but it's displaying every record in the table. Is there a way of only looping 4 times so as to just display the top 4 records? Here's the code: Code: [Select] $result = mysql_query("SELECT * FROM locations ORDER BY rating DESC"); while($row = mysql_fetch_array($result)) { echo $row['name']; echo "<br>; } Thankyou in advance for any help Similar TutorialsHi Guys just need some advice really I would like to know if there is a way I can check if a number is in a times table for example if(3 is in 4 times table){ do bla bla } the result for above will be false as 4 times table does not contain 3 if(12 is in 4 times table){ do bla bla } the above would be true Thanks guys How do you make php code repeat for a certain amount of times. I am only new to php and I am trying to make the code below repeat 6 times instead of repeating all the matching elements in the database. From my other coding experience I would use a for loop but as I am new to php I am not really sure how to implement the for and while loops together. I was trying to add an integer that incremented until it hit 6 and then would exit the while loop but I couldn't get it to work. This is probably a simple problem and any help would be appricated. Thanks. Code: [Select] <?php $subject_set = mysql_query("Select * FROM movies WHERE media = 'Movies' ORDER BY dateadded DESC", $connection); if (!$subject_set){ die("Database connection failed: " . mysql_error()); } while ($subject = mysql_fetch_array($subject_set)){?> <div class="par_element"> <div class="repeat_horizontal"> <div class="repeat_hor_picture"> <a href="<?=$subject['link']?>"> <img src=" <?=$subject['picture']?>" /></a> </div> <a href=" <?=$subject['link']?>"><?= $subject['title']?>.</a> </div> <?php } ?>
I want to run this loop until it has created 50 or a 100 links, max. At present it continues running even though no inputs are being added to the database. I suspect, it keeps looping through and collecting duplicates and then not adding them to the database. I see this as two options, I either limit the number of loops or must find someway for the pages that have already been crawled to be skipped. I am busy doing a php course and the lecturer is not answering questions about how the code could be improved. I figure that if you are going to do something in a training course it should be able to do what it needs to and if it doesn't it needs a little alteration. function followLinks($url) { global $alreadyCrawled; global $crawling; global $hosta; $parser = new DomDocumentParser($url); $linkList = $parser->getLinks(); foreach($linkList as $link) { $href = $link->getAttribute("href"); if((substr($href, 0, 3) !== "../") AND (strpos($href, "imagimedia") === false)) { continue; } else if(strpos($href, "#") !== false) { continue; } else if(substr($href, 0, 11) == "javascript:") { continue; } $href = createLink($href, $url); if(!in_array($href, $alreadyCrawled)) { $alreadyCrawled[] = $href; $crawling[] = $href; getDetails($href); } } array_shift($crawling); foreach($crawling as $site) { followLinks($site); } Edited January 29 by guymclarenza added info i HAVE FOLLOWING VALUES IN FEED TABLE
a1a a1b a1c a1d ......
7 8 7 7
8 9 8 8
9 7 7 8
7 8 10 9
6 4 6 7
7 8 8 5
9 7 7 6
This in an array ( select a1a,a1b,a1c,a1d from feed where .....)
1) I want to know how many times each values has occured in the array ( eg: 7 occured 10 times, 8 occured 8 times)
2) How many 7's, 8's, 9's are there in a1a, howmany .....in a1b
Number of times each values occured OVERALL in array as well as also under each head
Please help
E.g. 18:00 - 22:30 $a = "18:00"; $b = "22:30"; this would return 4.5 (hours) 22:00 - 01:00 would return 3 hours Code: [Select] if ($month <= 9){ if ($list_day <= 9){ $event_day = $year.'-'."0".$month.'-'."0".$list_day; if(isset($events[$event_day])) { foreach($events[$event_day] as $event) { $calendar.= '<div class="event">'.$event['event_date'].'</div>'; } } } Right, using a mysql query the value from $event['event_Date'] prints out in a div. I need a number count of the amount of times this value is printed. any help? Im looking to update the way my merchandise page lists items. Im trying to make it so the query will list items in a table and have it query 6 items in one row before it makes a second table row. heres my code i have now, but it lists them all horizontally down the page cuz of how i have it. but i'd like to change it to my explanation above i know i will have to change it all into a table query but how to get it to list 6 items before it makes next row is what i dont know how to do. Code: [Select] <?php if('/merch.php'==$_SERVER['PHP_SELF']) { $catquery = mysql_query('SELECT * FROM merch GROUP BY merch_cat') or die('mySQL Query Failed: '.mysql_error()); $num_rows = mysql_num_rows($catquery); if($num_rows==0){ echo 'Nothing Here'; break; } echo '<center><font size="6">'; while($row = mysql_fetch_array($catquery)){ list($id, $merch_name, $merch_image, $merch_cat, $merch_info, $buy, $price) = $row; echo ': <font class="myFont"><a href="merch.php?list=false&merch_cat='.$merch_cat.'">'.$merch_cat.'</a></font> '; } echo ':</font><br />'; echo '<center>Select a Category</center>'; echo '<br /><br />'; echo '<div><font class="myFont" size="6">New Items</font></div>'; $newquery = mysql_query('SELECT * FROM merch ORDER BY id DESC LIMIT 4') //Obviously im going to change the limit when i get this working or die('New Query Failed: '.mysql_error()); while($rows = mysql_fetch_array($newquery)){ list($id, $merch_name, $merch_image, $merch_cat, $merch_info, $buy, $price) = $rows; echo '<a href="merch.php?list=true&merch_cat='.$merch_cat.'&id='.$id.'">'.$merch_name.'<br />'; echo '<img src="media/merch/'.$merch_image.'-thumb.png" border="0"></a>'; echo '<br /><br />'; } } break; ?> Okay I'm a newbie at PHP but was trying to write a counter for my website to count the amount of times a specific button is clicked. My desired outcome is as follows: If the form submit button "like" or "dislike" is clicked, get user's ip and check to see if it already exists in the database. If it exists, don't increment the count (of either button), otherwise log the ip and increment the count (of whichever button is clicked) by 1. Currently I've got the increment working (testing only the like button at the moment) and I've got the ip being stored into the database, but cannot get the comparison to work. Each time the button is clicked it adds the ip address into the database instead of disallowing it. Note: there are two different tables--one storing the ip (counter) and one storing the like clicks (Designs) (dunno if there's a better way?) Excuse my newbieness. The problem area: (like button only): if(isset($_POST['like'])) { $ip_address = $_SERVER['REMOTE_ADDR']; $query = mysql_query("SELECT ip FROM counter WHERE ip = '$ip_address'"); $num_rows = mysql_num_rows($query); if ($num_rows > 0) { die ("You've already clicked the button!"); } else { mysql_query("INSERT INTO counter VALUES ($ip_address)"); mysql_query("UPDATE Designs SET up = up + 1 WHERE ref = 'cataclysm'"); } } $select = mysql_query("SELECT up FROM Designs"); while($row = mysql_fetch_array($select)) { echo $row['up']; } Hello, I am trying to subtract the current time from a list of times in a mysql database. The first page inserts the time into mysql.
<?php $var_Time = date("h:i:s"); $mysqli = new mysqli('localhost','root','blah','test'); if ($mysqli->connect_error) { die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error); } $insert_row = $mysqli->query("REPLACE INTO test_table (id, time) Values(NULL, '$var_Time')"); if($insert_row){ while (false); }else{ die('Error : ('. $mysqli->errno .') '. $mysqli->error); } $mysqli->close(); ?>The second page is supposed to iterate through all of the times in the database and subtract the current time, but i cant figure out how to do it. <?php $mysqli = new mysqli('localhost','root','blah','test'); if ($mysqli->connect_error) { die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error); } $query = "SELECT * FROM `test_table`"; $result = $mysqli->query($query) or die($mysqli->error.__LINE__); $var_set_time = stripslashes($row['time']); $var_current_time = date("h:i:s"); $diff = strtotime( $var_current_time .' UTC' ) - strtotime( $var_set_time .' UTC'); echo $diff; ?> Edited by Ch0cu3r, 09 October 2014 - 01:40 PM. Added code tags Hello, im looking for some help if anyone can be of help... i want to read from a file each line of that file, for each line search the database for that line found in the file and return what comes back, but i want it todo this for the whole file which could be up to 500 diffrent lines. what i have so far doesnt work ive tried a number of things including foreach() some of this could i got some somewhere else they said it worked for them. $lines = file("/var/www/htdocs/mp32/playlist.lst"); require('dbconfig1.php');//connect to db script while($n < count($lines)) { //get number of lines in file or array $recipeQuery = mysqli_query($conn1, "SELECT * FROM mp_id3_tags WHERE filename LIKE = '$lines[$n]'"); //query database for each one while($recipeQuery1 = mysqli_fetch_array($recipeQuery)) { print "{$recipeQuery1['artist']}"; } $n = $n + 1; } the second database found on the cloud
i try to get JSON data but how to insert and update them to another online database with the same table my php script to return json data <?php include_once('db.php'); $users = array(); $users_data = $db -> prepare('SELECT id, username FROM users'); $users_data -> execute(); while($fetched = $users_data->fetch()) { $users[$fetchedt['id']] = array ( 'id' => $fetched['id'], 'username' => $fetched['name'] ); } echo json_encode($leaders);
i get
{"1":{"id":1,"username":"jeremia"},"2":{"id":2,"username":"Ernest"}} Edited March 24 by mahenda Ok, I need some serious help here. I have a jQuery .load method that retrieves a single users name from a database. However... I also need to incorporate error checking into the script that the .load method access, so that, if the user enters a name in the field that is not in the database, it will insert it into the database, and then then pull it back out again to be returned by the ajax call. This is the jQuery that performs the call: Code: [Select] $('#submit').click(function(e) { var user = $('#user').val(); var checkurl = "indexData.php"; $('#username').load(checkurl, 'user=' + user); e.preventDefault(); }); This is the script form indexData.php: Code: [Select] <?php $db = mysql_pconnect('localhost', 'joeme0', 'Galatians2'); if (!$db) { die('Could not connect: ' . mysql_error()); } mysql_select_db('joeme0_brave'); $name = $_POST['name']; $checkQuery = "select name from users where name='$name'"; $checkResult = mysql_query($checkQuery); if ($checkResult > 1) { $insQuery = "insert into users (id, name) values ("", '$name')"; $insResult = mysql_query($insQuery); if ($insResul 0) { $query="select name from users where name='$name'"; $result=mysql_query($query); while($row=mysql_fetch_array($result)) { echo $row['name']; } } else { echo "Cold not insert your name into the database"; } } else { $query="select name from users where name='$name'"; $result=mysql_query($query); while($row=mysql_fetch_array($result)) { echo $row['name']; } } ?> So far I can get it to pull out a name that is manually entered into the database no problem. But I can't get it to insert a name that isn't in the database, and then query the database a second time to pull that same name back out again. The page is pretty simple. The user comes to the page, enters their name in the text field, either clicks the submit button or presses the enter key. The scripts fire off the ajax call to the database, check to see if the name exists, if not enter it and pull it back out (this is where I have the problem), if so, pull it out and display it back on the page. As I title says; I need to have an image showed the number of times, the value of a table/field.. How can I do this? Here is my java script
$.each(data, function() { var myTable1 = '<tr bgcolor=#ffffff>' + '<td align=center>'+this.vehiclelog_plate+'</td>' + '<td align=center>'+this.vehiclelog_name+'</td>' + '<td align=center>'+this.vehiclelog_date+'</td>' + '<td align=center>'+this.vehiclelog_reftype+'</td>' + '<td align=center>'+this.vehiclelog_refid+'</td>' + '<td align=center>'+this.vehiclelog_description+'</td>' + '</tr>'; $('#tableField').append(myTable1); });And here is my HTML <div id="tabs-6"> <div id="rform"> <form action = "home.php" method="post"> <fieldset> <legend>View Vehicle Service</legend><br><br> <div> <label class="label-left">Vehicle Name:</label> <span role="status" aria-live="polite" class="ui-helper-hidden-accessible"></span> <input id="autocomplete" title="type "a"" class="ui-autocomplete-input" name="vehicle_service_search" autocomplete="off"> </div> <div> <button id="searchVehicleDesc" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"> <span class="ui-button-text">View</span> </button> </div> <div> <table border="1" width="650" id = "tableField"> <tr bgcolor=#c0c0c0> <td width=100 align="center"><font face="helvetica"><b>Vehicle Name</b></font></td> <td width=80 align="center"><font face="helvetica"><b>Service Type</b></font></td> <td width=80 align="center"><font face="helvetica"><b>Others</b></font></td> <td width=100 align="center"><font face="helvetica"><b>Reference No.</b></font></td> <td width=80 align="center"><font face="helvetica"><b>Reference Date</b></font></td> <td width=80 align="center"><font face="helvetica"><b>Reference Type</b></font></td> </tr> </table> </div> </fieldset> </form> </div> </div>And here is my response [{"success":1,"plate":"SIX666","name":"YAMAHA ISUZU","date":"0000-00-00","type":"Add Vehicle","id":"0","desc":""},{"success":1,"plate":"VIE597","name":"Resource id #6","date":"2014-05-09","type":"OIL","id":"332142","desc":"castroil"}]Im getting the right response from ajax but I can't put my value to a table I get an alert that says undefined.
So I have a database that is structured like this: https://imgur.com/a/DdyTqiE
I would like to loop through this table, and get a count of how many were 'is_no_show' and 'is_cancelled' per (unique) category with respect to 'scheduled_student_services.' How would I approach this? I know I probably need to do two loops but I'm not sure the PHP syntax for this. Any suggestions or tips would be helpful. Thank you for your time! No idea what I am doing here. I have a joined table which is:
$sql = "SELECT itemnum, image1, title, close, quantity, bidquantity, ". I need to loop through the table on buser and insert select data into two other tables. One of the tables is the control table which will only have one row per buser. The other table I guess you would call the data table of the two and may have more than one row depending. The catch is these will be linked together by an invoice number. Table A, the control table has a field for invoice number, table B does not. Of course once the data is inserted into the new tables they will be joined and from there on it should be easy. I just don't know now how to get there. I've thought about using an array to loop through, but I don't know enough about them to make any sense of this. Not even sure the group by may help me in doing this. Anyone have any ideas on this? I sure do need it and thanks in advance! Hi all I have 2 tables: 1. is a tables full of images that have an id, a src and a title (images_table). 2. table is a list of records with an id, a description and an images_id (records_table) What I'm looking to do is: Loop through the records in the records_table and find the description, the description is something like this 'Welcome to Kansas'. Then, I want to loop through the images_table and find the associated image of Kansas, based on a MySQL LIKE statement. This is because the images_table has a title of 'Kansas', for example. Once this has been done, I then need to insert the id of Kansas into the images_id in the records_table a possible MySQL UPDATE. Has anyone got an idea how I could do this? Thanks Hello all, I'm collecting date/time information via a form and would like to convert the info into something that I can stick in my MySql database (a timestamp???). I'm collecting the current month (variable name: month-- of the form "mm"), day (variable name: day -- of the form "dd"), year (variable name: year -- of the form "yyyy"), time of day (variable name: time -- of the form "h:00"), and before or after noon (variable name: ampm -- of the form "am" or "pm"). Any suggestions as to how to change this into a quantity that I can store as a value and then use to compare to other date/times would be appreciated. Thanks! How do I call the last ID number from a table in MySql and echo it? This is what I have so far: Code: [Select] $query = mysql_query("SELECT idnum FROM ready_aclassft"); Maybe im comeing at it all wrong. Like the title says. I have 4 of the same number in my database, but I only want my website to display one of the 4. How can I do something like this? |