0% found this document useful (0 votes)
10 views10 pages

22ubc-Php Notes2 v0.3

Uploaded by

sasikala8161
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
10 views10 pages

22ubc-Php Notes2 v0.3

Uploaded by

sasikala8161
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 10

ARRAYS:

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).

PHP Array Types:

Indexed arrays: Arrays with a numeric index. Index starts at 0

Associative arrays: Arrays with named keys.

Creating Indexed Arrays:


We can create an array using the array() construct. For example, the statement:

$fruitBasket = array(‘apple’, ‘orange’, ‘banana’, ‘pear’);


Or
$fruitBasket = array(0 => ‘apple’, 1 => ‘orange’, 2 => ‘banana’, 3 => ‘pear’);

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’;

Creating Associative Arrays:


To create associative arrays, supply key/value pairs separated by commas, where the key and value
are separated by the special symbol =>.
$fruitBasket = array(‘red’ => ‘apple’, ‘orange’ => ‘orange’, ‘yellow’ => ‘banana’, ‘green’ =>
‘pear’);
The above array is indexed by color names rather than numbers. To recover the name of the yellow
fruit, for example, we just evaluate the expression:
$fruitBasket[‘yellow’] // will be equal to ‘banana’
Array Iteration:
foreach statement
The foreach statement is used to iterate over elements in an array.

The general format is

foreach( $arrayname as $valuename )


{
block of statements;
}

Alternate format of foreach statement


foreach( $arrayname as $keyname => $valuename )
{
block of statements;
}

 arrayname: The name of the array to walk through.


 keyname: The name of the variable where we want to store the key.
 valuename: The name of the variable where we want to store the value.

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.

Function definition syntax


Function definitions have the following form:
function functionName ($argument1, $argument2, ..)
{
statement1;
statement2;
...
}
Function definitions have four parts:
 The special keyword word function
 The name of the function. Function name is not case sensitive.
 The function’s parameter list — dollar-sign variables separated by commas
 The function body — a brace-enclosed set of statements

Function to add two numbers:


<?php
function sum($a,$b)
{
$c = $a + $b;
echo “The sum of $a and $b is $c”;
}

$Val1 = (int)readline(' Enter the first number : ');


$Val1 = (int)readline(' Enter the second number : ');
sum($Val1,$Val2);
?>

*******************************************************************************
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.

Creating a database in MYSQL


The syntax of creating a database in MYSQL is:
create database if not exists databasename;
For example, the following command creates a database called sxc.
create database if not exists sxc;

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

A whole record is obtained using the wildcard (asterisk) symbol:


SELECT * FROM student

The syntax for selecting specific records is:


SELECT * from tableName where condition

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

The WHERE clause specifies which record or records should be updated. If


WHERE clause is omitted, all records will be updated.
Example:
UPDATE student SET city='chennai' WHERE regNo= ‘22UBC500’

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

Return Value: TRUE on success, FALSE on failure.

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.

Return Value: Returns an error code value. Zero if no error occurred

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");

if (isset($_POST['RegNo']) && isset($_POST['Name']) && isset($_POST['Gender']) &&


isset($_POST['Email']) && isset($_POST['Mobile']))
{
$RegNo = $_POST['RegNo'];
$Name = $_POST['Name'];
$Gender = $_POST['Gender'];
$Email = $_POST['Email'];
$Mobile = $_POST['Mobile'];
$id = $_POST['Id'];
$query = "INSERT INTO bcom VALUES('$id', '$RegNo', '$Name', '$Gender', '$Email',
'$Mobile')";
$result = mysqli_query($conn,$query);
echo "Affected Rows : " . mysqli_affected_rows($conn);
if(mysqli_connect_errno())
{
echo " Failed : " . mysqli_connect_error();
exit();
}
}

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;

$query = "SELECT * FROM bcom";


$result = mysqli_query($conn,$query);
$rows = mysqli_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);

echo <<<_END
<pre>
RegNo $row[1]
Name $row[2]
Gender $row[3]
Email $row[4]
Mobile $row[5]
</pre>
_END;
}

$result->close();
$conn->close();
?>

You might also like