Postingan Yang Kamu Cari

Sabtu, 27 Maret 2010

http://www.kuliahit.com/
http://www.idfreelance.net/pemrograman/tutorial-operasi-crud-visual-basic-net/
http://blog.re.or.id/free-download-ebook/pdf/membuat_server_wordpress_pada_jaringan_komputer_lokal.htm

Beranda > ArtikelProgrammingVisual basic > Membuat Koneksi DataBase Sql Server 2005 Ke VB .NET 205

Membuat Koneksi DataBase Sql Server 2005 Ke VB .NET 205

Akhirnya kesampaian juga menulis tentang pemrograman. Pada Kesempatan kali ini saya akan memberikan tips bagaimana membuat koneksi database dari sql server 2005 ke visual basic 2005 (VB 2005).
Kenapa VB 2005, karena saat ini saya sedang belajar pemrograman vb 2005 ditambah sudah semakin berumurnya vb 6, membuat saya ingin beralih. Ok langsung kita mulai saja.
Sebelumnya, jika Anda blm punya SQL server 2005 Express disini
dan SQL Server Management Studio Express disini
Buat dahulu database di SQL server dengan menggunakan SQL Server Management Studio Express.
Buka SQL Server Management Studio Express di Start Menu ->All programs -> Microsoft SQL Server 2005 -> SQL Server Management Studio Express.
Setelah itu akan muncul tampilan seperti di bawah ini :
SQL Server Management
Pastikan nama servernya benar, setelah itu pada klik kanan pada database -> New database. Dalam contoh ini saya akan membuat database dengan nama Ihsan
SQL Server Management.jpg (2)
Setelah selesai, buka visual basic 2005. Tambahkan sebuah objek di form, yaitu button. Lalu ganti tulisan button dengan tulisan “Connect to database” dengan cara mengganti properti text pada button.
Setelah itu kita masuk pada tahap coding, double click pada button yang telah ditambahkan tadi.
Masukan code dibawah ini ke dalam form coding tersebut :
Public Class Form1
Inherits System.Windows.Forms.Form
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlconn As New SqlClient.SqlConnection
‘membuat koneksi dengan database
‘RAIN-57C3A9A4CD\SQLEXPRESS adalah nama server di komputer, ini bisa diganti

sqlconn.ConnectionString = “server = RAIN-57C3A9A4CD\SQLEXPRESS;Database = Ihsan;integrated security=true”
Try
sqlconn.Open()
Catch ex As Exception
MessageBox.Show(ex.Message, “Connection Failed”, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
If sqlconn.State = 1 Then
Me.Text = “Koneksi Berhasil”
Me.BackColor = Color.Aqua
End If
End Sub
End Class
Perancangan form
Perancangan form
Koneksi berhasil
Koneksi berhasil

Penjelasan :
1. Inherits System.Windows.Forms.Form : Class Form1 sebagai turunan
(inherits)dari System.Windows.Forms.Form. Ini karena setiap objek
yang kita buat pada vb 2005 terdiri dari class.
2. sqlconn.ConnectionString = “server =
RAIN-57C3A9A4CD\SQLEXPRESS;Database = Ihsan;integrated
security=true” 
: Sintaks ini sebagai pembuat koneksi
database antara vb 2005 dengan sql server 2005, dengan nama
server “RAIN-57C3A9A4CD\SQLEXPRESS” adalah nama komputer
saya, sedangkan nama databasenya adalah Ihsan sesuai dengan
yang tadi telah kita buat. Nama server dan database sebaiknya
diganti sesuai nama server pada laptop atau komputer anda.
3. Perintah try sampai dengan end try adalah sintaks yang berfungsi
untuk mengalihkan jika terjadi error. Jika dalam instruksi dalam Try
terdapat kesalahan maka yang akan dijalankan adalah instruksi
dibawah catch. Dalam contoh di atas apabila, tidak ada kesalahan
pada Try koneksi akan berjalan, sedangkan jika tidak akan keluar
pesan eror.
4. Sedangkan pada percabangan if, jika koneksi berhasil akan merubah background form dan properti text pada form.
http://www.myphptutorials.com/topics/1/membuat-website-dinamis-dengan-php-mysql

PHP Dasar : String, Number & Konstanta

Post By : Ellyx Christian
Post Date : Fri, Feb 12th 2010, 21:00
Category : PHP
Di tutorial PHP Dasar bagian II ini anda akan belajar variabel PHP tipe String, Numbers(Bilangan), Concatenation string, menformat bilangan, cara mendefinisikan Konstanta dan menggunakan konstanta di PHP

Strings

String adalah kumpulan dari karakter, bilangan, sepasi, dan yang lainnya yang berada dalam tanda petik. Di bawah ini semuanya adalah string :
  • '9 Januari 2009 '
  • '1.000.000'
  • "satu juta"
  • 'Belajar PHP'
Untuk membuat variable string adalah seperti di bawah :
$nama='Christian';
$kegiatan='Belajar PHP';
Ketika membuat variabel strings anda bisa menggunakan tanda petik satu atau tanda petik dua, yang penting pembuka dan penutupnya sama. Jika Anda membuat strings dengan pembuka tanda petik satu maka penutupnya juga dengan tanda petik satu. Lalu bagaimana jika di dalam strings terdapat karakter yang sama dengan pembuka dan penutup misalkan, dia mengatakan "saya mengantuk." Jika anda membuat strings seperti dibawah :
$var="dia mengatakan "saya mengantuk."" ; //ini salah;
maka akan terjadi error. Penulisan yang benar adalah :
$var="dia mengatakan \"saya mengatuk\"";
atau boleh juga seperti berikut:
$var='dia mengatakan "saya mengantuk." ';
Untuk menampilkan strings gunakan echo() atau print():
echo $var;
print $tanggal;
untuk menampilkan strings dengan kontek lain, gunakan tanda petik dua :
echo "Selamat pagi, $nama";
untuk lebih memperdalam pemahaman anda kerjakanlah contoh berikut.
  1. Buatlah document baru dengan text editor anda, dan ketik script php di bawah ini:








    //membuat variabel string
    $nama="Ellyx Christian";
    $tgl_lahir='29 Februari 2008';
    $komen= "Jangan pernah menyerah \"Terus Semangat\"";


    //menampilkan nilai dari variabel
    echo $nama;
    echo "
    Tanggal lahir : $tgl_lahir";
    echo "
    Komentar :
    ";
    echo $komen;

    ?>
  2. Simpan document tersebut dengan nama strings.php dan tempatkan di direktori web server anda. Kemudian lihat hasilnya dengan menggunakan browser anda.
  3. Jika anda melakukannya dengan benar maka hasilnya akan seperti berikut:
Belajar Variable PHP String

Concatenating Strings

Concatenation Strings adalah operasi penjumlahan pada strings, dimana karakter akan ditambahkan pada bagian akhir strings. Operator concatenation adalah tanda titik (.), contoh:
$jalan='Jalan Padma Timur no.14';
$kota='Kuta';
$alamat=$jalan . $kota;
sekarang nilai dari variabel $alamat adalah 'Jalan Padma Timur no.14Kuta'. Tidak mengambarkan alamat yang jelas bukan (biasanya ' Jalan Padma Timur no.14, Kuta')? oleh karena itu gunakan yang di bawah ini :
$alamat=$jalan . ', ' .$kota;
sekarang nilai dari variabel $alamat adalah 'Jalan Padma Timur no.14, Kuta'. Concatenation bekerja untuk strings dan numbers, code di bawah akan menghasilkan hasil yang sama, yaitu 'Jalan Padma Timur no.14, Kuta 80361' :
$alamat=$jalan . ', ' . $kota .' 80361';
$alamat=$jalan . ', ' . $kota .' '. 80361;
hasilnya akan sama, nilai variabel $alamat adalah ' Jalan Padma Timur no.14, Kuta 80381'.

Numbers

Tipe variabel numbers yang benar pada PHP adalah seperti di bawah:
  • 2008
  • 2.5
  • -1
  • 100000
  • 4.2e2
numbers tidak pernah berada dalam tanda petik, dan tidak juga ada tanda koma untuk menandakan ribuan. Number diasumsikan positip kecuali diawali dengan tanda minus (-). Untuk bilangan desimal digunakn tanda titik sebagai pemisah. Semua operator aritmatika standar dapat digunakan pada numbers.
OPERATORKETERANGAN
+penjumlahan
-pengurangan
/pembagian
*perkalian
%modulus
++increment
- -decrement
Ada banyak sekali function yang bisa digunakan pada number, yang paling umum digunakan adalah round() dan number_format(). round() digunakan untuk membulatkan bilangan.
$n=2.25;
$n=round($n); // hasilnya 2
round() juga dapat digunakan untuk menentukan jumlah digit desimal:
$n=10.34785;
$n=round($n,2); //hasilnya 10.35;
number_format() digunakan untuk menghasilkan format bilangan yang umum digunakan, membagi bilangan dalam ribuan.
$n=10280;
$n=number_format($n); //hasilnya 10,280
juga bisa untuk menentukan jumlah digit desimal:
$n=1250;
$n=number_format($n,2); // hasilnya 1,250.00

Konstanta

Konstanta sama halnya seperti variabel untuk menyimpan sebuah nilai. Perbedaanya adalah nilai konstanta tidak bisa dirubah. Untuk membuat konstanta anda dapat menggunakan fungsi define().
define('NAME', 'value');
nama dari sebuah konstanta disarankan menggunakan huruf kapital, meskipun itu tidak harus. Dan nama dari sebuah konstanta tidak diawali dengan tanda dolar. Konstanta hanya bisa diisi dengan skalar, seperti string dan number. Lalu bagaimana cara mengakses nilai dari sebuah konstanta? Anda tidak bisa mengakses nilai dari sebuah konstanta menggunakan cara berikut:
echo "Hello, USERNAME" ; // tidak akan bekerja.
ini akan menghasilkan Hello , USERNAME bukan nilai dari USERNAME yang akan ditampilkan. Untuk itu anda dapat menggunakan cara berikut:
echo "Hello, ";
echo USERNAME;
atau menggunakan concatenation :
echo "Hello, " . USERNAME;
untuk lebih memperjelas saya akan memberikan sebuah contoh sebagai berikut:
  1. Buatlah document baru dengan text editor anda dan buatlah script PHP berikut :






    //membuat variabel number
    $juml_brg=20;
    $harga=1057;

    //membuat konstanta
    define('DISKON', 0.35); // 50 %
    // MENGHITUNG HASIL
    $total=$juml_brg*$harga;
    $diskon=$total*DISKON;
    $total_harga=$total-diskon;

    //menampilkan hasil
    echo 'Jumlah barang :'.$juml_brg;
    echo "
    Harga per satuan : $harga";
    echo '
    Total : '.number_format($total);
    echo "
    Diskon : $diskon (".(DISKON*100).'%)';
    echo '
    Total Harga :'.number_format($total_harga,2);

    ?>
  2. Simpan document tersebut dengan nama konstanta.php dan tempatkan pada direktori web server anda. Lihat hasilnya melalui browser anda.
  3. Jika anda melakukannya dengan benar maka hasilnya akan seperti berikut ini:
belajar number dan konstanta

Demikian tutorial PHP Dasar : String, Number dan Konstanta, di tutorial ini anda telah belajar cara mendefinisikan string, menggunakan string di PHP, mendefinisi

Post By : Ellyx Christian
Post Date : Thu, Feb 11th 2010, 22:23
Category : PHP
Langkah awal dalam membangun atau mengembangkan website dinamis dengan PHP dan MYSQL adalah mempelajari dasar dasar PHP itu sendiri. Pada tutorial ini anda akan belajar dasar - dasar PHP, mulai dari syntak PHP, variabeloperatorKonstanta dan dasar PHP lainnya.

Sintaks Dasar

Seperti telah  dijelaskan sebelumnya, untuk menambahkan kode PHP ke dalam sebuah halaman, anda mesti menaruhya dalam PHP tag
?>
Segala sesuatu yang diletakkan di dalam PHP tag akan dieksekusi oleh web server sebagai kode PHP, dan text di luar PHP tag akan segera dikirim ke web browser sebagai HTML biasa.

Mengirim Data ke Web Browser

Untuk membuat website dinamis, anda harus tahu bagaimana cara mengirim data ke web browser. PHP menyediakan banyak function untuk melakukan hal tersebut, yang paling banyak digunakan adalah print() dan echo(). Untuk mengirim sebuah text "Nama saya PHP" ke web browser caranya sangat mudah:
echo "Nama saya PHP"; atau echo 'Nama saya PHP';
atau anda dapat menggunakan print():
print "Nama saya PHP"; atau print 'Nama saya PHP';
seperti anda lihat, penggunaan echo dan print untuk mengirim text / data ke browser adalah dengan menempatkan text / data yang akan dikirim dalam tanda petik dua atau tanda petik satu 'dan diakhiri dengan tanda titik kome ;. Lalu bagaimana jika text yang dikirim berisi tanda petik dua atau tanda petik satu misalnya, "Andi said, "How are you?"" atau "Andi's dog";. Ada dua cara yang bisa anda gunakan, yang pertama jika text yang dikirim berisi tanda petik dua anda dapat meletakkanya dalam tanda petik satu seperti :
echo 'Andi said, "How are you?" ';
jika text yang dikirim berisi tanda petik satu anda dapat meletakannya dalam tanda petik dua seperti :
echo "Andi's dog";
cara kedua adalah dengan menggunakan tanda backslash (escape string) seperti berikut:
echo "Andi said, \"How are you?\"";
echo 'Andi\'s dog';

Menulis Komentar

Seperti bahasa pemrograman lainnya, PHP juga bisa disisipi dengan komentar untuk mengingatkan tentang sesuatu. Untuk menulis komentar dalam PHP ada tiga cara, yang pertama adalah menggunakan tanda #
# ini adalah komentar
yang kedua adalah dengan menggunakan 2 buah slash
//ini juga komentar
echo 'helo word'; // say helo word

yang ketiga adalah dengan diapit tanda /* */
/*ini adalah komentar
bentuk ketika */

cara ketiga dapat digunakan untuk menulis komentar lebih dari satu baris. sedangkan cara satu dan dua digunakan untuk menulis komentar dalam satu baris. Komentar tidak akan dieksekusi oleh web server.

Variabel PHP

Variabel adalah tempat untuk menyimpan data sementara. Nilai dari sebuah variabel bisa text, bilangan atau data yang lainnya. PHP memiliki 8 tipe variabel: boolean (true - false), integer, floating point (desimal), string, array, object, resource dan null. Aturan penulisan varibel dalam php adalah sebagai berikut:
  1. Sebuah variabel harus dimulai dengan tanda dolar $ misalnya, $namaVariabel;
  2. Nama variabel dapat berisi kombinasi dari huruf, angka dan underscore misal, $customer_1;
  3. Karakter pertama setelah tanda dolar harus huruf atau underscore, tidak boleh angka.
  4. nama variabel dalam PHP case-sensitive, artinya $namaVariabel berbeda dengan $Namevariabel.
Variabel diisi nilai (di-asign) dengan tanda sama dengan = misal, $name = 'Andi'. Dan variabel dapat ditampilkan tanpa tanda petik seperti :
echo $name;
print $name;

atau dapat ditampilkan dengan tanda petik dua:
echo "Hello, $name";
anda tidak bisa menampilkan varibel dengan tanda pertik satu:
echo 'Helo, $name'; // ini tidak akan bekerja, salah.
untuk lebih jelas dalam penggunaan variabel akan diberikan sebuah contoh. Ikutilah langkah-langkah berikut.
  1. Buat document baru dengan text editor anda, mulai dengan mengetikan kode HTML di bawah :





  2. Buat pembuka tag php dan isi sebuah komentar
  3. buat sebuah varibel dengan script berikut:
    $file=$_SERVER['SCRIPT_FILENAME'];
    $_SERVER sebenarnya adalah sebuah variabel yang berisi informasi tentang server. variabel $_SERVER[‘SCRIPT_FILENAME’] berisi nama dari script yang sedang dijalankan misalnya, C:\xampp\htdocs\variable.php. Script di atas adalah untuk membuat sebuah variabel baru dengan nama $file dan mengisi variabel baru $file dengan nilai dari variabel $_SERVER[‘SCRIPT_FILENAME’].
  4. buat variabel kedua dengan script di bawah:
    $user = $_SERVER[‘HTTP_USER_AGENT’];
    $_SERVER[‘HTTP_USER_AGENT’] berisi nilai web browser dan sistem operasi yang digunakan untuk mengakses script. Script di atas adalah untuk membuat sebuah variabel baru dengan nama $user dan mengisi variabel $user dengan nilai $_SERVER[‘HTTP_USER_AGENT’].
  5. ketik script di bawah untuk menampilkan script yang sedang diakses:
    echo "Anda menjalankan script:
    $file
    " ;
  6. buat script untuk menampilkan informasi bowser yang digunakan:
    echo "Anda menggunkan:
    $user
    " ;
  7. Selesaikan kode PHP dan HTML:
    ?>


    Hasil akhirnya adalah sebagai berikut:








    //variabel pertama
    $file = $_SERVER['SCRIPT_FILENAME'];

    //Variabel kedua
    $user = $_SERVER['HTTP_USER_AGEN'];

    //manmpilkan variabel pertama
    echo "Anda menjalankan script:
    $file
    " ;

    //menampilkan variabel kedua
    echo "Anda menggunkan:
    $user
    " ;
    ?>
  8. Simpan dengan nama variabel.php, tempatkan di direktori web server anda dan test dengan menggunakan browser anda. Jika anda melakukannya dengan benar maka hasilnya akan sebagai berikut:
Penggunaan Variabel

mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both

 Description

array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.

 Parameters

result
The result resource that is being evaluated. This result comes from a call to mysql_query().
result_type
The type of array that is to be fetched. It's a constant and can take the following values:MYSQL_ASSOCMYSQL_NUM, and MYSQL_BOTH.

 Return Values

Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (asmysql_fetch_row() works).
If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use the numeric index of the column or make an alias for the column. For aliased columns, you cannot access the contents with the original column name.

 Examples

Example #1 Query with aliased duplicate field names
SELECT table1.field AS foo, table2.field AS bar FROM table1, table2

Example #2 mysql_fetch_array() with MYSQL_NUM
mysql_connect("localhost""mysql_user""mysql_password") or
    die(
"Could not connect: " mysql_error());mysql_select_db("mydb");
$result mysql_query("SELECT id, name FROM mytable");

while (
$row mysql_fetch_array($resultMYSQL_NUM)) {
    
printf("ID: %s  Name: %s"$row[0], $row[1]); 
}
mysql_free_result($result);?>

Example #3 mysql_fetch_array() with MYSQL_ASSOC
mysql_connect("localhost""mysql_user""mysql_password") or
    die(
"Could not connect: " mysql_error());mysql_select_db("mydb");
$result mysql_query("SELECT id, name FROM mytable");

while (
$row mysql_fetch_array($resultMYSQL_ASSOC)) {
    
printf("ID: %s  Name: %s"$row["id"], $row["name"]);
}
mysql_free_result($result);?>

Example #4 mysql_fetch_array() with MYSQL_BOTH
mysql_connect("localhost""mysql_user""mysql_password") or
    die(
"Could not connect: " mysql_error());mysql_select_db("mydb");
$result mysql_query("SELECT id, name FROM mytable");

while (
$row mysql_fetch_array($resultMYSQL_BOTH)) {
    
printf ("ID: %s  Name: %s"$row[0], $row["name"]);
}
mysql_free_result($result);?>

 Notes

NotePerformance
An important thing to note is that using mysql_fetch_array() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value. 
NoteField names returned by this function are case-sensitive.
NoteThis function sets NULL fields to the PHP NULL value.

 See Also



mysql_fetch_assoc><mysql_escape_string
Last updated: Fri, 26 Mar 2010
 
 add a note add a noteUser Contributed Notes
mysql_fetch_array
Sebastian K
02-Mar-2010 08:56
To put the full result in one array, I wrote this function:


$query
="select * from table_xyz";$result mysql_query($query) or die(mysql_error());$arr_table_result=mysql_fetch_full_result_array($result);

function 
mysql_fetch_full_result_array($result)
{
    
$table_result=array();
    
$r=0;
    while(
$row mysql_fetch_assoc($result)){
        
$arr_row=array();
        
$c=0;
        while (
$c mysql_num_fields($result)) {       
            
$col mysql_fetch_field($result$c);   
            
$arr_row[$col -> name] = $row[$col -> name];           
            
$c++;
        }   
        
$table_result[$r] = $arr_row;
        
$r++;
    }   
    return 
$table_result;
}

echo 
$arr_table_result[2]['id'];
?>
coldfire_hx at yahoo dot co dot in
07-Feb-2010 12:27
Hey this is a simple function where you pass your table name and any number of coloumns you want and it will fetch the coloumns and return as a table.

//function

 
function fetch_records($table_name$fields){
       
                
$conn mysql_connect("localhost""root""");
                
$select_db mysql_select_db("db"$conn);
           
                if(!
$conn){
                    return 
"Not able to connect to dabase....";
                }
               
                
$table "";
                
$cols implode (', '$fields);
                
$sql "select $cols from $table_name";   
                
$run mysql_query($sql);   
                  
                    if(
$run){   
                        if(
mysql_num_rows($run) == 0){
                                return 
"Sorry. No records found in the database";                       
                        }
                        else {
                               
                            while(
$arr mysql_fetch_array($runMYSQL_ASSOC)){
                                    
$table .= "\t\t\n";
                                   
                                    foreach (
$arr as $val_col) {
                                    
$table .= "\t\t\t".''."\n";
                                    }
                                       
                                    
$table .= "\t\t\n";                                       
                            }
                            
$table .= "
'.$val_col.'
"
;
                            return 
$table;
                         }
                       
                        
mysql_free_result($run);       
                  }
                 
                return 
"There was an error while fetching the records. Please contact site administrator.";
 }
//how to call the function

        
$table "product_master";
        
$cols = array("product_name""product_image""product_price");
        echo 
fetch_records($table$cols); ?>
buddy at databoysoftware dot com
03-Aug-2009 05:24
In the note entered by Typer85, concerning the use of mysql_data_seek(), it should be noted that there are two parameters, both of which are required.

If you have already iterated through a result array (for instance, using mysql_fetch_array()), and have a need to start from the top, the proper syntax is:

mysql_data_seek({result set},{record#})

EG:
mysql_data_seek($result,0)
("0" represents the first record in the array.)

This will reset your result to the top of the array so that you can then re-process with
while($row = mysql_fetch_array($result)) or other array processing.
Tristan
28-Jul-2009 12:42
Here's a quicker way to clone a record.  Only 3 lines of code instead of 4.  But the table must have an auto-incremented id.
I took the code from Tim and altered it. Props to Tim.

// copy content of the record you wish to clone $entity mysql_fetch_array(mysql_query("SELECT * FROM table_name WHERE id='$id_to_be cloned'"), MYSQL_ASSOC) or die("Could not select original record");
// set the auto-incremented id's value to blank. If you forget this step, nothing will work because we can't have two records with the same id $entity["id"] = "";
// insert cloned copy of the original  record mysql_query("INSERT INTO table_name (".implode(", ",array_keys($entity)).") VALUES ('".implode("', '",array_values($entity))."')");
// if you want the auto-generated id of the new cloned record, do the following $newid mysql_insert_id(); ?> 
There you go.
mehdi dot haresi at gmail dot com
20-Jul-2009 07:44
For all of you having problems accessing duplicated field names in queries with their table alias i have implemented the following quick solution:

function mysql_fetch_alias_array($result)
{
    if (!(
$row mysql_fetch_array($result)))
    {
        return 
null;
    }

    
$assoc = Array();
    
$rowCount mysql_num_fields($result);
   
    for (
$idx 0$idx $rowCount$idx++)
    {
        
$table mysql_field_table($result$idx);
        
$field mysql_field_name($result$idx);
        
$assoc["$table.$field"] = $row[$idx];
    }
   
    return 
$assoc;
}
?>
Lets asume we have 2 tables student and contact each having fID as the index field and want to access both fID fields in php.

The usage of this function will be pretty similar to calling mysql_fetch_array:

$result mysql_query("select * from student s inner join contact c on c.fID = s.frContactID");

while (
$row mysql_fetch_alias_array($result))
{
    echo 
"StudenID: {$row['s.fID']}, ContactID: {$row['c.fID']}";
}
?>
Voila, that's it :)

Please be aware that by using this function, you have to access all fields with their alias name (e.g. s.Name, s.Birhtday) even if they are not duplicated.

If you have questions, just send me a mail.

Best regards,
Mehdi Haresi
die-webdesigner.at
info at o08 dot com
06-Dec-2008 02:33
As opposite of mysql_fetch_array:

function mysql_insert_array ($my_table$my_array) {
    
$keys array_keys($my_array);
    
$values array_values($my_array);
    
$sql 'INSERT INTO ' $my_table '(' implode(','$keys) . ') VALUES ("' .implode('","'$values) . '")';
    return(
mysql_query($sql));
#http://www.weberdev.com/get_example-4493.html ?>
KingIsulgard
24-Nov-2008 01:49
I have found a way to put all results from the select query in an array in one line.

// Read records
$result = mysql_query("SELECT * FROM table;") or die(mysql_error());
   
// Put them in array
for($i = 0; $array[$i] = mysql_fetch_assoc($result); $i++) ;
   
// Delete last empty one
array_pop($array);

You need to delete the last one because this will always be empty.

By this you can easily read the entire table to an array and preserve the keys of the table columns. Very handy.
jab_creations_-at_-yahoo_-dot-_com
23-Nov-2008 07:04
If you notice that the first row is not appearing in PHP when you're looking at the data make sure you're not executing the mysql_fetch_array function twice on the same query. I hope that helps break some other people from the frustration of missing rows.
noagbodjivictor at gmail dot com
10-Nov-2007 04:53
Little improvement to the previous function.

function mysql_fetch_rowsarr($result, $numass=MYSQL_BOTH) {
  $got = array();

  if(mysql_num_rows($result) == 0)
    return $got;

  mysql_data_seek($result, 0);
 
  while ($row = mysql_fetch_array($result, $numass)) {
    array_push($got, $row);
  }
 
  return $got;
}
joaocosta at zonalivre dot org
22-Jul-2007 02:29
You can make the function on the previous note slightly more efficient by using php's built in array_push function instead of a foreach loop:

function mysql_fetch_rowsarr($result$numass=MYSQL_BOTH) {
  
$got=array();
  
mysql_data_seek($result0);
    while (
$row mysql_fetch_array($result$numass)) {
        
array_push($got$row);
    }
  return 
$got;
}
?>
devinivy at gmail dot com
16-Jul-2007 04:02
function mysql_fetch_rowsarr($result$numass=MYSQL_BOTH) {
  
$i=0;
  
$keys=array_keys(mysql_fetch_array($result$numass));
  
mysql_data_seek($result0);
    while (
$row mysql_fetch_array($result$numass)) {
      foreach (
$keys as $speckey) {
        
$got[$i][$speckey]=$row[$speckey];
      }
    
$i++;
    }
  return 
$got;
}
?>
Ever found it a bit of a pain to use mysql_fetch_array()? I find this function much easier to receive data, and to be in a more accessible manner when accessing various data from several rows. It is practical when more than one row is expected to be returned from a SELECT query. It returns a 2-dimensional array in the form of $arr[number_row_returned][column_desired]. So, if there is some column 'password', and you want the password from the third returned row:
$result mysql_query($query);$arr mysql_fetch_rowsarr($result);$password $arr[2]['password'];?>
The function also has the ability to return the columns numerically, associatively, or both, just as mysql_fetch_array() does. It uses MYSQL_NUM, MYSQL_ASSOC, and MYSQL_BOTH (MYSQL_BOTH being the default)- exactly like mysql_fetch_array(). So, if the column 'password' is the 4th column which is returned in the query, then password of the 1st returned row could be accessed like so:
$arr mysql_fetch_rowsarr($resultMYSQL_NUM);$password $arr[0][3];?>
I hope you find it useful!
-Dan
badulla at kaboom dot com
26-Feb-2007 10:15
Just a real world example from a post below. I found it very useful for creating a table I needed from hundreds of proprietary colors. I added formatting so HTML source is clean and thought someone might be able to use or modify as I did.

// Query$sql "select colors_id, colors_type, colors_name, colors_number, R, G, B, colors_wetsample from products_colors where colors_type = 'Color Canvas' order by colors_number asc limit 40";
$result mysql_query($sql ,$db);
// Change display for number of columns. Do not change cols as it is needed for counting.$display 7;$cols 0;
echo 
"   \n";
while(
$C mysql_fetch_array($result)){
   if(
$cols == 0){
       echo 
"    \n";
   }
   
// Display each cell here
   
echo "     \n";
   
$cols++;
   if(
$cols == $display){
       echo 
"    \n";
       
$cols 0;
   }
}
// Display the correct HTMLif($cols != $display && $cols != 0){
   
$neededtds $display $cols;
   for(
$i=0;$i<$neededtds;$i++){
       echo 
"     \n";
   }
     echo 
"    \n"
          "  
\n"
        "\t\n"
        "\t \n"
        "\t  \n"
        "\t \n"
        "\t \n"
        "\t  \n"
        ."\t \n"
        "\t
" "
        
"style=" "\"" "background-color: rgb("
        
$C['R'] . "," .$C['G'] . "," $C['B'] . ")\"" ">\n"
        
"\t   $C['colors_number'] . "\n"
        
"\t 
\n"
        "\t   "
        
"$C['colors_number'] . "')\"" ">"$C['colors_name'] . "\n"
        
"\t 
\n"
        
"    
\n"
;
   } else {
   echo 
"   \n";
}
?>
joshmish at haanmc dot com
11-Dec-2006 04:29
A simple function that returns the next auto index. I recommend you use a unique id and not a relative row index, but if the need arises, here's how to get that id before you INSERT without the error-prone MAX(id) approach.

function nextautoindex ($table) {
    
$res=mysql_query("SHOW TABLE STATUS");
    if (@
mysql_num_rows($res)>0) { while ($row = @mysql_fetch_array($resMYSQL_ASSOC)) {
        if (
$table == $row["name"]) return $row["Auto_increment"];
    }}
    return 
false;
}
/* Example usage:
$newID = nextautoindex("user"); // output: 12

// Now you can insert multiple related records without guessing the id
*/
?>
Typer85 at gmail dot com
01-Dec-2006 01:22
Please be advised that the resource result that you pass to this function can be thought of as being passed by reference because a resource is simply a pointer to a memory location.

Because of this, you can not loop through a resource result twice in the same script before resetting the pointer back to the start position.

For example:

----------------

// Assume We Already Queried Our Database.

// Loop Through Result Set.
while( $queryContent mysql_fetch_row$queryResult ) {

    
// Display.

    
echo $queryContent];
}
// We looped through the resource result already so the
// the pointer is no longer pointing at any rows.

// If we decide to loop through the same resource result
// again, the function will always return false because it
// will assume there are no more rows.

// So the following code, if executed after the previous code
// segment will not work.
while( $queryContent mysql_fetch_row$queryResult ) {

    
// Display.

    
echo $queryContent];
}
// Because $queryContent is now equal to FALSE, the loop
// will not be entered.
?>----------------

The only solution to this is to reset the pointer to make it point at the first row again before the second code segment, so now the complete code will look as follows:

----------------

// Assume We Already Queried Our Database.

// Loop Through Result Set.
while( $queryContent mysql_fetch_row$queryResult ) {

    
// Display.

    
echo $queryContent];
}
// Reset Our Pointer.
mysql_data_seek$queryResult );
// Loop Again.
while( $queryContent mysql_fetch_row$queryResult ) {

    
// Display.

    
echo $queryContent];
}
?>----------------

Of course you would have to do extra checks to make sure that the number of rows in the result is not 0 or else mysql_data_seek itself will return false and an error will be raised.

Also please note that this applies to all functions that fetch result sets, including mysql_fetch_row, mysql_fetch_assos, and mysql_fetch_array.
05-Jun-2006 09:14
Note that as unlikely as it might be, queries like the following will mess up an array that is of result_type MYSQL_BOTH:

SELECT 'hello', 'world' AS '0';
hdixonish at deltabravo dot com
18-May-2006 10:39
Just a fairly useful (to me at least!) "implementation" of mysql_fetch_assoc to stop the clobbering of identical column names and allow you to work out which table produced which result column when using a JOIN (or simple multiple-table) SQL query:
(assuming a live connection ...)
$sql "SELECT a.*, b.* from table1 a, table2 b WHERE a.id=b.id"// example sql$r mysql_query($sql,$conn);
if (!
$r) die(mysql_error());$numfields mysql_num_fields($r);$tfields = Array();
for (
$i=0;$i<$numfields;$i++)
{
    
$field =  mysql_fetch_field($r,$i);
    
$tfields[$i] = $field->table.'.'.$field->name;
}
while (
$row mysql_fetch_row($r))
{
    
$rowAssoc = Array();
    for (
$i=0;$i<$numfields;$i++)
    {
        
$rowAssoc[$tfields[$i]] = $row[$i];
    }
//    do stuff with $rowAssoc as if it was $rowAssoc = mysql_fetch_assoc($r) you had used, but with table. prefixes}?>let's you refer to $rowAssoc['a.fieldname'] for example.

[for real email addr, remove the ish]
tilmauder at yahoo dot com
16-Feb-2006 09:18
Remember that using a while() loop for traversing your result array is significantly slower than using a foreach() loop. Read the comments in the control structures section of this site for further details.
john at skem9 dot com
21-Jan-2006 12:13
my main purpose was to show the fetched array into a table, showing the results side by side instead of underneath each other, and heres what I've come up with.

just change the $display number to however many columns you would like to have, just dont change the $cols number or you might run into some problems.

$display 4;$cols 0;
echo 
"";
while(
$fetched mysql_fetch_array($result)){
    if(
$cols == 0){
        echo 
"\n";
    }
    
// put what you would like to display within each cell here
    
echo "\n";
    
$cols++;
    if(
$cols == $display){
        echo 
"\n";
        
$cols 0;
    }
}
// added the following so it would display the correct htmlif($cols != $display && $cols != 0){
    
$neededtds $display $cols;
    for(
$i=0;$i<$neededtds;$i++){
        echo 
"\n";
    }
     echo 
"
".$fetched['id']."
"
.$fetched['name']."
"
;
    } else {
    echo 
"";
}
?>
Hopefully this will save some of you a lot of searching.

any kind of improvements on this would be awesome!
andrea at 3site dot it
28-Dec-2005 03:51
alternative mysql_fetch_all

// array mysql_fetch_all(query:resource [, kind:string (default:'assoc' | 'row')])
function mysql_fetch_all($query, $kind = 'assoc') {
    $result = array();
    $kind = $kind === 'assoc' ? $kind : 'row';
    eval('while(@$r = mysql_fetch_'.$kind.'($query)) array_push($result, $r);');
    return $result;
}

// Example
$query = mysql_query($myquery) or die(mysql_error());
$result = mysql_fetch_all($query);
echo '
'.print_r($result, true).'
';
info at modulotech dot ch
23-Nov-2005 10:37
I think using a for loop to display fetched rows from a table is more convenient than a while loop, since one have directely access to the record number:

$reclist = mysql_query("SELECT field FROM table",$db)
               or die(mysql_errno()." : ".mysql_error());

for ($j=0; $rec=mysql_fetch_array($reclist); $j++){
     printf("%s - %s
\n",$j,$rec["field"]);   
}

Hope this is usefull. Ali
tim at wiltshirewebs dot com
14-Nov-2005 01:49
Here's a quick way to duplicate or clone a record to the same table using only 4 lines of code:

// first, get the highest id number, so we can calc the new id number for the dupe
// second, get the original entity
// third, increment the dupe record id to 1 over the max
// finally insert the new record - voila - 4 lines!

$id_max = mysql_result(mysql_query("SELECT MAX(id) FROM table_name"),0,0) or die("Could not execute query");
$entity = mysql_fetch_array(mysql_query("SELECT * FROM table." WHERE id='$id_original'),MYSQL_ASSOC) or die("Could not select original record"); // MYSQL_ASSOC forces a purely associative array and blocks twin key dupes, vitally, it brings the keys out so they can be used in line 4
$entity["id"]=$id_max+1;
mysql_query("INSERT INTO it_pages (".implode(", ",array_keys($Entity)).") VALUES ('".implode("', '",array_values($Entity))."')");

Really struggled in cracking this nut - maybe there's an easier way out there?  Thanks to other posters for providing inspiration. Good luck - Tim
eddie at nailchipper dot com
03-Nov-2005 06:58
mob AT stag DOT ru has a nice function for getting simple arrays from MySQL but it has a serious bug. The MySQL link being set as an argument is NULL when no link is supplied meaning that you're passing NULL to the mysql funcctions as a link, which is wrong. I am not using multitple connections so I removed the link and using the global link. If you want to support multiple links check to see if its set first.

/*
* to support multiple links add the $link argument to function then
* test it before you use the link
*
* if(isset($link))
*   if($err=mysql_errno($link))return $err;
* else
*   if($err=mysql_errno())return $err;
*/

function mysql_fetch_all($query){
 $r=@mysql_query($query);
 if($err=mysql_errno())return $err;
 if(@mysql_num_rows($r))
  while($row=mysql_fetch_array($r))$result[]=$row;
 return $result;
}
function mysql_fetch_one($query){
 $r=@mysql_query($query);
 if($err=mysql_errno())return $err;
 if(@mysql_num_rows($r))
 return mysql_fetch_array($r);
}
kunky at mail dot berlios dot de
01-Oct-2005 10:41
This is very useful when the following query is used:

`SHOW TABLE STATUS`

Different versions of MySQL give different responses to this.

Therefore, it is better to use mysql_fetch_array() because the numeric references given my mysql_fetch_row() give very different results.
joelwan at gmail dot com
05-Sep-2005 10:14
Try Php Object Generator: http://www.phpobjectgenerator.com

It's kind of similar to Daogen, which was suggested in one of the comments above, but simpler and easier to use.

Php Object Generator generates the Php Classes for your Php Objects. It also provides the database class so you can focus on more important aspects of your project. Hope this helps.
yashiro at esfera dot cl
30-Jun-2005 01:36
This is a simple function that outputs a String with a table with the name of fields and their respective values, pretty useful
u insert a result like this : $result = mysql_query("select * from table", $db)

    /*Esta funcion genera automaticamente una tabla que muestra el resultado de un mysql_query,
    basta con invocar la funcion y con echo imprimirla*/
    function muestra_select($result){
        $tabla = "\n\t".''."\n";
        for($i = 0; $i < mysql_num_fields($result); $i++){
            $aux = mysql_field_name($result, $i);
            $tabla .= "\t\t\n";
        }
        while ($linea = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $tabla .= "\t\t\n";
            foreach ($linea as $valor_col) {
                $tabla .= "\t\t\t".''."\n";
            }
            $tabla .= "\t\t\n";
        }
        $tabla .= "\t
".$aux."
'.$valor_col.'
\n";
        return $tabla;
    }
romans at servidor dot unam dot mx
13-May-2005 05:31
Regarding duplicated field names in queries, I wanted some way to retrieve rows without having to use alias, so I wrote this class that returns rows as 2d-arrays

  $field $drow['table']['column'];?>
Here is the code:

  class mysql_resultset
  
{
    var 
$results$map;

    function 
mysql_resultset($results)
    {
      
$this->results $results;
      
$this->map = array();

      
$index 0;
      while (
$column mysql_fetch_field($results))
      {
        
$this->map[$index++] = array($column->table$column->name);
      }
    }

    function 
fetch()
    {
      if (
$row mysql_fetch_row($this->results))
      {
        
$drow = array();

        foreach (
$row as $index => $field)
        {
          list(
$table$column) = $this->map[$index];
          
$drow[$table][$column] = $row[$index];
        }

        return 
$drow;
      }
      else
        return 
false;
    }
  }
?>
The class is initialized with a mysql_query result:

  $resultset = new mysql_resultset(mysql_query($sql));?>
The constructor builds an array that maps each field index to a ($table, $column) array so we can use mysql_fetch_row and access field values by index in the fetch() method. This method then uses the map to build up the 2d-array.

An example:

  $sql =
    
"select orders.*, clients.*, productos.* ".
    
"from orders, clients, products ".
    
"where join conditions";

  
$resultset = new mysql_resultset(mysql_query($sql));

  while (
$drow $resultset->fetch())
  {
    echo 
'No.: '.$drow['orders']['number'].'
'
;
    echo 
'Client: '.$drow['clients']['name'].'
'
;
    echo 
'Product: '.$drow['products']['name'].'
'
;
  }
?>
I hope others find this useful as it has been to me.
mob AT stag DOT ru
24-Jan-2005 07:16
I wrote some utility functions to improve usability and readability, and use them everywhere in my code. I suppose they can help.

function mysql_fetch_all($query,$MySQL=NULL){
 $r=@mysql_query($query,$MySQL);
 if($err=mysql_errno($MySQL))return $err;
 if(@mysql_num_rows($r))
  while($row=mysql_fetch_array($r))$result[]=$row;
 return $result;
}
function mysql_fetch_one($query,$MySQL=NULL){
 $r=@mysql_query($query,$MySQL);
 if($err=mysql_errno($MySQL))return $err;
 if(@mysql_num_rows($r))
 return mysql_fetch_array($r);
}

Example use:
if(is_array($rows=mysql_fetch_all("select * from sometable",$MySQL))){
 //do something
}else{
 if(!is_null($rows)) die("Query failed!");
}
joey at clean dot q7 dot com
19-Apr-2004 02:47
The issue of NULL fields seems to not be an issue anymore (as of 4.2.2 at least).  mysql_fetch_* now seems to fully populate the array and put in entries with values of NULL when that is what the database returned.  This is certainly the behaviour I expected, so I was concerned when i saw the notes here, but testing shows it does work the way I expected.
Ben
06-Apr-2004 06:59
One of the most common mistakes that people make with this function, when using it multiple times in one script, is that they forget to use the mysql_data_seek() function to reset the internal data pointer.

When iterating through an array of MySQL results, e.g.

while ($line mysql_fetch_array($resultMYSQL_ASSOC)) {
    foreach (
$line as $col_value) {
        echo 
$col_value '
'
;
    }
}
?>
the internal data pointer for the array is advanced, incrementally, until there are no more elements left in the array. So, basically, if you copy/pasted the above code into a script TWICE, the second copy would not create any output. The reason is because the data pointer has been advanced to the end of the $line array and returned FALSE upon doing so.

If, for some reason, you wanted to interate through the array a second time, perhaps grabbing a different piece of data from the same result set, you would have to make sure you call

mysql_data_seek($result0);?>
This function resets the pointer and you can re-iterate through the $line array, again!
sigit at djpkpd dot go dot id, harris at djpkpd dot go dot id
25-Mar-2003 06:28
if you have to use the field name with number like 1,2,..etc, it cause a problem when you fetch it with mysql_fetch_array.
An index array will contain a field name.
The solusion is:
1. Use mysql_fetch_assoc to escape the result to html;
2. Use alias and choose another name of field in mysql_query
hanskrentel at yahoo dot de
08-Jan-2003 09:25
for the problem with fields containing null values in an associated array, feel free to use this function. i've got no more problems with it, just drop it in your script:

/*
*    mysql_fetch_array_nullsafe
*
*
*    get a result row as an enumerated and associated array
*    ! nullsafe !
*
*    parameter:    $result
*                    $result:    valid db result id
*
*    returns:    array | false (mysql:if there are any more rows)
*
*/
function mysql_fetch_array_nullsafe($result) {
    $ret=array();

    $num = mysql_num_fields($result);
    if ($num==0) return $ret;

    $fval = mysql_fetch_row ($result);
     if ($fval === false) return false;

    $i=0;
     while($i<$num)
        {
            $fname[$i] = mysql_field_name($result,$i);           
            $ret[$i] = $fval[$i];            // enum
            $ret[''.$fname[$i].''] = $fval[$i];    // assoc
            $i++;
        }

    return $ret;
}
juancri at tagnet dot org
12-Nov-2002 09:41
An example with mysql_fetch_array():

    $result = mysql_query("SELECT name FROM table WHERE id=8");
    $array = mysql_fetch_array($result);

$array will be:

    array ([0] => "John", ['name'] => "John")

Then you can access to the results:

    echo "The name is " . $array[0];
    // or
    echo "The name is " . $array['name'];

But the array is not referential. $array[0] is not a reference to $array['name'] or $array['name'] to $array[0], they are not relationed between. Because of that, the system will use excesive memory. With large columns, try to use mysql_fetch_assoc() or mysql_fetch_row() only.
dkantha at yahoo dot com
11-Nov-2002 12:27
I did find 'jb at stormvision's' code useful above, but instead of the number of rows you need the number of fields; otherwise you get an error.

So, it should read like the following:

$result=mysql_query("select * from mydata order by 'id'")or die('died');
$num_fields = mysql_num_fields($result);
$j=0;
$x=1;
while($row=mysql_fetch_array($result)){ 
  for($j=0;$j<$num_fields;$j++){
   $name = mysql_field_name($result, $j);
   $object[$x][$name]=$row[$name];
  }$x++;
}

For Later in the script you may use the below array to gain access to your data

$i=1;
$ii=count($object);        //quick access function
for($i=1;$i<=$ii;$i++){
echo $object[$i]['your_field_name'];
}

I have tested this in my apps and it works great! :-)
glenn dot hoeppner at yakhair dot com
09-Oct-2002 09:04
Just another workaround for columns with duplicate names...

Modify your SQL to use the AS keyword.

Instead of:
$sql = "SELECT t1.cA, t2.cA FROM t1, t2 WHERE t1.cA = t2.cA";

Try:
$sql = "SELECT t1.cA AS foo1, t2.cA AS foo2 FROM t1, t2 WHERE t1.cA = t2.cA";

Then you can reference the results by name in the array:
  $row[foo1], $row[foo2]
tslukka at cc dot hut dot fi
25-Sep-2002 09:20
If you think MySQL (or other) database
handling is difficult and requires lot's of
code, I recommend that you try http://titaniclinux.net/daogen/

DaoGen is a program source code generator
that supports PHP and Java. It makes database
programming quick and easy. Generated sources
are released under GPL.
robjohnson at black-hole dot com
14-Jun-2002 10:22
Benchmark on a table with 38567 rows:

mysql_fetch_array
MYSQL_BOTH: 6.01940000057 secs
MYSQL_NUM: 3.22173595428 secs
MYSQL_ASSOC: 3.92950594425 secs

mysql_fetch_row: 2.35096800327 secs
mysql_fetch_assoc: 2.92349803448 secs

As you can see, it's twice as effecient to fetch either an array or a hash, rather than getting both.  it's even faster to use fetch_row rather than passing fetch_array MYSQL_NUM, or fetch_assoc rather than fetch_array MYSQL_ASSOC.  Don't fetch BOTH unless you really need them, and most of the time you don't.
barbieri at NOSPAMzero dot it
31-May-2002 01:21
Here is a suggestion to workaround the problem of NULL values:

// get associative array, with NULL values set
$record = mysql_fetch_array($queryID,MYSQL_ASSOC);

// set number indices
if(is_array($record))
{
    $i = 0;
    foreach($record as $element)
        $record[$i++] = $element;
}

This way you can access $result array as usual, having NULL fields set.
mjm at porter dot appstate dot edu
13-Mar-2002 03:48
If you perform a SELECT query which returns different columns with duplicate names, like this:

--------
$sql_statement = "SELECT tbl1.colA, tbl2.colA FROM tbl1 LEFT JOIN tbl2 ON tbl1.colC = tbl2.colC";

$result = mysql_query($sql_statement, $handle);

$row = mysql_fetch_array($result);
--------

Then

$row[0] is equivalent to $row["colA"]

but

$row[1] is not equivalent to $row["colA"].

Moral of the story: You must use the numerical index on the result row arrays if column names are not unique, even if they come from different tables within a JOIN. This would render mysql_fetch_assoc() useless.

[Ed. note - or you could do the usual 'select tbl1.colA as somename, tbl2.colA as someothername. . .' which would obviate the problem. -- Torben]
some at gamepoint dot net
10-Jan-2002 07:13
I never had so much trouble with null fields but it's to my understanding that extract only works as expected when using an associative array only, which is the case with mysql_fetch_assoc() as used in the previous note.

However a mysql_fetch_array will return field values with both the numerical and associative keys, the numerical ones being those extract() can't handle very well.
You can prevent that by calling mysql_fetch_array($result,MYSQL_ASSOC) which will return the same result as mysql_fetch_assoc and is extract() friendly.