Scripts and functions that I have written or found useful

Pressing enter does not submit form

September 6th, 2007 Posted in PHP | No Comments »

Problem: pressing enter on form just refreshes page/ Pressing enter in textbox refreshes page

All forms submit one of two ways…

  • By clicking submit
  • By pressing the ‘enter’ key

Sometimes you may find that pressing enter only resubmits the form or appears to just refresh it.

Reason/Solution

This is a kind of bug with html and is caused by the fact that there is only one textbox in the form, either add another text box and it will work or if you only have one field to enter then add a hidden one like so…

<input name=”" type=”t” value=”" style=”display:none”>

Dont worry, it wont affect any dynamic collection of the POST or GET values as it doesnt have a name.

mod rewrite change php to htm

August 18th, 2007 Posted in PHP, mod_rewrite | No Comments »

Options +Indexes
Options +FollowSymlinks
RewriteEngine on
RewriteBase /
RewriteRule ^(.*)\.htm$ $1.php [L]

If you change your pages from htm (or html) to php and want to maintain links particularly from Google then you can place the code above in your .htaccess file in the root folder of your website. This allows you to type http://yourdomain/mypage.htm instead of http://yourdomain/mypage.php which is better for SEO and means that any old links to your .htm page will still work

PHP Get last inserted ID from mysql

August 18th, 2007 Posted in MYSQL, PHP | 1 Comment »

$id = mysql_insert_id();

Each person on the website has a different session so if you use the above, it will automatically know which row was inserted last with this session. You do not need to worry about 2 people being on the site at the same time and creating 2 different rows.

Reading in all POST and GET variables

September 12th, 2006 Posted in PHP | 1 Comment »

This simple one liner will read in all of the variables sent via POST and GET and turn them into relevant variables within this new page, so $_GET[variable] becomes $variable automatically.

@extract($_POST);
@extract($_GET);

If this doesnt work, and some server setups stop your from doing the above, then you can use a variable variable (yes thats right, you did read it correctly) with the following code

foreach ($_POST as $key => $value)
$$key = $value;

This basically says that if $_POST['myvariable'] exists then it will create $myvariable. This is also a very easy way of filtering all input because you can simply add an extra line in the for loop like the below…

foreach ($_POST as $key => $value){
$temp = stripslashes($value);
$$key = $temp;
}

PHP + MySQL Recursive Word Search

September 8th, 2006 Posted in MYSQL, PHP | No Comments »

This script will allow you totype asmany words as you like into a text box and find instances where all of these words exists in any field. The words entered only need to be seperated by spaces, no commas required!

PHP:
  1. $search = explode(" ",$keywords);
  2. $count = count($search);
  3. for($x=0;$x&lt;$count;$x++){
  4. if($repeat == 0){
  5. $sqlquery .= " WHERE (keyword1 LIKE '%".$search[$x]."%' OR keyword2 LIKE '%".$search[$x]."%' OR caption LIKE '%".$search[$x]."%')";
  6. $repeat = 1;
  7. }else{
  8. $sqlquery .= " AND (keyword1 LIKE '%".$search[$x]."%' OR keyword2 LIKE '%".$search[$x]."%' OR caption LIKE '%".$search[$x]."%')";
  9. }
  10. }
  11. $sql = mysql_query("SELECT * FROM library ".$sqlquery) or die(mysql_error());

Simple php email script

September 8th, 2006 Posted in PHP | No Comments »

This is a simple email script which once uploaded, will send an email everytime the page is requested. It may be a good idea to add some security to this by restricting the destination email to stop spam

PHP:
  1. $subject = ''
  2. $destemail = ''
  3. $fromemail = ''
  4. $emailtext = ''
  5.  
  6. $headers = "From: ".$fromemail." \n";
  7. $headers .= "Reply-To: ".$destemail."\n";
  8. $headers .= "MIME-version: 1.0\n";
  9. $headers .= "Content-type: multipart/alternative; boundary=\"Message-Boundary\"\n\n";
  10. $headers .= "This is a multi-part message in MIME format.\n\n";
  11. $headers .= "--Message-Boundary\n";
  12. $headers.="Content-Type: text/plain; charset=iso-8859-1\n";
  13. $headers.="Content-Transfer-Encoding: 8bit\n\n";
  14. $headers.= $emailtext ."\n\n";
  15. $headers.="--Message-Boundary--";
  16. mail($destemail,"$subject","",$headers);

Javascript automatically submit a form

September 8th, 2006 Posted in Javascript | No Comments »

Simply remove the sumit button and place this after the form. Once your browser reads in this script the form will submit.

JAVASCRIPT:
  1. document.form1.submit();

Dynamic Date ticker/scroller

September 8th, 2006 Posted in Javascript, MYSQL | No Comments »

This is useful for displaying dynamic data in a small space, it scrolls the data and pauses at every line. It will also pause on mouseover

JAVASCRIPT:
  1. <script type="text/javascript"><!--
  2.  
  3.  
  4. /*Example message arrays for the two demo scrollers*/
  5. var pausecontent2=new Array()
  6. pausecontent2[0]='First item'pausecontent2[1]='Second item'pausecontent2[2]='Third item'// --></script>
  7.  
  8. <script type="text/javascript"><!--
  9.  
  10.  
  11. /***********************************************
  12. * Pausing up-down scroller- © Dynamic Drive (<a href="http://www.dynamicdrive.com/" mce_href="http://www.dynamicdrive.com/">www.dynamicdrive.com</a>)
  13. * This notice MUST stay intact for legal use
  14. * Visit <a href="http://www.dynamicdrive.com/" mce_href="http://www.dynamicdrive.com/">http://www.dynamicdrive.com/</a> for this script and 100s more.
  15. ***********************************************/
  16.  
  17. function pausescroller(content, divId, divClass, delay){
  18. this.content=content //message array content
  19. this.tickerid=divId //ID of ticker div to display information
  20. this.delay=delay //Delay between msg change, in miliseconds.
  21. this.mouseoverBol=0 //Boolean to indicate whether mouse is currently over scroller (and pause it if it is)
  22. this.hiddendivpointer=1 //index of message array for hidden div
  23. document.write('
  24. <div id="'+divId+'" class="'+divClass+'" style="position: relative; overflow: hidden" mce_style="position: relative; overflow: hidden">
  25. <div class="innerDiv" style="position: absolute; width: 100%" mce_style="position: absolute; width: 100%" id="'+divId+'1">'+content[0]+'</div>
  26. <div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" mce_style="position: absolute; width: 100%; visibility: hidden" id="'+divId+'2">'+content[1]+'</div>
  27. </div>
  28. ')
  29. var scrollerinstance=this
  30. if (window.addEventListener) //run onload in DOM2 browsers
  31. window.addEventListener("load", function(){scrollerinstance.initialize()}, false)
  32. else if (window.attachEvent) //run onload in IE5.5+
  33. window.attachEvent("onload", function(){scrollerinstance.initialize()})
  34. else if (document.getElementById) //if legacy DOM browsers, just start scroller after 0.5 sec
  35. setTimeout(function(){scrollerinstance.initialize()}, 500)
  36. }
  37.  
  38. //                                  -
  39. // initialize()- Initialize scroller method.
  40. // -Get div objects, set initial positions, start up down animation
  41. //                                  -
  42.  
  43. pausescroller.prototype.initialize=function(){
  44. this.tickerdiv=document.getElementById(this.tickerid)
  45. this.visiblediv=document.getElementById(this.tickerid+"1")
  46. this.hiddendiv=document.getElementById(this.tickerid+"2")
  47. this.visibledivtop=parseInt(pausescroller.getCSSpadding(this.tickerdiv))
  48. //set width of inner DIVs to outer DIV's width minus padding (padding assumed to be top padding x 2)
  49. this.visiblediv.style.width=this.hiddendiv.style.width=this.tickerdiv.offsetWidth-(this.visibledivtop*2)+"px"
  50. this.getinline(this.visiblediv, this.hiddendiv)
  51. this.hiddendiv.style.visibility="visible"
  52. var scrollerinstance=this
  53. document.getElementById(this.tickerid).onmouseover=function(){scrollerinstance.mouseoverBol=1}
  54. document.getElementById(this.tickerid).onmouseout=function(){scrollerinstance.mouseoverBol=0}
  55. if (window.attachEvent) //Clean up loose references in IE
  56. window.attachEvent("onunload", function(){scrollerinstance.tickerdiv.onmouseover=scrollerinstance.tickerdiv.onmouseout=null})
  57. setTimeout(function(){scrollerinstance.animateup()}, this.delay)
  58. }
  59. //                                  -
  60. // animateup()- Move the two inner divs of the scroller up and in sync
  61. //                                  -
  62.  
  63. pausescroller.prototype.animateup=function(){
  64. var scrollerinstance=this
  65. if (parseInt(this.hiddendiv.style.top)>(this.visibledivtop+5)){
  66. this.visiblediv.style.top=parseInt(this.visiblediv.style.top)-5+"px"
  67. this.hiddendiv.style.top=parseInt(this.hiddendiv.style.top)-5+"px"
  68. setTimeout(function(){scrollerinstance.animateup()}, 50)
  69. }
  70. else{
  71. this.getinline(this.hiddendiv, this.visiblediv)
  72. this.swapdivs()
  73. setTimeout(function(){scrollerinstance.setmessage()}, this.delay)
  74. }
  75. }
  76.  
  77. //                                  -
  78. // swapdivs()- Swap between which is the visible and which is the hidden div
  79. //                                  -
  80.  
  81. pausescroller.prototype.swapdivs=function(){
  82. var tempcontainer=this.visiblediv
  83. this.visiblediv=this.hiddendiv
  84. this.hiddendiv=tempcontainer
  85. }
  86.  
  87. pausescroller.prototype.getinline=function(div1, div2){
  88. div1.style.top=this.visibledivtop+"px"
  89. div2.style.top=Math.max(div1.parentNode.offsetHeight, div1.offsetHeight)+"px"
  90. }
  91.  
  92. //                                  -
  93. // setmessage()- Populate the hidden div with the next message before it's visible
  94. //                                  -
  95.  
  96. pausescroller.prototype.setmessage=function(){
  97. var scrollerinstance=this
  98. if (this.mouseoverBol==1) //if mouse is currently over scoller, do nothing (pause it)
  99. setTimeout(function(){scrollerinstance.setmessage()}, 100)
  100. else{
  101. var i=this.hiddendivpointer
  102. var ceiling=this.content.length
  103. this.hiddendivpointer=(i+1>ceiling-1)? 0 : i+1
  104. this.hiddendiv.innerHTML=this.content[this.hiddendivpointer]
  105. this.animateup()
  106. }
  107. }
  108.  
  109. pausescroller.getCSSpadding=function(tickerobj){ //get CSS padding value, if any
  110. if (tickerobj.currentStyle)
  111. return tickerobj.currentStyle["paddingTop"]
  112. else if (window.getComputedStyle) //if DOM2
  113. return window.getComputedStyle(tickerobj, "").getPropertyValue("padding-top")
  114. else
  115. return 0
  116. }
  117.  
  118. // --></script>
  119.  
  120. <script type="text/javascript"><!--
  121.  
  122.  
  123. //new pausescroller(name_of_message_array, CSS_ID, CSS_classname, pause_in_miliseconds)
  124.  
  125. new pausescroller(pausecontent2, "pscroller2", "someclass", 2000)
  126.  
  127. // --></script>

Quick and simple Mysql connect

September 8th, 2006 Posted in MYSQL | No Comments »

This is the simplest and neatest way to connect to a MySQL database using php

PHP:
  1. $dbh=mysql_connect ("localhost", "username", "password") or die ('I cannot connect to the database because: ' . mysql_error());
  2. mysql_select_db ("database_name");

Dynamically read $_POST variables into an array

September 8th, 2006 Posted in PHP | No Comments »
PHP:
  1. foreach ($_POST as $key=&gt;$value)
  2.  $url .= "&amp;".$key."=" . $value;