22ubc-Php Notes2 v0.3
22ubc-Php Notes2 v0.3
An array is a data structure that stores many values in a single name. We can access the array values
by using an index or a name (key).
causes the variable $fruitBasket to be assigned to an array with four string elements (‘apple’,
‘banana’, ‘orange’, ‘pear’), with the indices 0, 1, 2, and 3, respectively
The assignment to $fruitBasket has exactly the same effect as the following:
$fruitBasket[0] = ‘apple’;
$fruitBasket[1] = ‘orange’;
$fruitBasket[2] = ‘banana’;
$fruitBasket[3] = ‘pear’;
The same effect can be accomplished by omitting the indices in the assignment, like:
$fruitBasket[] = ‘apple’;
$fruitBasket[] = ‘orange’;
$fruitBasket[] = ‘banana’;
$fruitBasket[] = ‘pear’;
For instance, the following foreach statement walks through the sample array of state capitals
and echoes a list:
$fruitBasket = array(‘red’ => ‘apple’, ‘orange’ => ‘orange’, ‘yellow’ => ‘banana’, ‘green’ =>
‘pear’);
foreach( $fruitbasket as $color => $fruit )
{
echo "$fruit is $color color \n ";
}
Output:
apple is red color
orange is orange color
banana is yellow color
pear is green color
*******************************************************************************
Functions
A function is a group of PHP statements that perform a specific task. Functions are designed to allow
to reuse the same code in different locations.
*******************************************************************************
STRING FUNCTIONS
Trim() Returns its string argument with both leading and trailing whitespace removed.
chop(), or rtrim() Returns its string argument with trailing (right-hand side) whitespace removed.
Whitespace is a blank space, \n, \r, \t, and \0.
ltrim() Returns its string argument with leading (left-hand side) whitespace removed
strtolower() Returns an all-lowercase string. It doesn’t matter if the original is all uppercase or
mixed
strtoupper() Returns an all-uppercase string, regardless of whether the original was all lowercase
or mixed
strlen() Takes a single string argument and returns its length as an integer
strcmp() Takes two strings as arguments and returns 0 if the strings are exactly equivalent. If
strcmp() encounters a difference, it returns a negative number if the first different
byte is a smaller ASCII value in the first string, and a positive number if the smaller
byte is found in the second string.
strcasecmp() Identical to strcmp(), except that lowercase and uppercase versions of the same
letter compare as equal.
strpos() Takes two string arguments: a string to search, and the string being searched for.
Returns the (0-based) position of the beginning of the first instance of the string if
found and a false value otherwise. It also takes a third optional integer argument,
specifying the position at which the search should begin.
strrpos() Like strpos(), except that it searches backward from the end of the string, rather
than forward from the beginning. The search string must only be one character long,
and there is no optional position argument.
strstr() Searches its first string argument to see if its second string argument is contained in
it. Returns the substring of the first string that starts with the first instance of the
second argument, if any is found — otherwise, it returns false
*******************************************************************************
PRIMARY KEY
A primary key is a field or group of fields which uniquely identifies a record in a table. For
example, in a student table, the student’s register number can be set as a primary key. It
uniquely identifies each student.
SQL WORKHORSES
SELECT
SELECT is the main command to get information out of a SQL database. The basic
syntax is:
SELECT field1, field2, field3 FROM table
Example:
SELECT regNo, name, email from student
Example:
SELECT * from student where city = “Palay”
INSERT
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO tableName (column1, column2, column3,...) VALUES (value1,
value2, value3,...)
Example:
INSERT INTO MyGuests(id,firstname,lastname,email,reg_date)
values(‘1’‘Sachin’,’Tendulkar’,’sachin@gmail.com’,12-09-1999)
UPDATE:
The UPDATE statement is used to update existing records in a table:
UPDATE tableName SET column1=value, column2=value2,... WHERE
someColumn=someValue
DELETE:
The DELETE statement is used to delete records from a table:
DELETE FROM tableName WHERE someColumn = someValue
The WHERE clause specifies which record or records should be deleted. If WHERE
clause is omitted, all records will be deleted!
Example:
DELETE FROM student WHERE regNo=‘22UBC500’
ALTER:
The ALTER TABLE statement is used add or drop various constraints on an existing
table.
ALTER TABLE tableName ADD columnName dataType
ALTER TABLE tableName DROP COLUMN columnName
ALTER TABLE tableName MODIFY COLUMN columnName dataType
Examples:
ALTER TABLE customers ADD Email varchar(20)
ALTER TABLE customers MODIFY COLUMN Email varchar(100)
ALTER TABLE customers DROP COLUMN Email
*******************************************************************************
MYSQLI FUNCTIONS
mysqli_connect(host, username, password, dbname, port, socket);
Description:
Opens a new connection to the MySQL server.
Parameter Values:
host: Specifies the host name or an IP address
username: Specifies the MySQL user name
password: Specifies the MySQL password
dbname: Specifies the default database to be used
port: Specifies the port number to attempt to connect to the MySQL server
socket: Specifies the socket or named pipe to be used.
All arguments are optional.
Return Value: Returns an object representing the connection to the MySQL server
Example:
mysqli_connect(‘localhost’, ‘root’, ‘’, ‘testdb’);
mysqli_select_db(connection, dbname)
Description:
Used to change the default database for the connection.
Parameter Values:
connection: Specifies the MySQL connection to use.
dbname: Specifies the database name
Example:
mysqli_select_db($connection, “testdb”);
mysqli_query(connection, query, resultmode)
Description:
Used to change the default database for the connection.
Parameter Values:
connection: Specifies the MySQL connection to use.
query: Specifies the SQL query string
resultmode: Optional. MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT
Return Value: For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries it will
return a mysqli_result_object. For other successful queries it returns TRUE, FALSE on failure.
Example:
$result = mysqli_query($connection, “SELECT * FROM Student”);
echo “Returned rows are : “ . mysqli_num_rows($result);
mysqli_connect_errno()
Description:
Returns the error code from the last connection error.
Example:
if(mysqli_connect_errno()) {
echo “Failed : “ . mysqli_connect_error();
exit();
}
mysqli_connect_error()
Description:
Returns the error description from the last connection error.
Return Value: Returns a string that describes the error. NULL if no error occurred
Example:
if(mysqli_connect_erorno()) {
echo “Failed : “ . mysqli_connect_error();
exit();
}
mysqli_affected_rows(connection)
Description:
Returns the number of affected rows in the previous SELECT, INSERT, UPDATE or DELETE
query.
Parameter Values:
connection: Specifies the MySQL connection to use.
Return Value: The number of rows affected. -1 indicates that the query returned an error.
Example:
mysqli_query($con, “SELECT * from Students”);
echo “Affected Rows : “ . mysqli_affected_rows($con);
mysqli_num_rows(result)
Description:
Accepts a result object and returns the number of rows in the given result.
Parameter Values:
result: An identifier representing the result object.
Return Value: Returns an integer value representing the number of rows/records in the
given result object.
Example:
$result = mysqli_query($con, “SELECT * from Students”);
$count = mysqli_num_rows($result);
echo “Number of rows in the result : “ . $count;
PHP program to edit data with an HTML form.
<?php // Test3.php
$conn = mysqli_connect("localhost", "root","","sxc");
echo <<<_END
<form action="Test3.php" method="post"><pre>
ID <input type="text" name="Id">
RegNO <input type="text" name="RegNo">
Name <input type="text" name="Name">
Gender <input type="text" name="Gender">
Email <input type="email" name="Email">
Mobile <input type="text" name="Mobile">
<input type="submit" value="ADD RECORD">
</pre></form>
_END;
echo <<<_END
<pre>
RegNo $row[1]
Name $row[2]
Gender $row[3]
Email $row[4]
Mobile $row[5]
</pre>
_END;
}
$result->close();
$conn->close();
?>