|
PHP and MySQL
Manipulate a MySQL Database
1. Access a MySQL database with PHP code
<?
$con=mysql_connect("ServerName","Username","Password");
$db=mysql_select_db("DatabaseName","Connection Idenfier");
// Server name is the name of server that you are working on 99% it is "localhost"
// Username is the name of user of mysql database
// Password is the password of mysql database
// Database Name is the name of database that you created in mysql
?>
2. Reading records from a MySQL database
<?
$con=mysql_connect("localhost","root","mypass");
$db=mysql_select_db("mydb",$son);
$result=mysql_query("Select * from myTable") or die(mysql_error());
while($row=mysql_fetch_array($result))
{
echo $row["fieldName"]."<br>";
echo $row["fieldName2"]."<br>";
}
// mysql_query() used to execute the sql
// die() If some error occur than this function triggers
// mysql_error() Shows mysql error
// mysql_fetch_array() gets the records in an array
// mysql_num_rows() returns the number of rows found
?>
3. Adding records to a MySQL database
<?
mysql_query("Insert into myTable set fieldName='Test Value',fieldName2='Test Value2' ");
// This will insert a record to myTable
// mysql_insert_id(); If an autoincremnet field is set in table than it returns the id of last entered record.
// mysql_affected_rows() Returns the number of rows affected by Add,Delete and Updat operation
?>
4. Updating a record in a table
<?
mysql_query("Update myTable set fieldName='Test Value',fieldName2='Test Value2' where id='1' ");
?>
5. Deleting a record in a table <?
mysql_query("delete from myTable where id='1' ");
?>
6. Using WHERE to limit the data returned
<?
mysql_query("select * from myTable where id='1' ");
?>
|