PHP mysql Getting rid of magic quotes problem once and for all

Here is a simple solution that i have found recently. In you project at very start of your code may be in your conf file some where:

This should solve all your magic quotes problems inshAllah.

If you post data has some variables like name[], phone[], etc. i.e. if you $_REQUEST is multidimensional use the following function:

 

 

Share

php mysql indented subcategory recursive loop

Here is my simple recursive function to create a category subcategory tree of unlimited subcategories.

 

 <select name="parent_cat">
      	<option value="0">Root</option>
      	<?
          function get_all_sub_cats($parent_cat_id, $level_string)
          {
              $return_str='';
              if(!$level_string)
              {
                  $level_string='';
              }
              $db=new DB();
              $db->open();
              $db->query("select * from categories where parent_id='{$parent_cat_id}'");
              $db->rsset();
              if($db->rs)
              {
                  while($db->rs)
                  {
                      $return_str.="<option value=\"{$db->rs['id']}\" style=\"padding-left:10px\">{$level_string}{$db->rs['name']}</option>";
                      $return_str.=get_all_sub_cats($db->rs['id'], $level_string.'+');
                      $db->rsset();
                  }
              }
              else
              {
                  return false;
              }
              return $return_str;
          }
      	    print get_all_sub_cats('0', '');
      	?>
      </select>

This is to fit my needs. You can get the logic and build your own accordingly.

Share

cs-cart help – enable ratings and reviews on all products at once

Use following code with you db info to enable ratings and reviews at once on all products saves a lot of time and energy. Originally this is taken from cs-cart forum but i have done little modification to work perfectly. Tested on version 2.x.

 

<?php

// login to the cscart database
$username=”";
$password=”";
$cscartDB=”";
mysql_connect(‘localhost’, $username, $password);
@mysql_select_db($cscartDB) or die(“Unable to select $cscartDB database”);

// get all the active product_id’s from the cscart_products table
//$query = “SELECT product_id FROM cscart_products WHERE status=’A'”;

$query = “SELECT product_id FROM cscart_products”;
$productsResult = mysql_query($query);
$numRows = mysql_numrows($productsResult);
echo “Processing $numRows product id’s…\n”;

while ($row = mysql_fetch_assoc($productsResult)) {
$cscart_product_id = $row['product_id'];

// see if there is a row already for this cscart_product_id
$query=”select object_id from cscart_discussion where object_id=$cscart_product_id AND object_type = ‘P’”;
$result=mysql_query($query);

// if not, add a row to cscart_discussion
if (mysql_num_rows($result) == 0) {
echo “Inserting record into cscart_discussion for $cscart_product_id\n”;
$query=”INSERT INTO cscart_discussion (object_id, object_type, type) VALUES ($cscart_product_id, ‘P’, ‘B’)”;
$result=mysql_query($query);

if (!$result)
echo “Query failed: ($query): ” . mysql_error(). “\n”;
}

//update already existing products statuses

$query=”update cscart_discussion  set type=’B’ where object_type=’P'”;
$result=mysql_query($query);

 

if (!$result)
echo “Query failed: ($query): ” . mysql_error(). “\n”;
}
?>

Share

25 BEST SSH COMMANDS / TRICKS

[ad]

OpenSSH is a FREE version of the SSH connectivity tools that technical users of the Internet rely on. Users of telnet, rlogin, and ftp may not realize that their password is transmitted across the Internet unencrypted, but it is. OpenSSH encrypts all traffic (including passwords) to effectively eliminate eavesdropping, connection hijacking, and other attacks. Additionally, OpenSSH provides secure tunneling capabilities and several authentication methods, and supports all SSH protocol versions.

SSH is an awesome powerful tool, there are unlimited possibility when it comes to SSH.

1) COPY SSH KEYS TO USER@HOST TO ENABLE PASSWORD-LESS SSH LOGINS.

ssh-copy-id user@host

To generate the keys use the command ssh-keygen

2) START A TUNNEL FROM SOME MACHINE’S PORT 80 TO YOUR LOCAL POST 2001

ssh -N -L2001:localhost:80 somemachine

Now you can acces the website by going to http://localhost:2001/

3) OUTPUT YOUR MICROPHONE TO A REMOTE COMPUTER’S SPEAKER

dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp

This will output the sound from your microphone port to the ssh target computer’s speaker port. The sound quality is very bad, so you will hear a lot of hissing.

4) COMPARE A REMOTE FILE WITH A LOCAL FILE

ssh user@host cat /path/to/remotefile | diff /path/to/localfile -

Useful for checking if there are differences between local and remote files.

5) MOUNT FOLDER/FILESYSTEM THROUGH SSH

sshfs name@server:/path/to/folder /path/to/mount/point

Install SSHFS from http://fuse.sourceforge.net/sshfs.html
Will allow you to mount a folder security over a network.

6) SSH CONNECTION THROUGH HOST IN THE MIDDLE

ssh -t reachable_host ssh unreachable_host

Unreachable_host is unavailable from local network, but it’s available from reachable_host’s network. This command creates a connection to unreachable_host through “hidden” connection to reachable_host.

7) COPY FROM HOST1 TO HOST2, THROUGH YOUR HOST

ssh root@host1 “cd /somedir/tocopy/ && tar -cf – .” | ssh root@host2 “cd /samedir/tocopyto/ && tar -xf -”

Good if only you have access to host1 and host2, but they have no access to your host (so ncat won’t work) and they have no direct access to each other.

8 ) RUN ANY GUI PROGRAM REMOTELY

ssh -fX <user>@<host> <program>

The SSH server configuration requires:

X11Forwarding yes # this is default in Debian

And it’s convenient too:

Compression delayed

9) CREATE A PERSISTENT CONNECTION TO A MACHINE

ssh -MNf <user>@<host>

Create a persistent SSH connection to the host in the background. Combine this with settings in your ~/.ssh/config:
Host host
ControlPath ~/.ssh/master-%r@%h:%p
ControlMaster no
All the SSH connections to the machine will then go through the persisten SSH socket. This is very useful if you are using SSH to synchronize files (using rsync/sftp/cvs/svn) on a regular basis because it won’t create a new socket each time to open an ssh connection.

10) ATTACH SCREEN OVER SSH

ssh -t remote_host screen -r

Directly attach a remote screen session (saves a useless parent bash process)

11) PORT KNOCKING!

knock <host> 3000 4000 5000 && ssh -p <port> user@host && knock <host> 5000 4000 3000

Knock on ports to open a port to a service (ssh for example) and knock again to close the port. You have to install knockd.
See example config file below.
[options]
logfile = /var/log/knockd.log
[openSSH]
sequence = 3000,4000,5000
seq_timeout = 5
command = /sbin/iptables -A INPUT -i eth0 -s %IP% -p tcp –dport 22 -j ACCEPT
tcpflags = syn
[closeSSH]
sequence = 5000,4000,3000
seq_timeout = 5
command = /sbin/iptables -D INPUT -i eth0 -s %IP% -p tcp –dport 22 -j ACCEPT
tcpflags = syn

12) REMOVE A LINE IN A TEXT FILE. USEFUL TO FIX

ssh-keygen -R <the_offending_host>

In this case it’s better do to use the dedicated tool

13) RUN COMPLEX REMOTE SHELL CMDS OVER SSH, WITHOUT ESCAPING QUOTES

ssh host -l user $(<cmd.txt)

Much simpler method. More portable version: ssh host -l user “`cat cmd.txt`”

14) COPY A MYSQL DATABASE TO A NEW SERVER VIA SSH WITH ONE COMMAND

mysqldump –add-drop-table –extended-insert –force –log-error=error.log -uUSER -pPASS OLD_DB_NAME | ssh -C user@newhost “mysql -uUSER -pPASS NEW_DB_NAME”

Dumps a MySQL database over a compressed SSH tunnel and uses it as input to mysql – i think that is the fastest and best way to migrate a DB to a new server!

15) REMOVE A LINE IN A TEXT FILE. USEFUL TO FIX “SSH HOST KEY CHANGE” WARNINGS

sed -i 8d ~/.ssh/known_hosts

16) COPY YOUR SSH PUBLIC KEY TO A SERVER FROM A MACHINE THAT DOESN’T HAVE SSH-COPY-ID

cat ~/.ssh/id_rsa.pub | ssh user@machine “mkdir ~/.ssh; cat >> ~/.ssh/authorized_keys”

If you use Mac OS X or some other *nix variant that doesn’t come with ssh-copy-id, this one-liner will allow you to add your public key to a remote machine so you can subsequently ssh to that machine without a password.

17) LIVE SSH NETWORK THROUGHPUT TEST

yes | pv | ssh $host “cat > /dev/null”

connects to host via ssh and displays the live transfer speed, directing all transferred data to /dev/null
needs pv installed
Debian: ‘apt-get install pv’
Fedora: ‘yum install pv’ (may need the ‘extras’ repository enabled)

18) HOW TO ESTABLISH A REMOTE GNU SCREEN SESSION THAT YOU CAN RE-CONNECT TO

ssh -t user@some.domain.com /usr/bin/screen -xRR

Long before tabbed terminals existed, people have been using Gnu screen to open many shells in a single text terminal. Combined with ssh, it gives you the ability to have many open shells with a single remote connection using the above options. If you detach with “Ctrl-a d” or if the ssh session is accidentally terminated, all processes running in your remote shells remain undisturbed, ready for you to reconnect. Other useful screen commands are “Ctrl-a c” (open new shell) and “Ctrl-a a” (alternate between shells). Read this quick reference for more screen commands: http://aperiodic.net/screen/quick_reference

19) RESUME SCP OF A BIG FILE

rsync –partial –progress –rsh=ssh $file_source $user@$host:$destination_file

It can resume a failed secure copy ( usefull when you transfer big files like db dumps through vpn ) using rsync.
It requires rsync installed in both hosts.
rsync –partial –progress –rsh=ssh $file_source $user@$host:$destination_file local -> remote
or
rsync –partial –progress –rsh=ssh $user@$host:$remote_file $destination_file remote -> local

20) ANALYZE TRAFFIC REMOTELY OVER SSH W/ WIRESHARK

ssh root@server.com ‘tshark -f “port !22″ -w -’ | wireshark -k -i -

This captures traffic on a remote machine with tshark, sends the raw pcap data over the ssh link, and displays it in wireshark. Hitting ctrl+C will stop the capture and unfortunately close your wireshark window. This can be worked-around by passing -c # to tshark to only capture a certain # of packets, or redirecting the data through a named pipe rather than piping directly from ssh to wireshark. I recommend filtering as much as you can in the tshark command to conserve bandwidth. tshark can be replaced with tcpdump thusly:
ssh root@example.com tcpdump -w – ‘port !22′ | wireshark -k -i -

21) HAVE AN SSH SESSION OPEN FOREVER

autossh -M50000 -t server.example.com ‘screen -raAd mysession’

Open a ssh session opened forever, great on laptops losing Internet connectivity when switching WIFI spots.

22) HARDER, FASTER, STRONGER SSH CLIENTS

ssh -4 -C -c blowfish-cbc

We force IPv4, compress the stream, specify the cypher stream to be Blowfish. I suppose you could use aes256-ctr as well for cypher spec. I’m of course leaving out things like master control sessions and such as that may not be available on your shell although that would speed things up as well.

23) THROTTLE BANDWIDTH WITH CSTREAM

tar -cj /backup | cstream -t 777k | ssh host ‘tar -xj -C /backup’

this bzips a folder and transfers it over the network to “host” at 777k bit/s.
cstream can do a lot more, have a look http://www.cons.org/cracauer/cstream.html#usage
for example:
echo w00t, i’m 733+ | cstream -b1 -t2

24) TRANSFER SSH PUBLIC KEY TO ANOTHER MACHINE IN ONE STEP

ssh-keygen; ssh-copy-id user@host; ssh user@host

This command sequence allows simple setup of (gasp!) password-less SSH logins. Be careful, as if you already have an SSH keypair in your ~/.ssh directory on the local machine, there is a possibility ssh-keygen may overwrite them. ssh-copy-id copies the public key to the remote host and appends it to the remote account’s ~/.ssh/authorized_keys file. When trying ssh, if you used no passphrase for your key, the remote shell appears soon after invoking ssh user@host.

25) COPY STDIN TO YOUR X11 BUFFER

ssh user@host cat /path/to/some/file | xclip

Have you ever had to scp a file to your work machine in order to copy its contents to a mail? xclip can help you with that. It copies its stdin to the X11 buffer, so all you have to do is middle-click to paste the content of that looong file :)

[ad]

Share

PHP MYSQL UTF-8

[ad]

Connection:

SET NAMES 'utf8';

PHP mysql connection (not totally confirmed, but see tests below) defaults to a latin1 connection, so, your first query after connection should be:

mysql_query("SET NAMES 'utf8'");

In php versions 5.2 and later, use

mysql_set_charset('utf8',$conn);

[ad]

Share

10+ extremely useful PHP classes

[ad]

PHP PSD Reader

A few weeks ago, I wrote an article about this PHP which allow you to display any Adobe PSD file on screen. Very usefull to create preview of PSDs designed for clients, for example.
Download

Browser detect

One of the most common (and boring) problem for front-end developers is definitely cross-browser compatibility. This PHP class will detect almost all browsers and simplify your cross-browser work.
Download

Akismet

Remember those days without spam? If your website gets spammed in any ways, Akismet can probably help you. When a new comment, trackback, or pingback comes to your site it is submitted to the Akismet web service which runs hundreds of tests on the comment and returns a thumbs up or thumbs down.
Download

ADOdb

The large majority of websites and web apps are using databases to store all kinds of data. ADOdb is a database abstraction library for PHP, supporting MySQL, PostgreSQL, Interbase, Firebird, Oracle, MS SQL and more. ADOdb is quite easy to learn and have lots of nice features as such as extensive portability support, speed and BSD licencing.
Download

HTML Purifier

As it name tells, HTML Purifier is a PHP class created to help you writing a better code. HTML Purifier can remove malicious code and make sure your code is standard-compliant. A great tool for all developers.
Download

Google charts API

Charts are very useful and highly asked by clients, but they can be a lot of work. I remember some years ago when a friend of mine had to create charts using Photoshop every week for one of his clients. Well, this time is gone for good.
With the Google charts API, a simple chart can be created and displayed on screen using as little as 4 lines of code.
Download

pChart

pChart is another chart class, and it is as good as Google charts API. Data can be easily retrieved from SQL queries, CSV files, or manually provided.
Download

PHP Excel

Excel documents are highly popular in the corporate world. Considering that fact, there’s a strong chance that one of your clients asks for you to create excel files in PHP someday.
Happilly, the PHP Excel engine allow you to easily create and manipulate lots of different files, as such as Excel 2007, Open XML, or PDF.
Download

Country from IP

Some websites are able to detect your location and automatically display information related with your language. How do they do that? Quite simple, they use your IP adress to find your location. The Country from IP class is easy to use and will allow you to get the country a specific IP is from.
Download

Cache Manager

If you’re working on a high traffic site, there’s not doubt you’ll need to cache files in order to improve performance. This will be very easy an simple to do, using this very handy class. A defifinitive must-have, in my opinion.
Download

WPGet

As I know many of you have a WordPress blog, I just can’t finish this article without a great tool for our favorite blogging engine.
WPGet is a PHP class which allow you to easily get infos from a WordPress 2.X database. In other words, it allows you to get posts, comments, etc from a WordPress blog, on a non-WordPress site. Great, isn’t it?
Download

[ad]

Share

Practical Date/Time examples with PHP and MySQL

In this article Mauricio shows us some examples of how to use the date/time features with MySQL and PHP including the UNIX timestamp and the PHP date_diff() function.Some time ago working with dates and times was a pain for me. In several of my projects I had to calculate a person’s age based on their birth date. I created a members area that allowed the administrators to set the maximum amount of time users can have a password before they must change it and remind each one how many days left before the change. I also had to create time-bomb accounts that worked for several days after its creation and then became useless.

Digging into the PHP and MySQL documentation I found and then worked with several functions that made my life easier. Now I want to share some code tips that allow better manipulation of the time and date in your projects and everyday needs.

The UNIX timestamp is the number of seconds elapsed since January 1, 1970 at 00:00:00. I use the timestamp mostly, it’s better for doing arithmetical operations as it is just a number.

For me it’s easier to add or subtract thousands of seconds than doing the same with a date string. I’m going to use both timestamps and date strings although prefer the first.

Printing the current timestamp is as simple as . This function alone doesn’t do much, the result is a number with more than nine figures, almost unreadable for the average user including me. I’m not going to enter into details about this topic as it has been covered in previous articles. Let’s go to the examples…

Calculating days, hours and seconds

PHP lacks date operation functions, but it provides the tools to do what we want to do. Say we want to know how many days, hours and seconds exist between two given dates, following is the function:


// The parameters of this function are the dates to be compared.
// The first should be prior to the second. The dates are in
// the form of: 1978-04-26 02:00:00.
// They also can come from a web form using the global $_POST['start']
// and $_POST['end'] variables.
function date_diff($str_start, $str_end)
{

$str_start = strtotime($str_start); // The start date becomes a timestamp
$str_end = strtotime($str_end); // The end date becomes a timestamp

$nseconds = $str_end – $str_start; // Number of seconds between the two dates
$ndays = round($nseconds / 86400); // One day has 86400 seconds
$nseconds = $nseconds % 86400; // The remainder from the operation
$nhours = round($nseconds / 3600); // One hour has 3600 seconds
$nseconds = $nseconds % 3600;
$nminutes = round($nseconds / 60); // One minute has 60 seconds, duh!
$nseconds = $nseconds % 60;

echo $ndays.” days, “.$nhours.” hours, “.$nminutes.” minutes, “.$nseconds.”
echo “seconds
“;

}

// Test the function with several values
date_diff(“1978-04-26″, “2003-01-01″);
date_diff(“1984-10-24 15:32:25″, “2003-01-01″);
date_diff(“2001-10-28 17:32:25″, “2003-01-01 12:00:18″);

?>

We could implement more options such as date validation etc., but I will add that in future articles.
This function does not need a lot of explanation, just multiplication and division. Now, let’s seeanother example.

Using the date_diff() function that we’ve just created it’s very easy to calculate your exact age by how many years, days, hours, minutes and seconds since you were born:


// Calculating my exact age
$str_birthday = “1978-04-26″; // My Birth Day
$str_today = date(“Y-m-d H:i:s”); // The exact time
date_diff($str_birthday, $str_today);

?>

As you see I’m using the same function but changing the parameters a little. First $str_birthday is a fixed string, in this example my birthday.

You can, for example, ask the user through a form and then call the function like this:

The trick here is the date() function. With its given parameters prints the exact date of today in the format YYYY-MM-DD hh:mm:ss.

The code returns:
9024 days, 17 hours, 29 minutes, 57 seconds

How many days until…?

Again, using the same function that we created at the beginning and changing the parameters appropriately we can calculate how many days until a given date. There is a problem though; the UNIX timestamp only works for dates between January 1st, 1970 and December 31st, 2037. Dates outside that range will give an unpredictable result.

Now, hoping that we’ll come up with a solution for this in the next thirty years let’s do the math:


$str_future_date = “2028-04-26″; // I’ll be fifty this day!
date_diff(date(“Y-m-d H:i:s”), $str_future_date);

?>

At this point you should be familiar with the function, just tweaking the parametersa little. In this case the first parameter is the exact date of today and the second is the future date that we want to know how many days until.{mospagebreak title=Dates with MySQL&toc=1} MySQL has several great date and time functions that are very useful when you are working with dates. These functions are worth another article which I’ll be writing after this one.

Meanwhile I’ll show the ones that I think are the more useful and interesting.

Also, forcing MySQL to do the date operations by itself saves a lot of time, a lot of code and increases the performance of your application.

Personally, every time that I need to do some date calculations involving dates contained in a database I take a look at MySQL documentation to see which function can help me and let it do the job for me.

In all the following examples the dates can be taken from the database itself, your code or user input.

Anyway, if you are working with databases it’s obvious that at least one of the dates came from there.

Take care when using these functions as most of them work only on MySQL 3.22 and later. If you have doubts refer to the documentation.

The UNIX timestamp revisited

Programmers seem to like the UNIX timestamp very much because you can see it anywhere you go. In the case of MySQL you can use it like this:

SELECT UNIX_TIMESTAMP();

This will return the current timestamp.

mysql> SELECT UNIX_TIMESTAMP(’1978-04-26 02:12:59′);
+—————————————+
| UNIX_TIMESTAMP(’1978-04-26 02:12:59′) |
+—————————————+
| 262422779 |
+—————————————+

mysql> SELECT UNIX_TIMESTAMP(’1978-04-26′);
+——————————+
| UNIX_TIMESTAMP(’1978-04-26′) |
+——————————+
| 262414800 |
+——————————+

This will print the timestamp of the given date.

Be careful when creating the structure and definitions for this kind of table. MySQL returns the UNIX timestamp as an unsigned integer, so keep this in mind when creating your database.

Now, imagine you have a database with a column that contains a UNIX timestamp, you can also convert it to a ‘human-readable’ date using MySQL like this:

mysql> SELECT FROM_UNIXTIME(’262422779′);
+—————————-+
| FROM_UNIXTIME(’262422779′) |
+—————————-+
| 1978-04-26 02:12:59 |
+—————————-+

With this value it’s just a matter of two lines of code and to use the function date_diff() that I created before:

// Working with mysql
$ndbconn = mysql_connect(“localhost”, “user”, “password”);
mysql_select_db(“mydb”);

// The query
$squery = “SELECT FROM_UNIXTIME(’262422779′), NOW()”;
$nresult = mysql_query($squery);
$s_given_date = mysql_result($nresult, 0, 0);
$s_curr_date = mysql_result($nresult, 0, 1);

// Free the result
mysql_free_result($nresult);

// Disconnected
mysql_close($ndbconn);

// The date difference
date_diff($s_given_date, $s_curr_date);

In this example I used MySQL to obtain the dates and then I calculated the time elapsed between both using my – now ‘famous’ – date_diff() function.

The UNIX timestamp can be any you have in your database, I selected the timestamp 262422779 that is exactly my ‘birth time’ and stored it in the $s_given_date variable.

Then I selected the current time with the NOW() function and stored it in the $s_curr_date variable. The rest is old news, I already explained how the function works.

Suppose that you have a members only area, each user has a password but you want the user to change his or her password every two weeks.

The first thing you have to do is add a new column to your users table; this column will store the timestamp of the exact date when the user changed his or her password.

Remember, again, that the timestamp is an unsigned integer, so keep this in mind when creating the table.

The code for this approach should look like this:


$ndbconn = mysql_connect(“localhost”, “user”, “password”);
mysql_select_db(“mysql”);

$n_start_date = 1062521254; // Timestamp for 2003-09-02 11:47:34 taken from your DB

// The query adds fourteen days to the given date
$squery = “SELECT DATE_ADD(FROM_UNIXTIME($n_start_date), INTERVAL 14 DAY)”;
$nresult = mysql_query($squery);
$s_new_date = mysql_result($nresult, 0, 0);

// Free the result
mysql_free_result($nresult);

// Disconnected
mysql_close($ndbconn);
echo “Your password will expire on $s_new_date”;

?>

The main function here is DATE_ADD(), this MySQL function perfectly adds any number of seconds, minutes, hours, days or years to a specific date.

In this example we used it to calculate the exact time fourteen days after the selected date. You can use this function with no risk, it even takes care of leap years.
For example:

mysql> SELECT DATE_ADD(’2004-02-28 23:50:00′, INTERVAL 10 MINUTE); #2004 is a leap year
+—————————————————–+
| DATE_ADD(’2004-02-28 23:50:00′, INTERVAL 10 MINUTE) |
+—————————————————–+
| 2004-02-29 00:00:00 |
+—————————————————–+

Subtraction is done with the DATE_SUB() function in the same way:

mysql> SELECT DATE_SUB(’2004-03-01′, INTERVAL 1 DAY);
+—————————————-+
| DATE_SUB(’2004-03-01′, INTERVAL 1 DAY) |
+—————————————-+
| 2004-02-29 |
+—————————————-+

And don’t worry about December 31st and January 1st transition:

mysql> SELECT DATE_SUB(’2004-01-01′, INTERVAL 1 DAY);
+—————————————-+
| DATE_SUB(’2004-01-01′, INTERVAL 1 DAY) |
+—————————————-+
| 2003-12-31 |
+—————————————-+

My conclusion is there really is no conclusion, date and time are extremely important in real-world applications, for example, calculating the age of a person or calculating how many days left for a loan to expire or a bill to be due.

This is a huge topic that I’ve always been interested in. I said there’s no conclusion because I’ll be posting more articles about this topic with more robust and useful applications. Thanks for your time, I hope you enjoyed it.

Share

Tuning / Optimizing my.cnf file for MySQL

This one really helped me.

Had to do some fine tuning of MySQL 4.1.9 and here is what my.cnf file looks like for a 2GHz machine with 1GB of memory.

[mysqld]
socket=/path/to/mysql.sock
datadir=/var/lib/mysql
skip-locking
skip-innodb
# MySQL 4.x has query caching available.
# Enable it for vast improvement and it may be all you need to tweak.
query_cache_type=1
query_cache_limit=1M
query_cache_size=32M
# max_connections=500
# Reduced to 200 as memory will not be enough for 500 connections.
# memory=key_buffer+(sort_buffer_size+read_buffer_size)*max_connections
# which is now: 64 + (1 + 1) * 200 = 464 MB
# max_connections = approx. MaxClients setting in httpd.conf file
# Default set to 100.
#max_connections=200
#interactive_timeout=180
interactive_timeout=100
#wait_timeout=180
#wait_timeout=100
# Reduced wait_timeout to prevent idle clients holding connections.
#wait_timeout=30
wait_timeout=15
connect_timeout=10
# max_connect_errors is set to 10 by default
#max_connect_errors=10
#table_cache=256
#table_cache=1024
# Checked opened tables and adjusted accordingly after running for a while.
table_cache=512
#tmp_table_size=32M by default
#thread_cache=128
# Reduced it to 32 to prevent memory hogging. Also, see notes below.
thread_cache=32
# key_buffer=258M
# Reduced it by checking current size of *.MYI files, see notes below.
key_buffer=128M
# Commented out the buffer sizes and keeping the default.
# sort_buffer_size=2M by default.
#sort_buffer_size=1M
# read_buffer_size=128K by default.
#read_buffer_size=1M
# 1Mb of read_rnd_buffer_size for 1GB RAM -- see notes below.
# read_rnd_buffer_size=256K by default.
#read_rnd_buffer_size=1M
# myisam_sort_buffer_size used for ALTER, OPTIMIZE, REPAIR TABLE commands.
# myisam_sort_buffer_size=8M by default.
#myisam_sort_buffer_size=64M
# thread_concurrency = 2 * (no. of CPU)
thread_concurrency=2
# log slow queries is a must. Many queries that take more than 2 seconds.
# If so, then your tables need enhancement.
log_slow_queries=/var/log/mysqld.slow.log
long_query_time=2
[mysql.server]
user=mysql
basedir=/var/lib
[safe_mysqld]
err-log=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
open_files_limit=8192
[mysqldump]
quick
max_allowed_packet=16M
[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates
[isamchk]
key_buffer=64M
sort_buffer=64M
read_buffer=16M
write_buffer=16M
[myisamchk]
key_buffer=64M
sort_buffer=64M
read_buffer=16M
write_buffer=16M
[mysqlhotcopy]
interactive-timeout
[client]
socket=/path/to/mysql.sock

Below are notes on some of the important variables, I took down while tuning the config file.

  1. query_cache_size:
    • MySQL 4 provides one feature that can prove very handy – a query cache. In a situation where the database has to repeatedly run the same queries on the same data set, returning the same results each time, MySQL can cache the result set, avoiding the overhead of running through the data over and over and is extremely helpful on busy servers.
  2. key_buffer_size:
    • The value of key_buffer_size is the size of the buffer used with indexes. The larger the buffer, the faster the SQL command will finish and a result will be returned. The rule-of-thumb is to set the key_buffer_size to at least a quarter, but no more than half, of the total amount of memory on the server. Ideally, it will be large enough to contain all the indexes (the total size of all .MYI files on the server).
    • A simple way to check the actual performance of the buffer is to examine four additional variables: key_read_requests, key_reads, key_write_requests, and key_writes.
    • If you divide the value of key_read by the value of key_reads_requests, the result should be less than 0.01. Also, if you divide the value of key_write by the value of key_writes_requests, the result should be less than 1.
  3. table_cache:
    • The default is 64. Each time MySQL accesses a table, it places it in the cache. If the system accesses many tables, it is faster to have these in the cache. MySQL, being multi-threaded, may be running many queries on the table at one time, and each of these will open a table. Examine the value of open_tables at peak times. If you find it stays at the same value as your table_cache value, and then the number of opened_tables starts rapidly increasing, you should increase the table_cache if you have enough memory.
  4. sort_buffer:
    • The sort_buffer is very useful for speeding up myisamchk operations (which is why it is set much higher for that purpose in the default configuration files), but it can also be useful everyday when performing large numbers of sorts.
  5. read_rnd_buffer_size:
    • The read_rnd_buffer_size is used after a sort, when reading rows in sorted order. If you use many queries with ORDER BY, upping this can improve performance. Remember that, unlike key_buffer_size and table_cache, this buffer is allocated for each thread. This variable was renamed from record_rnd_buffer in MySQL 4.0.3. It defaults to the same size as the read_buffer_size. A rule-of-thumb is to allocate 1KB for each 1MB of memory on the server, for example 1MB on a machine with 1GB memory.
  6. thread_cache:
    • If you have a busy server that’s getting a lot of quick connections, set your thread cache high enough that the Threads_created value in SHOW STATUS stops increasing. This should take some of the load off of the CPU.
  7. tmp_table_size:
    • “Created_tmp_disk_tables” are the number of implicit temporary tables on disk created while executing statements and “created_tmp_tables” are memory-based. Obviously it is bad if you have to go to disk instead of memory all the time.

Share