The document discusses connecting to and interacting with a MySQL database from PHP, including connecting to MySQL, creating databases and tables, inserting, updating, and deleting data. Key points covered are using mysql_connect() to connect to MySQL, mysql_query() to execute queries like CREATE, INSERT, UPDATE and DELETE, and retrieving and displaying form data submitted from PHP to insert new records.
2. Connecting to MYSQL mysql_connect(servername,username,password); <?php $con=mysql_connect('localhost','root',''); if (!$con) { die('Could not connect: ' . mysql_error()); } ?>
3. Creating a MYSQL Database CREATE DATABASE database_name <?php $con = mysql_connect('localhost', 'root', ''); if (!$con) { die('Could not connect: ' . mysql_error()); } if (mysql_query('CREATE DATABASE my_db',$con)) { echo "Database 'my_db' created"; } else { echo "Error creating database: " . mysql_error(); } mysql_close($con); ?>
4. Creating a MYSQL Table CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, ....... ) <?php $con = mysql_connect('localhost', 'root', ''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db('my_db', $con); $sql = 'CREATE TABLE person ( FirstName varchar(15), LastName varchar(15), Age int )'; mysql_query($sql,$con); mysql_close($con); ?>
5. Insert Using PHP Inserting data to MySQL is done by using mysql_query() to execute INSERT command. Note that the query string should not end with a semicolon. Below is an example of adding a new MySQL person by inserting a new row into table person in database “my_db” <?php $con = mysql_connect('localhost', 'root', ''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db('my_db', $con); $query = 'INSERT INTO person (Firstname, Lastname, Age) VALUES ("Jesus", "Christ", 33)'; mysql_query($query) or die('Error, insert query failed'); mysql_close($con); ?>
6. Insert Using FORMS and PHP <?php if(isset($_POST['add'])){ $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = ''; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); $dbname = 'my_db'; mysql_select_db($dbname); $CFName = $_POST['CFName']; $CSName = $_POST['CSName']; $CAge = $_POST['CAge']; $query = $query = "INSERT INTO person (Firstname, Lastname, Age) VALUES ('$CFName', '$CSName', $CAge)"; mysql_query($query) or die('Error, insert query failed'); mysql_close($conn); echo "person added to database"; } else{ ?>
8. Data Update Using PHP Use mysql_query() to execute the UPDATE or DELETE statement. For instance, to update the age in a MYSQL table for name “Jesus”, execute an UPDATE statement with mysql_query() like this: <?php $con = mysql_connect('localhost', 'root', ''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db('my_db', $con); $query = 'UPDATE person SET Age = (55) WHERE Firstname = "Jesus"'; mysql_query($query) or die('Error, insert query failed'); mysql_close($con); ?>