10/23/2012

connect mysql based on PHP

Before we use MySQL, we should create instance for MySQL. Now I give one example based on PHP source code.

Based on classic ways
1. connect MySQL

$link = mysql_connect("localhost", "root", "abc123456");
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

2. Select database
mysql_select_db("test_db", $link);

3. Execute select, update, insert .....


$result = mysql_query('SELECT email, name, pass FROM users ');
while ($row = mysql_fetch_assoc($result)) {
    var_export($row);
}


4. Close MySQL
mysql_close($link);

Based on Security ways

1. connect MySQL
$link = new PDO('mysql:host=localhost;dbname=test_db', 'root', 'abc123456');

2. Execute select, update, insert .....
$sth = $pdo->query('SELECT email, name, pass FROM users');
foreach($sth as $row) {
    var_export($row);
}

No comments:

Post a Comment