Wednesday, October 05, 2005

PHP Tips -- DB Functions

MySQL Functions
<?php
$host="localhost:3306";
$user="root";
$dbpasswd="passwd";
$dbname="mydb";

$id = @mysql_connect($host, $user, $dbpasswd) or die(mysql_error());

@mysql_select_db($dbname,$id)
or die("DBCannot open database" . mysql_error());

$query = "select * from mycontact;";
$result = mysql_query($query, $id)
or die("mysql_query: $query" . mysql_error());

// Retrieves the number of fields from a query.
$num_fields = mysql_num_fields($result);
$rows = mysql_num_rows($result);
if ($rows === false) return false;

$i=0;
while($i<$num_fields)
{
$fname[$i] = mysql_field_name($result,$i);
$i++;
}

while ($accarray = mysql_fetch_row($result))
//No. 1 fast, but difficult to remember column number.
while ($accarray = mysql_fetch_assoc($result))
//No. 2 fast, with associated array, recommend
while ($conarray = mysql_fetch_array($result))
//No. 3 fast
while ($conarray = mysql_fetch_array($result, MYSQL_NUM))
//No. 4 fast
while ($conarray = mysql_fetch_array($result, MYSQL_ASSOC))
//No. 5 fast
while ($conarray = mysql_fetch_array($result, MYSQL_BOTH))
//The slowest
{
foreach($conarray as $k=>$v) $message .= $v. " ";
$fname = $conarray['firstname'];
}

mysql_data_seek($result, 0);

mysql_close($id);
?>


ODBC Functions

<?php
//connect to database
$connectionstring = odbc_connect("myapp", "user", "pswd");

//SQL query
$Query = "delete from company where id=$jid";
$Query = "update company set description='$description', company='$company', Website = '$web', name='$name', tel='$tel', fax='$fax', email='$email', address='$address', date='$date' where id=$jid";
$Query = "SELECT *, DATEPART('yyyy',date) AS mydate FROM company where id=$jid";

//execute query
$queryexe = odbc_do($connectionstring, $Query);
if (odbc_fetch_row($queryexe))
{
//collect results
$position = odbc_result($queryexe, "position");
}

//disconnect from database
odbc_close($connectionstring);
?>

No comments: