Tag: table

Check if Field Exists in Mysql Table

Sometimes it is useful to know if a field exists in a mysql table before running a query using that field name, especially when the field name is coming from some kind of user input.

So to do this we use the function mysql_list_fields to grab the fields out of a table and run through them with a for loop until we find the one we are looking for – using the function mysql_field_name, in which case we return true. If we don’t find it, the function returns false.

[code lang=”php”]

[/code]

And it’s that easy!

Filed under: MySQL, PHP, TutorialsTagged with: , , , ,

Mysql Rows from a Table

If you have a mysql database you can connect to, you can create tables, rows, columns, and do many other mysql functions through PHP. Let’s say we have a mysql database named “my_database”. We will connect to it using the php function “mysql_connect()” and draw information from the tables.

Config.php:
[code lang=”php”]

[/code]

This is usually placed in a config.php file and is included or required on other pages that execute mysql queries.

Now let’s move on to our query file. Let’s say we have a table named “table1.” We will insert the config file to have the connection to the database, and then select columns from the table1.

[code lang=”php”]
0){
// we have some!

// this is used to grab all rows in the table.
while($row = mysql_fetch_array($sql)){
echo ‘Col1: ‘.$row[‘col1′].’
‘;
echo ‘Col2: ‘.$row[‘col2′].’
‘;
echo ‘Col3: ‘.$row[‘col3′].’

‘;
}
} else {
// nothing found.
echo ‘No rows found.’;
}

?>
[/code]

Now, this will return simple HTML of each row with col1: (its value), col2: (its value), etc. We can get fancy and use a table to organize our information better. Here is an example:

[code lang=”php”]
if($count > 0){
// we have some, make the table!
echo ‘

‘;
echo ‘

‘;

// this is used to grab all rows in the table.
while($row = mysql_fetch_array($sql)){
echo ‘

‘;
echo ‘

‘;
echo ‘

‘;
echo ‘

‘;
echo ‘

‘;
}
} else {
// nothing found.
echo ‘No rows found.’;
}
[/code]

This will display something like this:

Col1 Col2 Col3
‘.$row[‘col1′].’ ‘.$row[‘col2′].’ ‘.$row[‘col3′].’
Col1 Col2 Col3
Row1: value1 Row1: value2 Row1: value3
Row2: value1 Row2: value2 Row2: value3
Row3: value1 Row3: value2 Row3: value3
Filed under: Web ProgrammingTagged with: , ,