Category: MySQL

Displaying Mysql Tables in PHP

Once you have a Mysql database setup with a table and some data in that table you are ready to display the data through PHP. This is very easy to do not only efficiently but also with a clean design in mind.

So let’s say this is your MySQL table:

Categories
Id, Title, Description, Timestamp

Once you have a Mysql database setup with a table and some data in that table you are ready to display the data through PHP. This is very easy to do not only efficiently but also with a clean design in mind.

Here is a basic Mysql command to grab all the data in our table “categories”:

[codesyntax lang=”php”]
<?php

$query = “SELECT * FROM categories ORDER BY id DESC”;
$sql = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($sql);

?>
[/codesyntax]

This will grab all the data out of the table “categories” in descending order by the ID. Now let’s say we want to display this in a table with headers and organization. Here is an easy example of how to do this:

[codesyntax lang=”php”]
<?php

if($count > 0){
// rows were returned by the query
// set up the table opener and headers
echo ‘<table width=”100%” align=”center” border=”0″ cellpadding=”2″ cellspacing=”0″ class=”data_table”>’;
echo ‘<tr>’;
// headers
echo ‘<th align=”left”>Title</th>’;
echo ‘<th align=”left”>Description</th>’;
echo ‘<th align=”left”>Posted Date</th>’;
echo ‘</tr>’;
for($i=0;$i<=$count;$i++){
while($row = mysql_fetch_array($sql)){
// go through all the returned rows and print the fields
echo ‘<tr>’;
if($i%2==0){
// apply row styles
echo ‘<td align=”left” class=”td_alt2″>’.$row[‘title’].'</td>’;
echo ‘<td align=”left” class=”td_alt2″>’.substr($row[‘description’],0,200).”;
// shorten to 200 characters
if(strlen($row[‘description’]) > 200){
echo ‘…’;
}
echo ‘</td>’;
echo ‘<td align=”left” class=”td_alt2″>’.date(“m/d/Y”,$row[‘timestamp’]).'</td>’;
} else {
echo ‘<td align=”left” class=”td_alt1″>’.$row[‘title’].'</td>’;
echo ‘<td align=”left” class=”td_alt1″>’.substr($row[‘description’],0,200).”;
// shorten to 200 characters
if(strlen($row[‘description’]) > 200){
echo ‘…’;
}
echo ‘</td>’;
echo ‘<td align=”left” class=”td_alt1″>’.date(“m/d/Y”,$row[‘timestamp’]).'</td>’;
}
echo ‘</tr>’;
}
}
echo ‘</table>’;
} else {
echo ‘No entries found, please try again.’;
}

?>[/codesyntax]

This will output something like so:

Title Description Posted Date
Data 1 Title Data 1 Description Data 1 Date
Data 2 Title Data 2 Description Data 2 Date
Data 3 Title Data 3 Description Data 3 Date
Data 4 Title Data 4 Description Data 4 Date
Data 5 Title Data 5 Description Data 5 Date
Filed under: MySQL, PHP, Web ProgrammingTagged with: , , , , , ,

Check if Field Exists in Mysql Table

Sometimes it is useful to know if a field exists in a mysql table before running a query using that field name, especially when the field name is coming from some kind of user input.

So to do this we use the function mysql_list_fields to grab the fields out of a table and run through them with a for loop until we find the one we are looking for – using the function mysql_field_name, in which case we return true. If we don’t find it, the function returns false.

[code lang=”php”]

[/code]

And it’s that easy!

Filed under: MySQL, PHP, TutorialsTagged with: , , , ,

PHP Pagination with Mysql

So you have a Mysql table you want to pull data from, but you don’t want to flood the page with everything in the table right! So you need some pagination to seperate all the content in the table into easy to open pages.

So let’s say this is your mysql query:

[code lang=”php”]
$sql = mysql_query(“SELECT * FROM table1”) or die(mysql_error());
[/code]

So this will grab everything from table1.

If we have a lot of rows in this table this is going to return all of them, so we need to make a pagination for all the rows returned. This requires modifying the query and adding some variables. I like to have the PER_PAGE,OFFSET, and PAGE_NUM variables defined so you can use them globally in every class and function, however you may not want the same values throughout so declare them as you wish.

Here is the header PHP for definitions:

[code lang=”php”]
// === START Pagination definitions === //
$pgNperPage=15;
$pgNpageNum=1;
if(isset($_GET[“p”])){
$pgNpageNum=(int)$_GET[“p”];
}
$pgNoffset = ($pgNpageNum – 1) * $pgNperPage;
// definitions
define(“SITE_URL”,”http://mysite.com/”,true);
define(“PER_PAGE”,$pgNperPage,true);
define(“OFFSET”,$pgNoffset,true);
define(“PAGE_NUM”,$pgNpageNum,true);
// === END Pagination definitions === //
[/code]

So we have to modify the query we use in $sql to include a limit with the offset and per page values used. I have made a pagination function which will do everything for me. We’ll pass the query along with some parameters through this function to output the new query and the pagination HTML.

Here is the function syntax:

[code lang=”php”]
pagination($query,$pageNum,$perpage,$sortable,$cat=””,$sort=””,$headers=””,$pageL=””);
[/code]

Function Paremeters:

  • $query – The original query to use for the Mysql. i.e. “SELECT * FROM table1”. (No ORDER BY or LIMIT).
  • $pageNum – Current page number.
  • $perpage – Per page integer value.
  • $sortable – Array of sortable fields in mysql table to order the results by.
  • $cat – What is being paginated. i.e. (Users, videos, comments, etc.) [Optional]
  • $sort – Field in Mysql table to sort it by. Default in the function definition is “timestamp” – usually used for date. [Optional]
  • $headers – Additional URL headers besides the sort and page number. i.e. “&g=bf-2142” (Start with & not ?) [Optional]
  • $pageL – Pagination letter. Useful if you have multiple paginations on one page. i.e. “cp”. (Default is p.) [Optional]

Here is the pagination function definition:

[code lang=”php”]
function pagination($query,$pageNum,$perpage,$sortable,$cat=””,$sort=””,$headers=””,$pageL=””){
$pagination = array();
$paginationDetails = “”;
$adjacents = 3;
if(!$perpage){
$perpage = 15; // default
}
if($cat){
$cat = ” “.$cat.””;
}
$pageNum = (int)$pageNum;
if(!$pageNum){
$pageNum=1;
}
if(!$pageL){
$pageL=”p”;
}
$pgNoffset = ($pageNum – 1) * $perpage;

if(isset($_GET[‘dsc’]) && $_GET[‘dsc’] != “”){
$dsc = “DESC”;
$urldsc = “&dsc=1”;
} else {
$dsc = “”;
$urldsc = “”;
}
if(is_array($sortable)){
if(in_array($sort,$sortable)){
$sort = trim($sort);
} else {
$sort = “”;
}
}
if($sort){
$order_by = “ORDER BY “.$sort.” “.$dsc.””;
} else {
$order_by = “”;
}
$limit = “LIMIT “.$pgNoffset.”,”.$perpage.””;
$queryNew = $query.’ ‘.$order_by.’ ‘.$limit;
$pagination[] = $queryNew;
if(strpos($_SERVER[“REQUEST_URI”],”?”)){
$pos = strpos($_SERVER[“REQUEST_URI”],”?”);
} else {
$pos = strlen($_SERVER[“REQUEST_URI”]);
}
$pageURL = substr($_SERVER[“REQUEST_URI”],0,$pos);

$pageURL .= “?sort=”.$sort.””;
$pageURL .= “&dsc=”.$dsc.””;
$pageURL .= $headers;

$sql = mysql_query($queryNew) or die(mysql_error());
$count = mysql_num_rows($sql);
if($count > 0){
$totalQuery = mysql_query($query) or die(mysql_error());
$totalCount = mysql_num_rows($totalQuery);
$total = ceil($totalCount / $perpage);
$pm1 = $total – 1;
$paginationDetails .= ‘

Displaying ‘.$count.’ of ‘.$totalCount.$cat.’.

‘;
if($pageNum > 1){
// previous button
$paginationDetails .= ‘

‘;
}
// conditionals for breaking up the pages
if($total < 7 + ($adjacents*2)){ // not enought to break up for($page=1;$page<=$total;$page++){ if($page == $pageNum){ $paginationDetails .= '

‘;
} else {
$paginationDetails .= ‘

‘;
}
}
}
else if($total > 5 + ($adjacents*2)){
// enought to hide some
if($pageNum < 1 + ($adjacents*2)){ // hide later pages for($page=1;$page<5+($adjacents*2);$page++){ if($page == $pageNum){ $paginationDetails .= '

‘;
} else {
$paginationDetails .= ‘

‘;
}
}
$paginationDetails .= ‘

‘;
$paginationDetails .= ‘

‘;
$paginationDetails .= ‘

‘;
}
else if($total – ($adjacents*2) > $pageNum && $pageNum > ($adjacents * 2)){
// in middle, hide little front and back
$paginationDetails .= ‘

‘;
$paginationDetails .= ‘

‘;
$paginationDetails .= ‘

‘;
for($page=($pageNum – $adjacents);$page<=($pageNum + $adjacents);$page++){ if($page == $pageNum){ $paginationDetails .= '

‘;
} else {
$paginationDetails .= ‘

‘;
}
}
$paginationDetails .= ‘

‘;
$paginationDetails .= ‘

‘;
$paginationDetails .= ‘

‘;
}
else {
// close to end, hide early pages
$paginationDetails .= ‘

‘;
$paginationDetails .= ‘

‘;
$paginationDetails .= ‘

‘;
for($page=$total – (3 +($adjacents*2));$page<=$total;$page++){ if($page == $pageNum){ $paginationDetails .= '

‘;
} else {
$paginationDetails .= ‘

‘;
}
}
}
}

if($pageNum < $total){ $paginationDetails .= '

‘;
}
$paginationDetails .= ‘

Page ‘.$pageNum.’ of ‘.$total.’ ‹ Prev ‘.$page.’ ‘.$page.’ ‘.$page.’ ‘.$page.’ ‘.$pm1.’ ‘.$total.’ 1 2 ‘.$page.’ ‘.$page.’ ‘.$pm1.’ ‘.$total.’ 1 2 ‘.$page.’ ‘.$page.’ Next ›

‘;
$pagination[] = $paginationDetails;
}
return $pagination;
}
[/code]

Now we just need to include the HTML and CSS classes for the pagination so viewers can navigate through the pages returned from this query.

Pagination CSS:

[code lang=”css”]
.pagination,.pagination div {
background-color: #eee;
font: 11px tahoma;
border: 1px solid #ccc;
text-align: left;
}
.a_td {
color: #343434;
background-color: #fff;
font-size: 11px;
font-family: tahoma;
}
.a_page {
color: #343434;
background-color: #fff;
font-size: 11px;
font-family: tahoma;
padding:0px;
}
.a_page:hover {
background-color: #eee;
}
.a_page a {
display:block;
padding:2px;
color: #333;
text-decoration: none;
}
.page_selected {
background-color: #333;
color: #fff;
font-weight: bold;
font-size: 11px;
font-family: tahoma;
}
.page_selected a {
color: #000;
}
[/code]

Now we have the function included on our page along with the necessary CSS styles. Now we can call the function and echo the contents of the returned array. The function pagination returns an array like so: pagination = [newMysqlQuery, paginationHTML].

So let’s say this was our function for downloads:

[code lang=”php”]
function downloads($g){
$g=mysql_real_escape_string($g); // Game
$validSorts = array(“title”,”catType”,”dl_count”,”timestamp”); // Sorts
if(isset($_GET[‘sort’]) && in_array($_GET[‘sort’],$validSorts)){
$sort = mysql_real_escape_string($_GET[‘sort’]);
} else {
$sort = ‘timestamp’; // default sort used.
}
if(isset($_GET[‘dsc’])){
$desc = “DESC”;
} else {
$desc = “”;
}
if(isset($_GET[‘p’])){
$page = (int)$_GET[‘p’];
} else {
$page = 1;
}
$query = “SELECT * FROM downloads WHERE gameCat = ‘$g'”;
$pagination = pagination($query,$page,15,$validSorts,”downloads”,$sort,”&g=”.$g.””); // Call the function.
$sql = mysql_query($pagination[0]) or die(mysql_error()); // $pagination[0] = new query.
$count = mysql_num_rows($sql);
}
[/code]

Now we have called the pagination function with some variables for displaying our downloads. Along with printing the pagination HTML you could display the rows with the new Mysql query that the function returns.

See how to display Mysql Rows here!

For this example we will simply echo the pagination HTML:

[code lang=”php”]
echo $pagination[1];
[/code]

Check this function out LIVE here:

http://bfgamerz.com/members.php

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

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: , , ,