Category:Php

From CodeCodex

This category includes articles with code examples written in PHP.

1) Connect to a MySQL database

A simple little function allowing you to connect to a MySQL database.

The code

<highlightsyntax>

<?php

/**

* Edit the database settings to your own.
* To use, just include the function and 
* call it using <?php db_connect(); ?>
*
* You can then do your database queries
*/

// Edit your database settings

function db_connect() {

   $db_host = "localhost";
   $db_user = "username";
   $db_pass = "password";
   $db_name = "databasename";
   
   $connection = mysql_connect($db_host,$db_user,$db_pass);
   
   if (!(mysql_select_db($db_name,$connection))) {
       echo "Could not connect to the database";
   }
   return $connection;

}

?> </highlightsyntax>

2)Add data to a mysql database

If you insert a new value to a MySQL database, and the id is an auto_increment, this simple function will obtain the id for you without having to do a new query on the database. This is the easiest way to get the id from a newly added row using a MySQL insert query without having to do a second query.

The code

<highlightsyntax>

<?php

// Do your insert query... mysql_query("INSERT etc..."); // This finds the id of the row once it has been added... $id = mysql_insert_id(); // Display it... echo $id;

?> </highlightsyntax>

3) Remove all characters except letters and numbers

If you want to strip a string of all symbols and characters other than alphanumeric letters and numbers then use this. It will take a string and erase / delete any non-alphanumeric characters, and then output a clean version without the unwanted characters.

The code

<highlightsyntax> <?php

$string = "This is some text and numbers 12345 and symbols !£$%^&"; $new_string = ereg_replace("[^A-Za-z0-9]", "", $string); echo $new_string;

?> </highlightsyntax>

4) Check that characters in a variable are alpha numeric using ereg

This verifies if a PHP variable string contains characters other than letters or numbers using the PHP function ereg. This PHP code snippet can be useful for form input where you only want users to input alpha numeric characters.

The code

<highlightsyntax> <?php

// Example 1 $text = "onlyalphanumericcharacters012345";

if (ereg('[^A-Za-z0-9]', $text)) {

 echo "This contains characters other than letters and numbers";

} else {

 echo "This contains only letters and numbers";    

}

// Example 2 $text = "mixedcharacters012345&../@"; if (ereg('[^A-Za-z0-9]', $text)) {

 echo "This contains characters other than letters and numbers";

} else {

 echo "This contains only letters and numbers";    

}

?> <highlightsyntax>

5)Add numbers to MySQL database results

Puts numbers in front of each result obtained from a MySQL database. Each item in the array has a number added in front of it.

The code

<highlightsyntax> <?php

/* This will add a number in front of each row eg. 1 - John 2 - Paul 3 - Michael 4 - Susan

  • /

$sql = "SELECT name FROM people"; $result = mysql_query($sql); $thenumber = 1;

while ($row = mysql_fetch_array ($result)) {

   echo $thenumber . ' - ' . $row['name'];
   $thenumber++;

}

?> </highlightsyntax>

6) How to include a file in PHP

If you have ever wondered how to include another PHP file into a PHP script, this simple one line code sample will show you how.

The code

<highlightsyntax> <?php

// Place this into your PHP page // and edit the file name

include "some_other_file.php";

?> </highlightsyntax>


7) Remove whitespace from a text string using the PHP trim function

If you use a form on your site then you'll know that user input can often have white space before or after the text as the person filling in the form field sometimes accidentally adds spaces. This handy function will remove the whitespace from the beginning or end of the string.

The code

<highlightsyntax>

<?php

// The original text string with whitespace at the end $textString = "This is some text with a space after it ";

// Remove the whitespace $trimmedTextString = trim($textString);

// Display the new text string echo $trimmedTextString;

?>

</highlightsyntax>

8) Find and replace words in a text string using str_replace

This will run through a section of text and change all occurrences of a word into something else using the PHP str_replace function.

The code <highlightsyntax> <?php

// The text string $text = "The quick brown fox jumped over the lazy dog.";

// The word we want to replace $oldWord = "brown";

// The new word we want in place of the old one $newWord = "blue";

// Run through the text and replaces all occurrences of $oldText $text = str_replace($oldWord , $newWord , $text);

// Display the new text echo $text;

?> </highlightsyntax>

9)Count number of words in a text string

This will count through the sentences in a section of text and show how many words are contained within it.

The code

<highlightsyntax> <?php

$text = "This is some text."; $count = count(explode(" ", $text)); echo "$text contains $count words";

?> </highlightsyntax>

10) Date and time a file was last accessed

One line of code that will show when a file was last accessed. It will display it in the form Last accessed: Tuesday, February 17th, 2004 @ 12:51:37 am

The code <highlightsyntax>

<?php

// Add this line to your php page echo "Last accessed: " . date("l, F jS, Y @ h:i:s a", fileatime($PATH_TRANSLATED));

?> </highlightsyntax>

11) Send email using the PHP mail() function

How to send an email from within a PHP page using the built in mail() function.

The code <highlightsyntax> <?php

// Your email address $email = "you@example.com";

// The subject $subject = "Enter your subject here";

// The message $message = "Enter your message here";

mail($email, $subject, $message, "From: $email");

echo "The email has been sent.";

?> </highlightsyntax>

12)Delete data from a MySQL database <highlightsyntax> How to remove and erase stored information from a MySQL database table.

The code

<?php

/*

* Change the first line to whatever
* you use to connect to the database.
*
* Change tablename to the name of your 
* database table.
*
* This example would delete a row from
* a table based on the id of the row.
* You can change this to whatever you
* want.
*/

// Your database connection code dbconnect();

$query = "DELETE FROM tablename WHERE id = ('$id')"; $result = mysql_query($query); echo "The data has been deleted.";

?> </highlightsyntax>

13) Add data to a MySQL database

How to insert and save information into a MySQL database table using PHP.

The code

<highlightsyntax> <?php /**

* Change the first line to whatever 
* you use to connect to the database.
*
* We're using two values, title and
* text. Replace these with whatever
* you want to add to the database.
*
* Finally, change tablename to the 
* name of your table.
*/

// Your database connection code db_connect();

$query = "INSERT INTO tablename(title, text) VALUES('$title','$text')"; $result = mysql_query($query); echo "The data has been added to the database.";

?> </highlightsyntax>

14) Count and display the number of rows in a mysql database table

This code will count the number of rows (entries / records) in a MySQL database table and then display it using echo on the screen.

The code

<highlightsyntax>

<?php /*

 Datebase connection code goes here.
 If you don't know how to do it, see:
 http://www.totallyphp.co.uk/code/connect_to_a_mysql_database.htm
 Change tablename to match the name of your own table
  • /

// Connect to the database db_connect();

// Query the database and get the count $result = mysql_query("SELECT * FROM tablename"); $num_rows = mysql_num_rows($result);

// Display the results echo $num_rows;

?>

</highlightsyntax>

15) Word wrap

A function that takes a string of text and wraps it into lines of a length that you determine. Can be useful for guestbooks, news posting scripts etc. to prevent the layout breaking.

The code <highlightsyntax>

<?php

/**

* Example usage:
* 
* // Your text
* $text = "This is a sentence which contains some words.";
* 
* // Or from a database result
* $text = $row['text'];
* 
* // Then put it into the function
* $text = word_wrap($text);
* 
* // Output the result
* echo $text;
*/
  function word_wrap($text) {
       // Define the characters to display per row
       $chars = "10";
       $text = wordwrap($text, $chars, "
", 1); return $text; }

?> </highlightsyntax>

16)Page redirect

If you want a PHP redirect script that redirects visitors from a page to a specific URL then this is it. It sends the user from one web page to a different web page address. It is a good alternative to using the meta tag http-equiv option.

The code <highlightsyntax>

<?php

/**

* Place in a blank PHP page
*/

// Change to the URL you want to redirect to $URL="http://www.example.com"; header ("Location: $URL");

?>

</highlightsyntax>

17) Find and replace words in a text string using str_replace

This will run through a section of text and change all occurrences of a word into something else using the PHP str_replace function.

The code <highlightsyntax>

<?php

// The text string $text = "The quick brown fox jumped over the lazy dog.";

// The word we want to replace $oldWord = "brown";

// The new word we want in place of the old one $newWord = "blue";

// Run through the text and replaces all occurrences of $oldText $text = str_replace($oldWord , $newWord , $text);

// Display the new text echo $text;

?> </highlightsyntax>

18) Write data to a text file

This will open a plain text file (.txt) and save information to it.

The code <highlightsyntax>

<?php $your_data = "This is the data to be stored in the text file.";

// Open the file and erase the contents if any $fp = fopen("textfile_name.txt", "w");

// Write the data to the file fwrite($fp, $your_data);

// Close the file fclose($fp);

?> </highlightsyntax>

19) Visitor information

Displays information about a visitor to a web page. Shows IP address, referrer and browser type.

The code <highlightsyntax>

<?php

/**

* Add this line of code in your page:
* <?php include "visitor_information.php"; ?>
*/

// Display IP address

echo "

IP Address: " . $_SERVER['REMOTE_ADDR'] . "

";

// Display the referrer

echo "

Referrer: " . $_SERVER['HTTP_REFERER'] . "

";

// Display browser type

echo "

Browser: " . $_SERVER['HTTP_USER_AGENT'] . "

";

?>

</highlightsyntax>

20) Page load time

Outputs the time in seconds that it takes for a PHP page to load.

The code <highlightsyntax>

<?php

// Insert this block of code at the very top of your page: $time = microtime(); $time = explode(" ", $time); $time = $time[1] + $time[0]; $start = $time;

// Place this part at the very end of your page $time = microtime(); $time = explode(" ", $time); $time = $time[1] + $time[0]; $finish = $time; $totaltime = ($finish - $start);

printf ("This page took %f seconds to load.", $totaltime);

?>

</highlightsyntax>

21) Convert links into clickable hyperlinks

A function to change an email address or URL into a clickable HTML hyperlink using eregi_replace.

The code <highlightsyntax>

<?php

function makeClickableLinks($text) {

 $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
   '<a href="\\1">\\1</a>', $text);
 $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
   '\\1<a href="http://\\2">\\2</a>', $text);
 $text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',
   '<a href="mailto:\\1">\\1</a>', $text);
 return $text;

}

// Usage

// Email address example $text = "you@example.com"; echo makeClickableLinks($text);

echo "

";

// URL example $text = "http://www.example.com"; echo makeClickableLinks($text);

echo "

";

// FTP URL example $text = "ftp://ftp.example.com"; echo makeClickableLinks($text);

?> </highlightsyntax>

Pages in category "Php"

The following 2 pages are in this category, out of 2 total.