How optimize all tables using php script

Optimizing tables is very necessary for database. That will improve the your website performance.  Optimize command is helpful to manage database files in right manner. This command will optimize the size of file size of database files.

How optimize all tables using  php script

How optimize all tables using  php script
How optimize all tables using php script

If you want to optimize the all tables of database then use following script.


<!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1"-->php
$dbconnect = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$dbconnect) {
 die('Could not connect: ' . mysql_error());
}
echo 'Connected to database successfully';

mysql_select_db('YOUR_DATABASE',$dbconnect);

dbConnect();
$alltables = mysql_query("SHOW TABLES");

while ($table = mysql_fetch_assoc($alltables))
{
 foreach ($table as $db => $tablename)
 {
 mysql_query("OPTIMIZE TABLE '".$tablename."'")
 or die(mysql_error());
 }
}
echo 'All tables optimized successfully';

mysql_close($dbconnect);
?>

The MySQL Optimize Table command will effectively de-fragment a mysql table and is very useful for tables which are frequently updated and/or deleted.

mysql sleep processes issue solved

I faced the sleep query issue sometimes.  Many times that kills the server. When ever you are using dedicated virtual hosting server that time you need to me very careful how you are setting up the apache and mysql. we solved mysql sleep processes issue

mysql sleep processes issue solved

mysql sleep processes issue solved
mysql sleep processes issue solved

I found some major reasons for mysql sleep processes. Here I am giving some reasons:

[viral-lock message=”Reasons and Solution is Hidden! It’s Visible for Users who Liked/Shared This article on Facebook or Twitter or Google+. Like or Tweet this article to reveal the content.”]

1. apache requests increase
2. mysql queries increase
3. mysql slow queries increase
4. apache connections start to wait on slow mysql queries
5. apache connections take longer to close
6. more apache connections are opened
7. with each apache request a new sleeping mysql connection is made
8. mysql & apache reach max_connections
9. server slows to a crawl

[/viral-lock]

Using linux top command you can check the load average and which process is taking so much memory of your server. If you saw mysqld is taking much memory of server then you should check using following mysql commands:

> show full processlist;

using this command you can check the mysql processes. Which sql queries being fired on mysql server. If you found so much sleep processes then you should check your mysql variables and settings. If so much mysql queries being fired on specific table then you should change the table storage engine type.

Using following command you can change the storage engine type.
> ALTER TABLE tablename ENGINE = MYISAM;

MYISAM storage engine type is faster then inodb. you can create the mediator tables also for big size table to handing a load of table.

Then major change for solving the issue of sleep processes is, you should change the wait_timeout variable. Default value is 2800 seconds.

mysql> show variables;

you can change the setting using following  mysql command. Best value is 60 second need to be set for wait timeout.
mysql> show variables like ‘wait_timeout’;

mysql> set global wait_timeout=60;

mysql>show variables like ‘wait_timeout’;

After doing above changes you can check the mysql processlist. If you are still facing issues with mysql then please write to me.

How to create mysql logs for specific queries

As a developers need to check the mysql logs. Many times for any request how many mysql queries are running or executed we need to know.

How to create mysql logs for specific queries.

 

How to create mysql logs for specific queries
How to create mysql logs for specific queries

In this tutorial I will show you how to created mysql log file for checking the SELECT, UPDATE, DELETE or any types of mysql queries.

If you are using the linux then use the my.cnf file which will be located in etc folder. If you are using the windows then use the my.ini file. That file you will find in following location in case of wamp server.

c:\wamp\bin\mysql\mysql5.0.45\my.ini

I am using the Linux so here I am giving that example.  use following command.

[root@siwank-pc mysql]# mkdir /var/log/mysql
[root@siwank-pc mysql]# chown mysql:mysql /var/log/mysql

[root@siwank-pc mysql]# vim /etc/my.cnf

[mysqld]
log = /var/log/mysql/mysqld.log //This log file will give you the full mysql access log

log-error=/var/log/mysql/mysqld-error.log // this log file will give you the error log of mysql

log-slow-queries=/var/log/mysql/log-slow-queries.log // this log file will give you the slow queries log

If you need the more information about mysql logs then write to me.

How to use mongodb with php

If you want to use the mongodb with php then you need to install pecl libraries. Mongo extension is not bundled with PHP.

The MongoDB server is built to already work with your current web server. The problem is that you’ll need to install drivers for your preferred backend language – PHP, Ruby, Node.js, Perl, whatever.

How to use mongodb with php

How to use mongodb with php
How to use mongodb with php

For installing the Mongo use following URL:
If you dont have pecl installed on your linux machine then use following command.
# yum install php-pecl*
then use following command
# pecl install mongo
Then open the php.ini file. if you are using the linux then use following command.
# vim /etc/php.ini

## Add following lines, end of php.ini file ##
# MongoDB Driver
extension=mongo.so

Restart the apache webserver using following command
# /etc/init.d/httpd restart
If Mongodb server is running then use can test your mongodb database using following code:
Create the mongotest.php file

<!--?php
// connect
$m = new Mongo();
// select a database
$db = $m--->wordpress;
$collection = $db->wordpressapi;
// add an element
$obj = array( "title" => "Sony this Good.\n", "author" => "Wordpressapi.com" );
$collection->insert($obj);
// add another element, with a different "shape"
$obj = array( "title" => "Wordpressapi.com", "online" => true );
$collection->insert($obj);
// find everything in the collection
$cursor = $collection->find();
// iterate through the results
foreach ($cursor as $obj) {
echo $obj["title"] . "\n";
echo $obj["author"] . "\n";
}
// disconnect
$m->close();
?>

If you open this file in browser then you can see the following words in browser:
Sony this Good. WordPressapi.com Sony this Good. WordPressapi.com
If you want to use the mongodb with php then you need to install pecl libraries. Mongo extension is not bundled with PHP.
For installing the Mongo use following URL:
If you dont have pecl installed on your linux machine then use following command.# yum install php-pecl*
then use following command# pecl install mongo
Then open the php.ini file. if you are using the linux then use following command.
# vim /etc/php.ini

## Add following lines, end of php.ini file ### MongoDB Driverextension=mongo.so

Restart the apache webserver using following command
# /etc/init.d/httpd restart
If Mongodb server is running then use can test your mongodb database using following code:
Create the mongotest.php file

<!--?php
// connect$m = new Mongo();
// select a database$db = $m--->wordpress;$collection = $db->wordpressapi;
// add an element$obj = array( "title" => "Sony this Good.\n", "author" => "Wordpressapi.com" );$collection->insert($obj);
// add another element, with a different "shape"$obj = array( "title" => "Wordpressapi.com", "online" => true );$collection->insert($obj);
// find everything in the collection$cursor = $collection->find();
// iterate through the resultsforeach ($cursor as $obj) {    echo $obj["title"] . "\n";     echo $obj["author"] . "\n";}
// disconnect$m->close();
?>

If you open this file in browser then you can see the following words in browser:Sony this Good. WordPressapi.com Sony this Good. WordPressapi.com

How to install Mongodb on linux

Mongodb is used for many projects now, it is quite fast. I given full detailed information about How to install Mongodb on linux box. Before installing the Mongodb on linux box you need to install following packages on box.

How to install Mongodb on linux

[root@sonyk-pc Download]# sudo yum -y install git tcsh scons gcc-c++ glibc-devel
[root@sonyk-pc Download]# sudo yum -y install boost-devel pcre-devel js-devel readline-devel
[root@sonyk-pc Download]# sudo yum -y install boost-devel-static readline-static ncurses-static

For 32bit user use following command

[root@sonyk-pc Download]# wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.6.2.tgz

For 64bit use following command

[root@sonyk-pc Download]# wget http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-1.6.2.tgz
[root@sonyk-pc Download]# tar xzf mongodb-linux-i686-1.6.2.tgz
[root@sonyk-pc Download]#  cd mongodb-linux-i686-1.6.2

Mongo stores database in data/db folder. so we need to create those folder using following command.

[root@sonyk-pc mongodb-linux-i686-1.6.2]# sudo mkdir -p /data/db/
[root@sonyk-pc mongodb-linux-i686-1.6.2]# sudo chown `id -u` /data/db
[root@sonyk-pc mongodb-linux-i686-1.6.2]# ./bin/mongod
./bin/mongod --help for help and startup options
Thu Sep  9 13:10:55 MongoDB starting : pid=22159 port=27017 dbpath=/data/db/ 32-bit
** NOTE: when using MongoDB 32 bit, you are limited to about 2 gigabytes of data
**       see http://blog.mongodb.org/post/137788967/32-bit-limitations
Thu Sep  9 13:10:55 db version v1.6.2, pdfile version 4.5

If you want to create mongodb service in linux then use following steps:

[root@sonyk-pc Download]# wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.6.2.tgz
[root@sonyk-pc Download]# tar xzf http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.6.2.tgz
[root@sonyk-pc Download]# mv mongodb-linux-i686-1.6.2 /opt/mongodb
[root@sonyk-pc Download]# mkdir -p /srv/db/mongodb
[root@sonyk-pc Download]# touch /srv/db/mongodb.log
[root@sonyk-pc Download]# mkdir /opt/bin/
[root@sonyk-pc Download]# mkdir /opt/config/

create the File: /opt/bin/mongodb-stop
Put following code in that file:

#!/bin/bash
pid=`ps -o pid,command ax | grep mongod | awk '!/awk/ && !/grep/ {print $1}'`;
if [ "${pid}" != "" ]; then
kill -2 ${pid};
fi

create the File: /opt/bin/mongodb-start
Put following code in that file:

#!/bin/sh
/opt/mongodb/bin/mongod --config /opt/config/mongodb \
## --upgrade \ ##runs a database upgrade option if needed \

File: /opt/config/mongodb
Put following code in that file:

# Configuration Options for MongoDB
#
# For More Information, Consider:
# - Configuration Parameters: http://www.mongodb.org/display/DOCS/Command+Line+Parameters
# - File Based Configuration: http://www.mongodb.org/display/DOCS/File+Based+Configuration
dbpath = /srv/db/mongodb
logpath = /srv/db/mongodb.log
logappend = true
bind_ip = 127.0.0.1
port = 27017
fork = true
auth = true
# noauth = true

Do that file as linux executable
chmod +x /opt/bin/mongodb-start
chmod +x /opt/bin/mongodb-stop
We’ve also created a very basic “init script” as a wrapper around the mongodb-start and mongo-stop scripts described above. You will still need to modify and manage the configuration of your MongoDB server in the files above. This script only provides a means for ensuring that MongoDB will start at boot. Issue the following commands:
wget http://library.linode.com/databases/mongodb/reference/init-rpm.sh
mv init-rpm.sh /etc/rc.d/init.d/mongodb
chmod +x /etc/rc.d/init.d/mongodb /etc/init.d/mongodb
chkconfig –add mongodb
chkconfig –level 35 mongodb on
You will also need to create a user and group for mongodb; issue the following command:

useradd -M -r --home-dir /opt/mongodb mongodb

Now issue the following command to ensure that the MongoDB user you just created will have access to all required files in the /srv/db/ hierarchy:
chown mongodb:mongodb -R /srv/db/
To start and stop MongoDB using the init script, issue the appropriate command from the following:
/etc/init.d/mongodb start
/etc/init.d/mongodb stop
For checking the web admin interface of Mongodb – listening on port 28017
Check this URL : http://localhost:28017/
Before installing the Mongodb on linux box you need to install following packages on box.[root@sonyk-pc Download]# sudo yum -y install git tcsh scons gcc-c++ glibc-devel[root@sonyk-pc Download]# sudo yum -y install boost-devel pcre-devel js-devel readline-devel[root@sonyk-pc Download]# sudo yum -y install boost-devel-static readline-static ncurses-static

For 32bit user use following command[root@sonyk-pc Download]# wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.6.2.tgz
For 64bit use following command[root@sonyk-pc Download]# wget http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-1.6.2.tgz

[root@sonyk-pc Download]# tar xzf mongodb-linux-i686-1.6.2.tgz [root@sonyk-pc Download]# cd mongodb-linux-i686-1.6.2
Mongo stores database in data/db folder. so we need to create those folder using following command.
[root@sonyk-pc mongodb-linux-i686-1.6.2]# sudo mkdir -p /data/db/[root@sonyk-pc mongodb-linux-i686-1.6.2]# sudo chown `id -u` /data/db
Using following command you can start the mongo database.
[root@sonyk-pc mongodb-linux-i686-1.6.2]# ./bin/mongod./bin/mongod –help for help and startup optionsThu Sep 9 13:10:55 MongoDB starting : pid=22159 port=27017 dbpath=/data/db/ 32-bit
** NOTE: when using MongoDB 32 bit, you are limited to about 2 gigabytes of data** see http://blog.mongodb.org/post/137788967/32-bit-limitations
Thu Sep 9 13:10:55 db version v1.6.2, pdfile version 4.5

If you want to create mongodb service in linux then use following steps:
[root@sonyk-pc Download]# wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.6.2.tgz [root@sonyk-pc Download]# tar xzf http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.6.2.tgz[root@sonyk-pc Download]# mv mongodb-linux-i686-1.6.2 /opt/mongodb[root@sonyk-pc Download]# mkdir -p /srv/db/mongodb[root@sonyk-pc Download]# touch /srv/db/mongodb.log
[root@sonyk-pc Download]# mkdir /opt/bin/[root@sonyk-pc Download]# mkdir /opt/config/
create the File: /opt/bin/mongodb-stopPut following code in that file;

#!/bin/bash
pid=`ps -o pid,command ax | grep mongod | awk '!/awk/ && !/grep/ {print $1}'`;if [ "${pid}" != "" ]; then    kill -2 ${pid};fi

create the File: /opt/bin/mongodb-startPut following code in that file:

#!/bin/sh
/opt/mongodb/bin/mongod --config /opt/config/mongodb \## --upgrade \ ##runs a database upgrade option if needed \

File: /opt/config/mongodbPut following code in that file:

# Configuration Options for MongoDB## For More Information, Consider:# - Configuration Parameters: http://www.mongodb.org/display/DOCS/Command+Line+Parameters# - File Based Configuration: http://www.mongodb.org/display/DOCS/File+Based+Configuration
dbpath = /srv/db/mongodblogpath = /srv/db/mongodb.loglogappend = true
bind_ip = 127.0.0.1port = 27017fork = true
auth = true# noauth = true

Do that file as linux executatblechmod +x /opt/bin/mongodb-startchmod +x /opt/bin/mongodb-stop

We’ve also created a very basic “init script” as a wrapper around the mongodb-start and mongo-stop scripts described above. You will still need to modify and manage the configuration of your MongoDB server in the files above. This script only provides a means for ensuring that MongoDB will start at boot. Issue the following commands:
wget http://library.linode.com/databases/mongodb/reference/init-rpm.shmv init-rpm.sh /etc/rc.d/init.d/mongodbchmod +x /etc/rc.d/init.d/mongodb /etc/init.d/mongodbchkconfig –add mongodbchkconfig –level 35 mongodb on

You will also need to create a user and group for mongodb; issue the following command:

useradd -M -r --home-dir /opt/mongodb mongodb

Now issue the following command to ensure that the MongoDB user you just created will have access to all required files in the /srv/db/ hierarchy:
chown mongodb:mongodb -R /srv/db/
To start and stop MongoDB using the init script, issue the appropriate command from the following:
/etc/init.d/mongodb start/etc/init.d/mongodb stop

For checking the web admin interface of Mongodb – listening on port 28017Check this URL : http://localhost:28017/

How to install Mongodb on linux
How to install Mongodb on linux

How to install Mysql workbench on Fedora

You can use following commands for installing the Mysql workbench on Linux system. You can use following commands for installing the Mysql workbench on Linux system. you will get answer of how install mysql workbench, is very nice tool for creating the ER diagram on mysql database. I personally like that tool so much.

how install mysql workbench

[root@sonyk-pc sony]# rpm -Uvh remi-release-11.rpm
warning: remi-release-11.rpm: Header V3 DSA signature: NOKEY, key ID 00f97f56
Preparing… ########################################### [100%]
1:remi-release ########################################### [100%]

[root@sonyk-pc sony]# yum –enablerepo=remi install mysql-workbench
Loaded plugins: refresh-packagekit
remi | 3.0 kB 00:00
remi/primary_db | 198 kB 00:01
Setting up Install Process
Resolving Dependencies
–> Running transaction check
—> Package mysql-workbench.i586 0:5.2.26-1.fc11.remi set to be updated
–> Processing Dependency: mysql-connector-c++ >= 1.1.0-0.1.bzr888 for package: mysql-workbench-5.2.26-1.fc11.remi.i586
–> Processing Dependency: python-paramiko for package: mysql-workbench-5.2.26-1.fc11.remi.i586
–> Running transaction check
—> Package mysql-connector-c++.i586 0:1.1.0-0.1.bzr888.fc11.remi set to be updated
—> Package python-paramiko.noarch 0:1.7.5-1.fc11 set to be updated
–> Finished Dependency Resolution

Dependencies Resolved

==================================================================================================================================================================================================================================
Package Arch Version Repository Size
==================================================================================================================================================================================================================================
Installing:
mysql-workbench i586 5.2.26-1.fc11.remi remi 14 M
Installing for dependencies:
mysql-connector-c++ i586 1.1.0-0.1.bzr888.fc11.remi remi 252 k
python-paramiko noarch 1.7.5-1.fc11 updates 982 k

Transaction Summary
==================================================================================================================================================================================================================================
Install 3 Package(s)
Upgrade 0 Package(s)

Total download size: 15 M
Is this ok [y/N]: y
Downloading Packages:
(1/3): mysql-connector-c++-1.1.0-0.1.bzr888.fc11.remi.i586.rpm | 252 kB 00:03
(2/3): mysql-workbench-5.2.26-1.fc11.remi.i586.rpm | 14 MB 02:17
http://fedoramirror.hnsdc.com/updates/11/i386/python-paramiko-1.7.5-1.fc11.noarch.rpm: [Errno 14] HTTP Error 404: Not Found
Trying other mirror.
(3/3): python-paramiko-1.7.5-1.fc11.noarch.rpm | 982 kB 00:09
———————————————————————————————————————————————————————————————————————————-
Total 98 kB/s | 15 MB 02:34
warning: rpmts_HdrFromFdno: Header V3 DSA signature: NOKEY, key ID 00f97f56
remi/gpgkey | 1.3 kB 00:00
Importing GPG key 0x00F97F56 “Remi Collet ” from /etc/pki/rpm-gpg/RPM-GPG-KEY-remi
Is this ok [y/N]: y
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
Installing : python-paramiko-1.7.5-1.fc11.noarch 1/3
Installing : mysql-connector-c++-1.1.0-0.1.bzr888.fc11.remi.i586 2/3
Installing : mysql-workbench-5.2.26-1.fc11.remi.i586 3/3

Installed:
mysql-workbench.i586 0:5.2.26-1.fc11.remi

Dependency Installed:
mysql-connector-c++.i586 0:1.1.0-0.1.bzr888.fc11.remi python-paramiko.noarch 0:1.7.5-1.fc11

Complete!
[root@sonyk-pc sony]#

After installation you will find the mysql workbench under application-> programming  menu

After that you will you will see the following screen.

how install mysql workbench
how install mysql workbench

clicking on new connection you can create the new connections and after that If you want to create the ER diagram then go to database Option and reverse engineering.

How you find this article for “how install mysql workbench”. please write to me.

Another mysql related article which will be helpful to you.

Install Mysql cluster on Fedora box
How to take mysql backup from file system

how to find largest tables on MySQL Server

Using following article You can find the largest tables from Mysql database. Finding largest tables on MySQL instance is no brainier in MySQL 5.0+ thanks to Information Schema but I still wanted to post little query I use for the purpose so I can easily find it later, plus it is quite handy in a way it presents information:

how to find largest tables on MySQL Server

PLAIN TEXT

SQL:

mysql> SELECT concat(table_schema,’.’,table_name),concat(round(table_rows/1000000,2),’M’) rows,concat(round(data_length/(1024*1024*1024),2),’G’) DATA,concat(round(index_length/(1024*1024*1024),2),’G’) idx,concat(round((data_length+index_length)/(1024*1024*1024),2),’G’) total_size,round(index_length/data_length,2) idxfrac FROM information_schema.TABLES ORDER BY data_length+index_length DESC LIMIT 10;
+————————————-+——–+——–+——–+————+———+
| concat(table_schema,’.’,table_name) | rows | DATA | idx | total_size | idxfrac |
+————————————-+——–+——–+——–+————+———+
| art87.link_out87 | 37.25M | 14.83G | 14.17G | 29.00G | 0.96 |
| art87.article87 | 12.67M | 15.83G | 4.79G | 20.62G | 0.30 |
| art116.article116 | 10.49M | 12.52G | 3.65G | 16.18G | 0.29 |
| art84.article84 | 10.10M | 10.11G | 3.59G | 13.70G | 0.35 |
| art104.link_out104 | 23.66M | 6.63G | 6.55G | 13.18G | 0.99 |
| art118.article118 | 7.06M | 10.49G | 2.68G | 13.17G | 0.26 |
| art106.article106 | 9.86M | 10.19G | 2.76G | 12.95G | 0.27 |
| art85.article85 | 6.20M | 9.82G | 2.51G | 12.33G | 0.26 |
| art91.article91 | 8.66M | 9.17G | 2.66G | 11.83G | 0.29 |
| art94.article94 | 5.21M | 10.10G | 1.69G | 11.79G | 0.17 |
+————————————-+——–+——–+——–+————+———+
10 rows IN SET (2 min 29.19 sec)

I do some converting and rounding to see number of rows in millions and data and index size in GB so I can save on counting zeros.
The last column shows how much does the index take compared to the data which is mainly for informational purposes but for MyISAM can also help you to size your key buffer compared to operating system cache.

I also use it to see which tables may be worth to review in terms of indexes. Large index size compared to data size often indicates there is a lot of indexes (so it is well possible there are some duplicates, redundant or simply unused indexes among them) or may be there is long primary key with Innodb tables. Of course it also could be perfectly fine tables but it is worth to look.

Changing the query a bit to look for different sorting order or extra data – such as average row length you can learn quite a lot about your schema this way.

It is also worth to note queries on information_schema can be rather slow if you have a lot of large tables. On this instance it took 2.5 minutes to run for 450 tables.

UPDATE: To make things easier I’ve added INFORMATION_SCHEMA to the query so it works whatever database you have active. It does not work with MySQL before 5.0 still of course

How to take mysql backup from file system

This method or trick is important when your database crash and you are not able connect to database. Still your will be able to take mysql backup from file system. Many times we fail to restore the mysql dump from command line.

How to take mysql backup from file system

If your mysql server crash. Follow my steps to take mysql backup from file system without database connection.

First go to your filesystem.
Here I am using the fedora OS for this example

In linux go to /var/lib/mysql path

In that folder each folder means separate database.

Copy that all folders to your local machine.
again go to your mysql local installation and paste that folder into your mysql folder.

For in each database folder file you will find following types of files in the folder
db.opt
test.frm
test.MYD
test.MYI

just copy and paste in your system

how to create multi level unique id in mysql

Multi level unique is very important feature in mysql. This feature is present all databases. Using composite unique key we can achieve multilevel uniqueness. In article for create multi level unique id in mysql. Using this composite unique key we can achieve multilevel uniqueness.

create multi level unique id in mysql

create multi level unique id in mysql
create multi level unique id in mysql

Here I am going to give you how to create the composite unique key in mysql.

mysql> alter table `user` add unique `DATE_uuid` (`date`, `uuid`)

how to check indexes on table
mysql> show index from user;
+—————-+————+————+————–+————-+———–+————-+———-+——–+——+————+———+
| Table          | Non_unique | Key_name   | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+—————-+————+————+————–+————-+———–+————-+———-+——–+——+————+———+
| user |          0 | PRIMARY    |            1 | user_id         | A         |           0 |     NULL | NULL   |      | BTREE      |         |
| user |          0 | DATE_uuid |            1 | date        | A         |        NULL |     NULL | NULL   |      | BTREE      |         |
| user |          0 | DATE_uuid |            2 | uuid       | A         |           0 |     NULL | NULL   |      | BTREE      |         |
+—————-+————+————+————–+————-+———–+————-+———-+——–+——+————+———+
3 rows in set (0.01 sec)

mysql>

how to work with multidimensional array in php

If you are programmer then you dont need introduction of array. In every language array is the most important part.

how to work with multidimensional array in php

Using array we can achieve so many things and array is useful for so many times when we do programming.
In this article I am going to share some method about PHP array.

What is PHP array?
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Following is syntax
array(key => value)

Creating PHP array:

<?php
$arr = array("str_arr" => "this is string", 25 => true);

echo $arr["str_arr"]; // print this is string
echo $arr[25];&nbsp;&nbsp;&nbsp; // print ture
?>

How to print direct PHP array.

<?php
$arr=array("a"=>"jimi","b"=>"timi","c"=>"limi");
print_r($arr);
?>

How to print PHP array preformated

<?php
$arr=array("a"=>"jimi","b"=>"timi","c"=>"limi");
print_r("<pre>".$arr);
?>

How to create a two-dimensional PHP array

<?php
$arr = array (
 "fruits"&nbsp; => array("a" => "orange", "b" => "banana", "c" => "apple"),
 "numbers" => array(1, 2, 3, 4, 5, 6),
 "holes"&nbsp;&nbsp; => array("first", 5 => "second", "third")
);
print_r("<pre>".$arr);
?>

How to create an array from MySql table

<?
function cre_array($row) {
 foreach($row as $key => $value) {
 global $$key;
 $$key = $value;
 }
}

//User table has first_name field present.

$sql = mysql_query("SELECT * FROM 'users'");
while ($row = mysql_fetch_assoc($sql)) {
 cre_array($row);
 echo $first_name.'<br>'; //instead of $row['first_name']
}

?>

How to count PHP array count

$fruits = array("a" => "orange", "b" => "banana", "c" => "apple");
echo sizeof($fruits);
echo $arrayLength = count($fruits);

PHP and MySql and Array

<?php
$sql = "SELECT key,value FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)) {
$myArray[$row[0]] = $row[1];
}

while(list($key,$value) = each($myArray)) {
echo "$key : $value";
}
?>

Following image will help you to understand two dimensional array.

How to work with PHP array
How to work with PHP array