Posts Tagged ‘Example Code’

April 10th, 2009 | Categories: Programming | Tags: , ,

If you need to take a simple string of values and do something for each of them you can use the explode function in PHP. Below is a list separated with spaces. Your list can be separated with any character, just change the line that contains explode(” “, $list) with a different character between the quotes.

<?php
$list = “me you him john bob mary”;
$names = explode(” “, $list);

foreach($names as $name) {
echo $name . “<br />”;
}
?>

April 10th, 2009 | Categories: Programming | Tags: , ,

Here is a simple example of how to connect to a MySQL server using PHP and pull down some data inside the database.

<?php

// Connect to database server
$hd = mysql_connect(“myhost”, “username”, “password”)
or die (“Unable to connect.”);

// Select database
mysql_select_db (“database”, $hd)
or die (“Unable to select database.”);

// Execute sample query
$res = mysql_query(“SELECT * FROM customer”, $hd)
or die (“Unable to run query.”);

// Query number of rows in rowset
$nrows = mysql_num_rows($res);

// Output
echo “The query returned $nrows row(s):<br />”;

// Iteration loop, for each row in rowset
while ($row = mysql_fetch_assoc($res))
{
// Assigning variables from cell values
$data1 = $row["title"];
$data2 = $row["fname"];
$data3 = $row["lname"];
$data4 = $row["phone"];

// Outputting data to browser
echo “ROW# $nr : $data1 $data2 $data3 $data4 <br />”;
}

// Close the MySQL connection
mysql_close($hd);

?>

TOP