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

Javascript & PHP Star Rating Script

I’ve searched around the interwebs for an ajax star rater and I came across a few different possibilities, all of which looked very good. The top result from google was Nick Stakenburg’s “Starbox” for “ajax star rater”. I also found Masuga Web Design’s Ajax Star Rater and a script from MySandbox to be popular results. However I couldn’t really seem to find a PHP / Mysql script that used Javascript for the rater effects. So I decided to make one based off of a script I found:

Reign Water Design’s 5 Star Rating System

This was a very nice easy to use Javascript 5 star rating script. All I had to do was make some tweaks to my preference and add on some PHP/Mysql code to submit the rating.

See the demo or download this script.

To view the PHP source code, images, and everything together you must download this script.

Javascript

Insert the following in the <head> tags of your page:
[codesyntax lang=”html4strict” title=”Javascript Source Code”]
<script type=”text/javascript”>
function insertParam(key, value)
{
key = escape(key); value = escape(value);

var kvp = document.location.search.substr(1).split(“&”);

var i=kvp.length; var x; while(i–)
{
x = kvp[i].split(“=”);

if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join(“=”);
break;
}
}

if(i<0) {kvp[kvp.length] = [key,value].join(“=”);}

//this will reload the page, it’s likely better to store this until finished
document.location.search = kvp.join(“&”);
}
function alterDisplay(id){
var dropdown = document.getElementById(id);
if(dropdown.style.display == “none”){
dropdown.style.display = “”;
} else {
dropdown.style.display = “none”;
}
}
</script>
<script type=”text/javascript” language=”javascript” src=”./scripts/ratingsys.js”></script>
[/codesyntax]

CSS

You will need to include this in the <head> tags as well either in <style> tags or by <link>:
[codesyntax lang=”css” title=”CSS Styles”]
#rateMe #rate_overlay {
position:absolute;
display:block;
float:left;
margin:0;
padding:0;
height:30px;
width:auto;
background:#eee url(./images/star_overlay.gif) repeat-x;
z-index:2;
cursor:default;
}
#rateStatus{width:100px; height:20px;margin:4px 0 0 5px;font: 12px “Trebuchet MS”, Arial, Helvetica, sans-serif; font-weight: bold}
#rateMe{width:152px; height:50px; padding:1px; margin:0px; vertical-align:top; z-index:auto; border: 1px solid #ccc; }
#rateMe li{float:left;list-style:none;}
#rateMe li a:hover,
#rateMe .on{background:url(./images/star_on.gif) no-repeat;}
#rateMe a{float:left;background:url(./images/star_off.gif) no-repeat;width:30px; height:30px;cursor:pointer;}
#rateMe a:hover{background:url(./images/star_on.gif) no-repeat;}
#rateMe a.grey,#rateMe a.grey:hover{background:url(./images/star_off.gif) no-repeat; cursor:default;}
#rateVotes{display:block; margin-left:65px; font: 11px “Trebuchet MS”, Arial, Helvetica, sans-serif; color:#4a4a4a;}
#ratingSaved{display:none;}
.saved{color:red; }
.grey

.rate_on_button {

}
.rate_on_button a { float:left;padding:10px;margin:0 5px;border:2px solid #666; background-color:#fff; color: #000; font-size: 2em; text-align:center; display:block; color: #000; text-decoration: none; }
.rate_on_button a:hover { color: #fff; text-decoration: none; background-color: #333; }
[/codesyntax]

Basically I took the script that Water’s made and changed a few things to the css styles, added an overlay for the current rating, and wrote a php script to insert rates and determine the current rating, etc. I also added the Javascript functions insertParam() and alterDisplay(). You do not need to use this function insertParam() to create the url, you can simply set the <a> tags to something like this:

[codesyntax lang=”html4strict”]
<a href=”./index.php?r=1″ id=”_1″ title=”Terrible” onmouseover=”rating(this)” onmouseout=”off(this)”></a>
[/codesyntax]

The Javascript function alterDisplay() is used to hide and show the overlay <div> that holds the current rating (if there is one). So when you mouse over the rating bar holder it hides the overlay so you can rate.

The PHP script grabs the information from the Mysql table that you specify in the function. You will need to adjust the following values:

  • $var – The column to base your mysql selection off of. Grab all rows where this column equals $id.
  • $table – The table where the ratings are being held.
  • $star_width – Width of the stars, default is 30px.

You will need to be connected to a MYSQL database before calling the rating bar function.

Since the syntax of the function is the following:

[codesyntax lang=”php” title=”Rating Bar Syntax”]
function rating_bar($id);
[/codesyntax]

You will need to supply the identifier ($id) which tells the PHP script which row to grab from the Mysql table.

To display the current rating after it has been rated on – because Javascript alone is not enough – I added an overlay <div> which will hold the current rating. This is done by setting the css style of this overlay div to the following:

[codesyntax lang=”css” title=”Rate Overlay CSS Style”]
#rateMe #rate_overlay {
position:absolute;
display:block;
float:left;
margin:0;
padding:0;
height:30px;
width:auto;
background:#eee url(./images/star_overlay.gif) repeat-x;
z-index:2;
cursor:default;
}
[/codesyntax]

The position: aboslute and z-index: 2 style attributes make the div lay over top of the rateMe div which holds the rater and has a z-index: 1.

Test out this free script with the demo link at the top of the post or download it and use on your own website. Credit where due is always appreciated.

Any questions or problems please feel free to email me at brian@bgallz.org or post here.

Filed under: Featured, Javascript, PHP, Scripts, TutorialsTagged 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: , , , ,

Mysql Rows in HTML Option Tag

Let’s say you want to have a simple HTML <select> form as a drop down for rows in a Mysql table. This could be for things like categories, pages, games, anything you want to have in a drop down to navigate to another page or submit a form. What ever the case is, I’m going to make a simple layout for displaying rows returned from a mysql query as <option>’s in a HTML <select> or drop down.

Before we can grab anything from a mysql database we have to connect to it. Find how to connect to a mysql database here.

Let’s make our mysql query first:

[code lang=”php”]

[/code]

This will grab all the rows in “table1” ordered by the value of “id” descending. You can make this query whatever you want whether you want it ordered differently or with other requirements, etc. Now we will just make a <select> inside of a HTML form that holds each of these values as a option.

[code lang=”html”]


Categories

Category:



[/code]

If you have rows returned in you mysql query you will have a HTML drop down that looks like this:

Categories:

This HTML form is being submitted to “index.php?do=nav.” Of course you can point this where ever you want to do whatever you want with it, but let’s say we want to have it direct you to a category with PHP. So we are going to run a function on index.php?do=nav that will redirect the viewer to the category.

[code lang=”php”]

[/code]

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

PHP Users Online with Mysql

Using PHP and Mysql you can keep track of the users online your website and display it on your page.

First thing ,we need a table in our Mysql database for the users online. So let’s make a table in our database.

[code lang=”sql”]
mysql_query(“CREATE TABLE online(
id INT(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
ip_address VARCHAR(25) NOT NULL,
timestamp VARCHAR(25) NOT NULL)”) or die(mysql_error());
[/code]

Now that we have the table, we need to update the users online on every page. That way it is most accurate and up to date with who is currently online. We will set a time offset so that we include all users online within the past 5 minutes.

[code lang=”php”]
0){
mysql_query(“UPDATE online SET timestamp = ‘”.time().”‘ WHERE ip_address = ‘$ip’) or die(mysql_error());
} else {
mysql_query(“INSERT INTO online (ip_address,timestamp) VALUES (‘$ip’,'”.time().”‘)”) or die(mysql_error());
}
$delete = mysql_query(“DELETE FROM online WHERE timestamp < '$time_offset'") or die(mysql_error()); ?>
[/code]

Now every time someone goes on a page with this code, mysql will check to see if the user is in the system, and if so update their current timestamp, otherwise create a row for them in the table. It will also erase any rows with old timestamps. This will keep the table clean and updated.

Now we count the users online and show it on the page.

[code lang=”php”]
‘$time_offset'”);
$online = mysql_num_rows($sql);

return ‘There are ‘.$online.’ user(s) currently online. ‘;
}
?>
[/code]

Filed under: TutorialsTagged with: , ,

PHP Display Mysql Rows with Column Limit

This little script is very useful for having a set width of a table and displaying several rows organized in that table.

It is easy to just display a table full of rows for all the data in a mysql table. Something like this:

[code lang=”php”]
0){
echo “

“;
echo “

“;
while($row = mysql_fetch_array($sql)){
echo “

“;
}
echo “

“.$row[“col1″].”

“;
}
?>
[/code]

This will grab all content of the mysql table and put the data from column 1 as a table column in this table.

Let’s say we have some images we want to display. The table is 500 pixels wide. So if your images are no larger than 100 pixels, you would want to display 5 columns per row in your table. This will give it good organization and flow in your webpage.

[code lang=”php”]
0){
echo “

“;
echo “

“;
for($i=0;$i<=mysql_num_rows($sql);$i=$i+1){ while($row = mysql_fetch_array($sql)){ $i++; if($i%5==0){ // use the operator to find the remainder of $i / 5 (%) // if the remainder is 0; it is a multiple of 5, so make a new row. echo " “;
} else {
echo “

“;
}

}
}
echo “

“;
}
?>
[/code]

The two codes will appear like so:

Before Column Limit:

Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7 Image 8 Image 9 Image 10

After Column Limit:

Image 1 Image 2 Image 3 Image 4 Image 5
Image 6 Image 7 Image 8 Image 9 Image 10
Filed under: TutorialsTagged 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: , ,

Mysql Database Connect

To connect to a Mysql database you need a few things first.

Of course you need to have the database created with a name you make up as well as the username and password of the mysql account that can connect to that database. This is very simple if you are using web managing software such as Cpanel or DirectAdmin. Under the Mysql databases area you can do all of this quickly.

For many websites mysql connections are included in a common file such as “config.php”. Here is how a basic mysql connection looks:

[code lang=”php”]
$host = “localhost”;
$db_username = “USERNAME”;
$db_password = “PASSWORD”;
$db_name = “DATABASE”;

mysql_connect($host,$db_username,$db_password) or die(mysql_error());

// should there be any errors, we will receive them before reaching any further
// we have connected to the mysql server successfully, now let’s get into the database

mysql_select_db($db_name) or die(mysql_error());

// if the following returns no errors, you are now connected to your mysql database
[/code]

$host – The host that you are connecting to. Usually set to “localhost”.
$db_username – The username of the account that connects to the database specified.
$db_password – The password of the account that connects to the database specified.
$db_name – The name of the database you are connecting to. This is shown in your domain managing area.

This code will connect to a mysql database and if there are any errors reported it will end php and display the errors.

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