If you have a mysql database you can connect to, you can create tables, rows, columns, and do many other mysql functions through PHP. Let’s say we have a mysql database named “my_database”. We will connect to it using the php function “mysql_connect()” and draw information from the tables.
Config.php:
[code lang=”php”]
[/code]
This is usually placed in a config.php file and is included or required on other pages that execute mysql queries.
Now let’s move on to our query file. Let’s say we have a table named “table1.” We will insert the config file to have the connection to the database, and then select columns from the table1.
[code lang=”php”]
0){
// we have some!
// this is used to grab all rows in the table.
while($row = mysql_fetch_array($sql)){
echo ‘Col1: ‘.$row[‘col1′].’
‘;
echo ‘Col2: ‘.$row[‘col2′].’
‘;
echo ‘Col3: ‘.$row[‘col3′].’
‘;
}
} else {
// nothing found.
echo ‘No rows found.’;
}
?>
[/code]
Now, this will return simple HTML of each row with col1: (its value), col2: (its value), etc. We can get fancy and use a table to organize our information better. Here is an example:
[code lang=”php”]
if($count > 0){
// we have some, make the table!
echo ‘
‘;
echo ‘
Col1 |
Col2 |
Col3 |
‘;
// this is used to grab all rows in the table.
while($row = mysql_fetch_array($sql)){
echo ‘
‘;
echo ‘
‘.$row[‘col1′].’ |
‘;
echo ‘
‘.$row[‘col2′].’ |
‘;
echo ‘
‘.$row[‘col3′].’ |
‘;
echo ‘
‘;
}
} else {
// nothing found.
echo ‘No rows found.’;
}
[/code]
This will display something like this:
Col1 |
Col2 |
Col3 |
Row1: value1 |
Row1: value2 |
Row1: value3 |
Row2: value1 |
Row2: value2 |
Row2: value3 |
Row3: value1 |
Row3: value2 |
Row3: value3 |
Filed under: Web ProgrammingTagged with: mysql, rows, table