Category: Web Programming

PHP Search a Mysql Database

Nearly every website has some kind of search feature that allows you to quickly find the specific things you are looking for. This can be done a number of ways depending on the language and desired features, but I am going to show you how to search a Mysql database using PHP and a simple HTML form. The form is going to submit two variables – “q” and “submit.” The “submit” variable will tell PHP to initiate the search, and “q” will be the defined search terms that it searches the database for.

First, we need the HTML form. We do this with the “form” tags and “input” tags as the keywords and search button.

[code lang=”html”]


[/code]

This form is sending the two variables to the page “search.php.” This is where we will search our mysql database for rows that match the terms. First we will clean the search terms using trim() and addslashes() which will remove any whitespace and add backslashes “\” before any quotation marks, etc. so it isn’t a threat to our mysql database.

Visit my post on Mysql Database Connect to see how to connect to the database.

[codesyntax lang=”php” title=”search.php Source Code”]
<?php

// search.php
if(isset($_POST[“submit”])){
// Form was submitted, collect the search terms.
$search = trim(addslashes($_POST[“q”]));
if($search){
// We got the search terms, now lets search the database.
// Connect to database here.
$sql = mysql_query(“SELECT * FROM table1 WHERE column1 LIKE ‘%$search%'”);
$count = mysql_num_rows($sql);
// This will search column1 in table1 for a match of the search terms. The parentheses before and after the terms allow the search terms to be a part of other text.
if($count > 0){
// Matches were found!
echo “<p>Search: \”<em>”.$search.”</em>\” – “.$count.” Results Found.</p>”;
echo “<table width=\”100%\” align=\”center\” border=\”1\” cellpadding=\”3\” cellspacing=\”0\”>”;
echo “<tr><th align=\”left\”><strong>Search Results</strong></th></tr>”;
while($row = mysql_fetch_array($sql)){
echo “<tr><td align=\”left\”>”.$row[“column1″].”</td></tr>”;
}
echo “</table>”;
}
} else {
echo “Please enter search terms.”;
}
} else {
// Form wasn’t submitted, redirect to index.php.
header(“Location: index.php”);
}
[/codesyntax]

You can personalize the mysql query however you like of course. Edit the values “table1” and “column1” to match the table you are searching in your database and the columns you want to match the search terms to. You can even match them against multiple columns like so:

[code lang=”php”]
$sql = mysql_query(“SELECT * FROM table1 WHERE column1 LIKE ‘%$search%’ OR column2 LIKE ‘%$search%'”);
[/code]

This will try to match the search terms to column1 or column2. This will make your search range larger, thus bringing more results to your viewers. Of course when displaying your results in the table above it would be smart to include things like: date/time it was submitted, who it was submitted by, category, etc. You can do this by including other columns when you echo the data into the table, like so:

[code lang=”php”]
while($row = mysql_fetch_array($sql)){
echo “

“.$row[“column1″].” “.$row[“column2″].” “.$row[“column3″].”

“;
}
[/code]

So let’s say you wanted to display posts in a table from users, when it was posted, the last reply, etc. You would have it displayed as so:

Title Last Reply Posted By Time Posted
HTML Linking Stylesheets May 1st, 2010 bgallz April 16th, 2010
Another Post May 1st, 2010 bgallz April 16th, 2010
Another Post May 1st, 2010 bgallz April 16th, 2010
Filed under: MySQL, PHP, TutorialsTagged with: , , ,

Battlefield Games, Downloads, Videos, and more!

If you are interested in playing Battlefield 3, Bad Company 2, 2142, BF 2, Vietnam; any or all – then BFGamerz.com is your ultimate Battlefield resource. On every Battlefield game you can find free downloads, reviews, videos, forums, and soon a Battlefield League! Registration is quick and free, join today and browse the forums and find clans worldwide or get a super quick direct download FREE for any game any time.

Currently I am working on the new theme and setup in Drupal. This is taking some time and will be a while before it is ready on the new system. However you can still visit the old site here.

BFGamerz.com has tons of free content for the Battlefield games (ALWAYS growing):

  • Downloads
  • Screenshots
  • Maps
  • Reviews
  • League
  • so much more…

I made this website starting back in about June of 2008. I’ve just been slowly piecing it together to reach its entirety. The league still needs to be finished, however it has a great resource for Battlefield games. Anyone who would like to be a leader of this website and submit downloads, screen shots, videos, maps, reviews, or anything on the site please send me an email at brian@bgallz.org. I am working on getting a Bad Company 2 server currently for the website to reach some publicity in game as well as on some advertisements. Right now I need some help gathering all of the data.

But if you like to play the Battlefield games, please sign up and make some posts.

Click here to visit BFGamerz.com – Battlefield Games, Talk, and more…

Filed under: Web ProgrammingTagged with: , , , , , , , ,

PHP Timestamps time()

One of the most common ways to capture the current time in PHP scripting is by using the time() function. This returns the current timestamp which is the number of seconds after a certain date and time in the past. You can use this when entering a mysql query to note the current time of whatever action you are capturing.

We must be connected to a Mysql database in order to submit the value(s) to the database. You can see how to connect to a mysql database here.

For example, lets say we want to capture the current time of when a form is submitted:

[code lang=”php”]
timestamp where the Username field matches a specified value. We will use the date() function to echo the timestamp into a date format. We will use the m/d/Y format:

  • d – Represents the day of the month (01 to 31)
  • m – Represents a month (01 to 12)
  • Y – Represents a year (in four digits)

View a complete list of the PHP date() format list here!

Like so:

[code lang=”php”]
0){
$row = mysql_fetch_assoc($sql);
echo “You joined on: “.date(“m/d/Y”,$row[‘time’]).”.”;
} else {
echo “User has not joined!”;
}
?>
[/code]

This will output the code as such:

You joined on: 05/31/2010.

Filed under: PHP, Tutorials, Web ProgrammingTagged with: , ,

HTML body tag

The body tag in a HTML document defines the documents body. This includes the majority of the displayed content on the page, such as hyperlinks, images, etc.

Here is a basic HTML document with the body tag:

[code lang=”html”]


HTML Document


Body content.


[/code]

The body tag is supported by all major web browsers.

Body tag standard attributes:

Attribute Value Information
class classname Specified class name to an element.
dir rtl

ltr

Specified text direction to an element.
id id Specified id name to an element.
lang language_code Specified language to an element.
style style Specified style definition to an element.
Filed under: HTMLTagged with: ,

PHP Switch Function

The function switch() in PHP is used to execute different codes based on a variable’s value. This is used in place of the IF/ELSE IF statements. A default value is optional and, if specified, is used when no other option is matched. You must include a break; after each case or the following cases will all return true.

[code lang=”php”]

[/code]

You can use this with forms and such to determine an action based on a submitted value as well! Here is an example using the switch() function in a form:

[code lang=”html”]

Select your gender:

[/code]

Now on our PHP side of the script (submit.php) we will use the switch() function to evaluate the value.

[code lang=”php”]

[/code]

Filed under: PHP, Web ProgrammingTagged with: , ,

PHP Validate Email Address

When a user submits their email address in a form, you want to be sure it is a real email address. We will use the function preg_match() to see if it matches our regex for emails.

[code lang=”php”]

[/code]

You can submit the email to this function using something like this:

[code lang=”php”]

[/code]

It is that simple! 🙂 Enjoy.

Filed under: Web ProgrammingTagged with: , ,

PHP Get File Size of Remote File

Previously in a post I made for uploading a file from URL we wanted to include a file size check to make sure the file wasn’t too big before we upload it. Here I’ll show you how to get the remote file’s size and other information before doing other functions with it.

We’ll do this through a simple form. By default a form will encode all characters and convert spaces to “+” so we will leave the enctype undefined.

Then we just need the text input named “url” which I gave a default value “Enter URL Here…” and the Javascript-related attribute – onfocus. So when you focus on the text input it will change from the default value to blank.

Finally of course, we include the submit input named “submit” with the value “Submit.” We will use this value to check that the  form was submitted.

[codesyntax lang=”html4strict” title=”HTML Form”]
<form action=”getinfo.php” method=”post”>
<input type=”text” name=”url” size=”40″ value=”Enter URL Here…” onfocus=”if(this.value == ‘Enter URL Here…’) this.value = ”;” /> <input type=”submit” name=”submit” value=”Submit” />
</form>
[/codesyntax]

This HTML form will submit the entered url to getinfo.php.

We are going to the function fopen() to get the information we need from the remote file. There is one thing to be aware of using fopen() to retrieve this data. You need to be sure the fopen wrappers is enabled in your php.ini. This can not be changed using ini_set().

We are going to create a variable “contents” and add each line of the file to it as we read it. Then we will use the function mb_strlen() to get the file size of the variable. Normally we would use strlen(), however that will only read one character as one byte. That doesn’t really give you the most accurate reading if you have special characters in the file which are more than one byte.

By default the function fgets() reads each line of a file 1024 bytes at a time. The function runs until either the specified length is reached (1024 bytes) or to the end of the file. It is more resource efficient to specify a read length:

“Until PHP 4.3.0, omitting it would assume 1024 as the line length. If the majority of the lines in the file are all larger than 8KB, it is more resource efficient for your script to specify the maximum line length.”php.net

getinfo.php

[codesyntax lang=”php” title=”getinfo.php Source Code”]
<?php
// getinfo.php

if($_POST[“submit”]){
// Form is submitted.

// Check the fopen wrapper settings in php.ini
if (ini_get(“allow_url_fopen”) == 1) {

// Open the file.
$file = fopen(trim($_POST[“url”]), “r”);

if($file){
// We got the file.

$contents = “”;
while($line = fgets($file,1024)){
// Write each line to the string contents a kilobyte at a time.
$contents .= $line;
}

$filesize = mb_strlen($contents,”8bit”);
$kb = $filesize / 1024; // Returns the file size in kilobytes
echo “<strong>File Size</strong>:  “.$filesize.” bytes or “.$kb.” kilobytes.”;

} else {

echo “Remote file not found.”;

}

} else {

echo “Fopen wrappers not enabled.”;

}

}

?>
[/codesyntax]

The page will display the file size in bytes and kilobytes, as so:
File Size: 1024 bytes or 1 kilobytes.

Filed under: PHP, Tutorials, Web ProgrammingTagged with: , , ,

.htaccess Remove “www” from URL

Here is a quick and easy code you can use in your .htaccess file, located in the root directory of your website, to remove any world-wide web letters from your url. This will remove “www” from all your website’s pages as well as search engines, etc.

[code lang=”apache”]
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.mywebsite.com$ [NC]
RewriteRule ^(.*)$ http://mywebsite.com/$1 [R=301,L]
[/code]

And vice-versa you can add “www” to your website’s url with the following .htaccess code:

[code lang=”apache”]
RewriteEngine on
Options FollowSymlinks
Rewritecond %{HTTP_HOST} ^mywebsite.com [NC]
Rewriterule ^(.*)$ http://www.mywebsite.com/$1 [R=301,NC]
[/code]

All I did here was switch the places of the url of with “www” and the url without “www” in the code.

Just replace “mywebsite.com” with your website’s domain name.

Filed under: Web ProgrammingTagged with:

Mysql Rows from a Table

If you have a mysql database you can connect to, you can create tables, rows, columns, and do many other mysql functions through PHP. Let’s say we have a mysql database named “my_database”. We will connect to it using the php function “mysql_connect()” and draw information from the tables.

Config.php:
[code lang=”php”]

[/code]

This is usually placed in a config.php file and is included or required on other pages that execute mysql queries.

Now let’s move on to our query file. Let’s say we have a table named “table1.” We will insert the config file to have the connection to the database, and then select columns from the table1.

[code lang=”php”]
0){
// we have some!

// this is used to grab all rows in the table.
while($row = mysql_fetch_array($sql)){
echo ‘Col1: ‘.$row[‘col1′].’
‘;
echo ‘Col2: ‘.$row[‘col2′].’
‘;
echo ‘Col3: ‘.$row[‘col3′].’

‘;
}
} else {
// nothing found.
echo ‘No rows found.’;
}

?>
[/code]

Now, this will return simple HTML of each row with col1: (its value), col2: (its value), etc. We can get fancy and use a table to organize our information better. Here is an example:

[code lang=”php”]
if($count > 0){
// we have some, make the table!
echo ‘

‘;
echo ‘

‘;

// this is used to grab all rows in the table.
while($row = mysql_fetch_array($sql)){
echo ‘

‘;
echo ‘

‘;
echo ‘

‘;
echo ‘

‘;
echo ‘

‘;
}
} else {
// nothing found.
echo ‘No rows found.’;
}
[/code]

This will display something like this:

Col1 Col2 Col3
‘.$row[‘col1′].’ ‘.$row[‘col2′].’ ‘.$row[‘col3′].’
Col1 Col2 Col3
Row1: value1 Row1: value2 Row1: value3
Row2: value1 Row2: value2 Row2: value3
Row3: value1 Row3: value2 Row3: value3
Filed under: Web ProgrammingTagged with: , ,