Archive for the ‘PHP Snippets’ Category.

PHP Snippet: Iterating through an array


$colorList = array(0 =>"red",1=>"green",2=>"blue",3=>"black",4=>"white");

foreach( $colorList as $key => $value){
	      echo "Key: $key, Val: $value ";
}

OUTPUT:

Key: 0, Val: red
Key: 1, Val: green
Key: 2, Val: blue
Key: 3, Val: black
Key: 4, Val: white

PHP Snippet: PHP MySQL Database Sample Code

<?php
//Connect to Databse
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($G['dbname']);
?>
<?php
// Simple query returning a single row 'COL_VAL'
$query = " SELECT 'COL_VAL' as COL_VAL ";
//Fetch Result
$result = mysql_query($query) or die('Error2, query failed:'.$query);
//Iterate through Result
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$C_COL_VAL = $row['COL_VAL'];
echo "$C_COL_VAL";
}
?>
<?php
//Closing DB Connection
mysql_close($conn);
?>

PHP Snippet: Print an array

$mappings = array ('windows' => 'microsoft', 'ipod' => 'apple', 'corby' => 'samsum');
print_r($mappings);

output:

Array ( [windows] => microsoft [ipod] => apple [corby] => samsum )

Sample Code: Simple Form Processing in PHP

<?php

 if(isset($_POST['submit'])){
    echo $_POST['name'];
 }else{

?>
<html>
<body>
  <form method="post" action="">
    <input name="name" id="name" type="text" />
	<input name="submit" id="submit" value="Add Me" type="submit" />
  </form>
</body>
</html>
<?php
}
?>