|
This section will show you how to interact with MySQL database using PHP language. Beside the code below you need to know PHP's built-in functions for MySQL by access the following url:
http://www.php.net/manual/en/ref.mysql.php
Build a connection
<?php
$conn = mysql_connect("localhost", "username", "password")
or die("Could not connect to MySQL");
mysql_select_db("DBName", $conn) or die("Could not select database");
?>
Retrieve data from database
$sql = "SELECT username FROM users
WHERE username='username' and password='password'";
$result = mysql_query($sql, $conn);
$recordSelected = mysql_num_rows($result);
if($result){
$username = mysql_result($result, 0, "username");
...
}
Add new record
The following code show how to build an insert statement and interact with MySQL, and how to retrieve the number of record inserted.
$sql = "INSERT INTO users (username, password) VALUES('Ruby', 'r0012')";
$result_id = mysql_query($sql, $conn);
$addedRecord = mysql_affected_rows($result_id);
Update record
The following code show how to build an update statement and interact with MySQL, and how to retrieve the number of record updated.
$sql = "UPDATE users SET password='rNewPwd' WHERE username='Ruby'";
$result_id = mysql_query($sql, $conn);
$updatedRecord = mysql_affected_rows($result_id);
Delete record
The following code show how to build an delete statement and interact with MySQL, and howto retrieve the number of record deleted.
$sql = "DELETE FROM users WHERE username='Ruby'";
$result_id = mysql_query($sql, $conn);
$deletedRecord = mysql_affected_rows($result_id);
Close connection
Don't forget the following line to make the code complete.
mysql_close($conn); |