PHP MySQL Basic Connectivity Code
Here is some basic query code for people starting out in php and mysql. Obviously this is for an existing mysql database.
<?php
//database
$const['sql_username']='mysql_user';
$const['sql_password']='mysql_password';
$const['sql_host' ]='localhost';
$const['sql_database']='wp_database';
function connection()
{
global $const;
$user = $const['sql_username'];
$pass = $const['sql_password'];
$host = $const['sql_host' ];
$dbname = $const['sql_database'];
$db = mysql_pconnect($host, $user, $pass) or die("could not connect: " . mysql_error());
mysql_select_db($dbname, $db) or die("cannot select db $dbname: " . mysql_error());
return $db;
}
$productid=34;
$category ='hardware';
$db = connection();
$query = sprintf("select id,productname,desc,price from products where id=%s and category=%s",
mysql_real_escape_string($productid),
mysql_real_escape_string($category)
);
$result = mysql_query($query, $db) or die('could not execute query: ' . $query);
echo "<table>";
while ($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['productname']."</td>";
echo "<td>".$row['description']."</td>";
echo "<td>".$row['price']."</td>";
echo "</tr>";
}
echo "</table>";
?>code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)
|