
PHP code snippets:
PHP is one of the most used server side scripting languages these days. It is very popular to mix PHP with MySQL and other databases, to get an easy to maintain and easy to make web page that looks professional. PHP has many similarites to Python, and it is therefor easy to mix up syntax between the languages. So here is some often used codesnippets to copy paste, so remember the syntax won't be that necessary.-> Getting information from a MySQL database
-> Insert/Update/Delete records in a MySQL database
-> Getting the name of a random picture in a folder
-> Simple counter for your home page
Getting information from a MySQL database:
001: //Lets say we have a MySQL table called "costumer" that looks like this:
002: //ID, FirstName, LastName, Phone
003:
004:
005: // Just get all the fields in the table.
006: $result = mysql_query("SELECT ID, FirstName, LastName, Phone FROM costumer");
007:
008: // Same result, just less to write.
009: $result = mysql_query("SELECT * FROM costumer");
010:
011:
012: // Sort the entries alphabeticaly on last names.
013: $result = mysql_query("SELECT ID, FirstName, LastName, Phone FROM costumer ORDER BY LastName ASC");
014:
015: // Limit the results to 10 results.
016: $result = mysql_query("SELECT ID, FirstName, LastName, Phone FROM costumer LIMIT 0, 9");
017:
018: // Limit from min number to max number.
019: $result = mysql_query("SELECT ID, FirstName, LastName, Phone FROM costumer LIMIT " . $min_number . ", " . $max_number . "");
020:
021:
022: // Select with a condition.
023: $result = mysql_query("SELECT ID, FirstName, LastName, Phone FROM costumer WHERE LastName = `Smith`");
024:
025: // When the condition is a variable.
026: $result = mysql_query("SELECT ID, FirstName, LastName, Phone FROM costumer WHERE LastName = `".$Name."` ");
027:
028:
029:
030:
031: //for more help:
032: //http://www.tizag.com/mysqlTutorial/mysqlquery.php
Insert/Update/Delete records in a MySQL database:
001: //Lets say we have a MySQL table called "costumer" that looks like this:
002: //ID, FirstName, LastName, Phone
003:
004:
005: // Insert a new record.
006: $query = mysql_query("INSERT INTO costumer VALUES(``, `$FirstName`, `$LastName`, `$Phone`)");
007:
008: // Update an already existing record. Add the primary key, and change the other atributes as you want.
009: $query = mysql_query("REPLACE INTO costumer VALUES(`$old_id`, `$new_first_name`, `$new_last_name`, `$new_number`)");
010:
011: // Delete an already existing record. You can do any matching here as you want. See "Select records"
012: $query = mysql_query("DELETE FROM costumer WHERE ID=`15`")
013:
014:
015: //for more help:
016: //http://www.tizag.com/mysqlTutorial/mysqlquery.php