Thursday, November 18, 2010

Goodbye OR

There are times in PHP when you want a true condition based on whether or not a variable matches one of many values. I used to just link many conditionals together using the OR (||) operator:

if($name == "Bob" || $name == "Andy" || $name == "Heidi" || $name == "Cindy") {
    //perform stuff here
}


This is fine when you only have a few values to check, but if you have to check the variable against more than a handful, this can get tedious. So, now what I do is I create an array of values that I want to check against. Then I use the in_array() function like so:

//define the array
$names = Array("Bob","Andy","Heidi","Cindy");

//now we use in_array() to check the variable
if(in_array($name,$names)){
    //perform stuff here
}


And that's that. You can even put the array into the if statement if you desire:

if(in_array($name,Array("Bob","Andy","Heidi","Cindy")){
    //perform stuff here
}

Tuesday, November 16, 2010

How to quickly show the results of query in Table format

There are many times when I'm coding when I just want to quickly display the results of a SQL Query either for debugging purposes or until I polish up a nice view for the user. This code will pick out the column names and make column headers in the table for each one.

P.S. This demonstration is for MSSQL, but it will work the same with MySQL (just replace the mssql_ functions with mysql_ functions).

<?php
//connect to your database
mssql_connect('localhost', 'user', 'password');
mssql_select_db('database');

//query your database
$sql = "SELECT * FROM employee_info";
$result = mssql_query($sql);

//only show output if there are records returned
if(mssql_num_rows($result)) {
    echo "<table border=1>"; //start the table
    $th = false; //set a boolean to determine when to show the header
    //loop through the results
    while($row = mssql_fetch_assoc($result)) {
        //display the header row if it hasn't already been shown
        if(!$th) {
            echo "<tr>";
            foreach($row as $key => $data)
                echo "<th>$key</th>";
            echo "</tr>";
            $th = true;
        }
        //start your data row
        echo "<tr>";
        foreach($row as $data)
                echo "<td>$data</td>";
        echo "</tr>";
    }
    echo "</table>"; //end the table
} else {
    echo "There are no results";
}
?>