Search
Syndication
Sponsors

Archive for the ‘Database’ Category

View a sqlite table

Wednesday, February 25th, 2009

This example shows how to view all the data in a sqlite table

<?php
//open db
if (!($db = sqlite_open(’sample.db’)))
{
    die(sqlite_error_string(sqlite_last_error($db)));
}

//select all results from db
$sql = ’select * from sample order by id asc’;
if (!($result = sqlite_query($db, $sql)))
{
    die(’SQL ERROR: ‘ . sqlite_error_string(sqlite_last_error($db)));
}

//display all results
while ($row = sqlite_fetch_array($result))
{
    echo “{$row['id']}. {$row['cat']} . {$row['title']}<br />\n”;
}

//close
sqlite_close($db);
?>

Add to a sqlite database

Wednesday, February 25th, 2009

<?php
//open db
if (!($db = sqlite_open(’sample.db’)))
{
    die(sqlite_error_string(sqlite_last_error($db)));
}
//data to be inserted
$cat = ’search’;
$title = ‘yahoo search’;
$sql = “insert into sample (cat, title) values (’$cat’,'$title’)”;
//insert new data
if (!(sqlite_query($db, $sql)))
{
    die(’SQL ERROR: ‘ . sqlite_error_string(sqlite_last_error($db)));
}
else
{
 echo “data entered”;
}

//close
sqlite_close($db);
?>

Create a sqlite database

Tuesday, February 24th, 2009

This example creates a sample sqlite database and populates it with some data

<?php
//Open/Create sqlite db
if (!($db = sqlite_open(’sample.db’)))
{
    die(sqlite_error_string(sqlite_last_error($db)));
}

//create a table and populate with some data
$sql = ”
create table sample (
    id   integer  primary key,
 cat   text not null,
    title text     not null
);

insert into sample (cat, title) values (’programming’,'getphp’);
insert into sample (cat, title) values (’sport’, ‘golf site’);
insert into sample (cat, title) values (’programming’,'java site’);
insert into sample (cat, title) values (’search’,'google’);
“;

//handle failure or success
if (!(sqlite_exec($db, $sql)))
{
    die(’SQL ERROR: ‘ . sqlite_error_string(sqlite_last_error($db)));
}
else
{
    echo ‘Database and table created!’;
}

//tidy things up
sqlite_close($db);
?>

Get MySQL version

Tuesday, February 24th, 2009

<?php
//displays MySQL version
printf (”MySQL client info: %s\n”, mysql_get_client_info());
?>

Connect to a MySQl database using PDO

Wednesday, February 18th, 2009

This example uses the sample database table at http://www.getphp.net/sample-mysql-database/ , the database is called test and the table is also called test.

This will display all of the links and descriptions

<?php
//change these
$user = ‘root’;
$pass = ”;
try
{
 //localhost, test database
    $dbh = new PDO(’mysql:host=localhost;dbname=test’, $user, $pass);
 //table is called test
    foreach($dbh->query(’SELECT * from test’) as $row)
 {
  print “<a href={$row['url']}>{$row['name']}</a> : {$row['desc']}<br/>”;
 }
    $dbh = null;
}
catch (PDOException $e)
{
    print “Error!: ” . $e->getMessage() . “<br/>”;
    die();
}
?>