Unit3 PHP
Unit3 PHP
DATATYPE ATTRIBUTES
1. AUTO_INCREMENT
▪ The auto increment attribute is used to assign unique integer identifier to newly inserted
rows.
▪ It increments the field value by value when a new row is inserted.
▪ The auto increment mostly used with primary key.
2. DEFAULT
▪ The DEFAULT attribute ensures that some constant value will be assigned when no
othervalue is available.
▪ This value must be constant because MYSQL does not allow functional or expressional
valuesto be inserted.
▪ If the NULL attribute has been assigned to this value the default value will be NULL and if
nodefault is specified.
3. NULL
▪ The null attribute indicates that no value can exist for the given field .
▪ The NULL attribute is assigned to a field by Default.
4. NOT NULL
▪ If a column is defined as not null than one cannot insert a null value for this column.
5. PRIMARY KEY
▪ Keyword PRIMARY KEY is used to define a column as primary key.
▪ It is used guarantee uniqueness for a given row. one cannot insert null values for the primary
key column.
▪ There are two other values to ensure a record uniqueness.
o Single-field primary keys: are used when there is a non-modifiable unique
identifier for each row entered into the database. They are never changed once set.
o Multi-field primary keys: are useful when it is not possible to guarantee
uniqueness from any single field with a record. Thus, multiple fields are joined to
ensure uniqueness.
6. UNIQUE
▪ A column assigned the UNIQUE attribute will ensure that all values possess different
values,except than NULL values are repeatable.
7. ZEROFILL
▪ It is available to any of the numeric type and will result in the replacement of all
remainingfield space with zero.
▪ When used in conjunction with the optional (nonstandard) attribute ZEROFILL, the
defaultpadding of spaces is replaced with zeros.
▪ For example, for a column declared as INT(4) ZEROFILL, a value of 5 is
retrievedas 0005.The ZEROFILL attribute is ignored when a column is involved in
expressions.
8. INDEX
▪ Indexing a column creates a sorted array of key for that column .each of which points to its
corresponding table row.
▪ By creating index the searching will become faster.
9. BINARY
▪ The binary attribute is only used with char and varchar values when columns are
assignedthis attributes they will be stored in case sensitive manner,(According to their ASCII
value)
DATABASE FUNCTIONS
Function Description
mysql_connect() Opens a new connection to the MySQL server
mysql_close() Closes a previously opened database connection
mysql_select_db() Selects the default database for database queries
mysql_query() Performs a query on the database
mysql_affected_rows() Returns the number of affected rows in the previous MySQL
operation
mysql_error() Returns the last error message for the most recent MySQL function
call
mysql_fetch_array() Fetches a result row as an associative, a numeric array, or both
mysql_free_result() Frees the memory associated with a result
mysql_num_rows() Returns the number of rows in a result set
mysql_fetch_row() Fetches one row of data from the result set and returns it as an
enumerated array
mysql_fetch_assoc() Fetches a result row as an associative array
mysql_result() Retrieves the content of one cell(field)
mysql_fetch_object() Returns row from a result set as an object
MYSQL_CONNECT()
• The mysql_connect() function opens a new connection to the MySQL server.
•It creates a connection to a MySQL server. This function takes three parameters and
returns a MySQL link identifier on success or FALSE on failure.
SYNTAX:
resource mysql_connect(string hostname, string username, string password);
Parameter Description
Hostname/server Optional - The host name running database server. If not
specified, then default value is localhost:3036.
Username Optional - The username accessing the database. If not specified,
then default is the name of the user that owns the server process.
Password Optional - The password of the user accessing the database. If
not specified, then default is an empty password.
EXAMPLE :
<?php
$conn = mysql_connect("localhost", "root", "") or die("ERROR: Could not connect. ");
// ....some PHP code...
?>
MYSQL_CLOSE()
• The mysql_close() function is used to close an open MySQL connection.
• The link to the MySQL server is closed when the script is terminated.
• It takes one argument which is the resource of the database. If the connection is not
specified as a parameter within the mysql_close(), the last opened link is used.
• If a resource parameter is not specified then last opened database is closed. This function
returns true if it closes connection successfully otherwise it returns false.
SYNTAX:
bool mysql_close ( [resource $link] );
Parameter Description
Link Required. Specifies the MySQL connection link to close .
EXAMPLE
<?PHP
$conn=mysql_connect("localhost","root","") die("ERROR: Could not connect. ");
// ....some PHP code...
Mysql_close($conn)
?>
MYSQL_SELECT_DB()
• It is used to select a database.
• It returns true on success and false on failure ,the name of the database as an argumentand
the resource name is optional.
SYNTAX:
bool mysql_select_db( String $databasename,[,resource $link]);
Parameter Description
Databasename/db_name Required - MySQL Database name to be select.
Link/connection Optional - name of the mysql connection. If not
specified, then last opened connection by
mysql_connect() will be used.
EXAMPLE:
<?php
$conn=mysql_connect("localhost","root"," ") or die("ERROR: Could not connect. ");
mysql_select_db("Employee",$conn) or die("ERROR: Could not find database. ");
MYSQL_QUERY()
• The mysql_query() function executes a query on a MySQL database connection.
• It sends the query to the currently active database on the server. It takes two arguments.
one is the query and the other is the resource which is optional.
• This function returns the query handle for SELECT queries, TRUE/FALSE for other
queries,or FALSE on failure.
SYNTAX:
resource mysql_query ( String $query [, resource $link] )
Parameter Description
Query Required. Specifies the SQL query to send (should not end with a
semicolon)
Link/connection Optional. Specifies the MySQL connection. If not specified, the
lastconnection opened by mysql_connect() or mysql_connect() is
used.
<?php
$link=mysql_connect("localhost","root","") or die("ERROR: Could not connect. ");
//open connection
mysql_select_db("Employee",$conn) or die("ERROR: Could not find database.");
//selects a database Employee
<?php
$conn=mysql_connect("localhost","root","") or die("ERROR: Could not
connect. ");
mysql_select_db("Employee",$conn) or die("ERROR: Could not find
database. ");
mysql_query("Update emp_per set name='Raj' where eno=101",$conn) or
die("ERROR: Could not updated. ");
//Update in to emp_per table
mysql_close($conn);
//close a connection
?>
<?php
$conn=mysql_connect("localhost","root","") or die("ERROR: Could not connect. ");
mysql_select_db("Employee",$conn) or die("ERROR: Could not find database. ");
mysql_query("delete from emp_per where rollno=101",$conn) or die("ERROR: Could
notdeleted. ");
//delete from student table
mysql_close($conn);
?>
MYSQL_NUM_ROWS
• This function Retrieves the number of rows from a result set. This command is only
validfor statements like SELECT or SHOW that return an actual result set.
• Resultset will be the array that is returned by mysql_query() when used with select.
Thisfunction returns False on failure.
SYNTAX:
int mysql_num_rows ( resource result )
Example:
<?php
$conn=mysql_connect("localhost","root","") or die("ERROR: Could not connect.);
mysql_select_db("Employee",$conn) or die("ERROR: Could not find
database. ");
$query="select * from emp_per";
$resultset=mysql_query($query,$conn);
$r=mysql_num_rows($resultset);
echo "<br>Rows: ".$r;
//$r contains total no. of rows in a resultset
mysql_close($conn);
?>
This command is only valid for statements like SELECT that return an actual statment.To
retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE
query,use mysql_affected_rows()
MYSQL_AFFECTED_ROWS()
•The mysql_affected_rows() function is used to get the number of affected rows by the last
MySQL query.
• If you run a mysql query to insert, update, replace or delete records, and want to know how
many records are being affected by that query, you have to use mysql_affected_rows().
• This function returns the number of affected rows on success, or -1 if the last operation
failed.
SYNTAX:
int mysql_affected_rows ( [resource $link] )
Parameter Description
Link/connection Optional. Specifies the MySQL connection. If not specified, the
lastconnection opened by mysql_connect() is used.
EXAMPLE:
<?php
$link=mysql_connect("localhost","root","") or die("ERROR: Could not connect.
");
mysql_select_db("Employee",$conn) or die(mysql_error());
mysql_query("delete from emp_per where rollno=101",$conn) or die(mysql_error());
$r=mysql_affected_rows();
echo "<br>Deleted Records Are: ".$r;
//Prints total no. of rows deleted
mysql_close($link);
//close a connection
?>
MYSQL_FETCH_ARRAY()
• This function fetches rows from the mysql_query() function and returns an array on
success .or false on failure or when there are no more rows.
• Array may be an associative array, a numeric array, or both.
• It moves the internal data pointer ahead.
SYNTAX:
array mysql_fetch_array ( resource $resultset [, int $result_type=MYSQL_BOTH] )
Name Description
resultset Refers to the resource return by a valid mysql query
(calling by mysql_query() function).
resultset_type The type of the result is an array.
Possible values :
MYSQL_ASSOC - Associative
array MYSQL_NUM - Numeric
array MYSQL_BOTH - Both and numeric array
associative
Default : MYSQL_BOTH
<?php
$link=mysql_connect("localhost","root","") or die("ERROR: Could not connect. ");
mysql_select_db("college",$conn) or die("ERROR: Could not find database. ");
$resultset=mysql_query("select * from emp_per",$conn) or die(mysql_error());
while($row=mysql_fetch_array($resultset))
{
echo $row[0]."-".$row[1]."<br>";
}
mysql_free_result($resultset); mysql_close($conn);//close a connection
?>
MYSQL_FREE_RESULT()
• The mysql_free_result() function frees memory used by a resultset handle. mysql_free_result()
only needs to be called if you are concerned about how much memory is being used for queries
that return large result sets.
• All associated result memory is automatically freed at the end of the script's execution. This
function returns TRUE on success, or FALSE on failure.
SYNTAX:
bool mysql_free_result ( resource $resultset )
Example:
<?php
$conn=mysql_connect("localhost","root","") or die("ERROR: Could not
connect. ");
mysql_select_db("Employee",$conn) or die("ERROR: Could not find database.
");
$resultset=mysql_query("select * from emp_per",$conn) or die(mysql_error());
while($row=mysql_fetch_array($resultset))
{
echo $row[0]."-".$row[1]."<br>";
}
mysql_free_result($resultset);
mysql_close($conn);
?>
MYSQL_RESULT()
• The mysql_result() function returns the value of a field in a result set. This
functionreturns the field value on success, or FALSE on failure.
• Iit requires three arguments: first is the result set, second will be the row number and
third is optional argument which is the field. Its default value is zero.
SYNTAX:
String mysql_result ( resource $resultset, int $row [, mixed $field=0] )
Name Description
resultset Refers to the resource return by a valid mysql query (calling by
mysql_query()).
Row The row number from the result that's being retrieved. Row numbers
start at 0.
Field The name or position of the field being retrieved.
EXAMPLE:
<?php
$conn=mysql_connect("localhost","root","") or die("ERROR: Could not
connect. ");
mysql_select_db("Employee",$conn) or die("ERROR: Could not find database.
");
$resultset=mysql_query("select * from emp_per",$link) or die(mysql_error());
echo mysql_result($resultset,2);//Outputs third student's rollno
echo mysql_result($resultset,2,1);//Outputs third student's name
mysql_close($conn);//close a connection
?>
MYSQL_ERROR()
• The mysql_error() function returns the error description of the last MySQL operation.
• This function returns an empty string ("") if no error occurs.
SYNTAX:
String mysql_error ( [resource $link] )
Parameter Description
$link Optional. Specifies the MySQL connection. If not specified, the
lastconnection opened by mysql_connect()is used.
EXAMPLE:
<?php
$conn=mysql_connect("localhost","root","") or die("ERROR: Could not
connect. ");
if(!$conn)
{
die(mysql_error());
}
mysql_close($conn);
?>
MYSQL_FETCH_ROW()
• The mysql_fetch_row() function returns a row from a resultset as a numeric array.
• This function gets a row from the mysql_query() function and returns an array
onsuccess, or FALSE on failure or when there are no more rows.
SYNTAX:
array mysql_fetch_row ( resource $resultset )
Name Description
resultset Refers to the resource return by a valid mysql query (calling by
mysql_query() function).
EXAMPLE:
<?php
$link=mysql_connect("localhost","root","") or die("ERROR: Could not connect. ");
mysql_select_db("Employee",$conn) or die("ERROR: Could not
find database. ");
$resultset=mysql_query("select * from emp_per",$conn) or die(mysql_error());
while($row=mysql_fetch_row($resultset)
{
echo $row[0]; //returns 1st record's first column value
echo $row[1]; //returns 1st record's second column value
}
mysql_close($conn);//close a connection
?>
MYSQL_FETCH_OBJECT()
• The mysql_fetch_object() function returns a row from a resultset as an object.
• This function gets a row from the mysql_query() function and returns an object on
success, or FALSE on failure or when there are no more rows.
SYNTAX:
object mysql_fetch_object ( resource $resultset )
Name Description
Resultset Refers to the resource return by a valid mysql query (calling by
mysql_query() function).
EXAMPLE:
<?php
$conn=mysql_connect("localhost","root","") or die("ERROR: Could not
connect. ");
mysql_select_db("Employee",$conn) or die("ERROR: Could not find database.
");
$query="select * from emp_per";
$resultset=mysql_query($query,$conn);
$while($row=mysql_fetch_object($resultset)
{
echo $row->rollno."<br/>";
}
mysql_close($conn);
?>
MYSQL_FETCH_ASSOC()
• The mysql_fetch_assoc() used to retrieve a row of data as an associative array from a
MySQL result handle.
• It Returns an associative array that corresponds to the fetched row and moves the
internal pointer ahead, or FALSE if there are no more rows.
SYNTAX:
array mysql_fetch_assoc ( resource $resultset )
Name Description
resultset Refers to the resource return by a valid mysql query (calling by
mysql_query() function).
EXAMPLE:
<?php
$conn=mysql_connect("localhost","root","") or die("ERROR: Could not
connect. ");
mysql_select_db("Employee",$conn) or die("ERROR: Could not find database.
");
$resultset=mysql_query("select * from emp_per",$link) or die(mysql_error());
while($row=mysql_fetch_assoc($resultset))
{
echo $row['rollno']."<br>";
echo $row['name']."<br>";
}
mysql_free_result($resultset);
mysql_close($conn);
?>
mysql_num_fields()
This function returns number of fields in result set or success , or FALSE on failure.
SYNTAX:
int mysql_num_fields ( resource $resultset )
IT EXAMPLE:
<?php
$conn=mysql_connect("localhost","root","") or die("ERROR: Could not
connect. ");
mysql_select_db("Employee",$conn) or die("ERROR: Could not find database.
");
$resultset=mysql_query("select * from emp_per",$link) or die(mysql_error());
echo "Total fields are:".mysql_num_fields($resultset);
mysql_close($conn);
?>
ORDER BY
•
The order by keyword is used to sort the data in result set.
• The order by keyword sorts the record in ascending order by default in order to sort
record is descending order you can use DESC keyword.
SYNTAX:
SELECT column_name(s)
This example selects all the records stored in the student table and sorts them byage
column.
Database:Employee
Table: Emp_per(eno,ename,age)
Example:
<?php
$conn=mysql_connect("localhost","root","") or die("ERROR: Could not
connect. ");
mysql_select_db("Employee",$conn) or die("ERROR: Could not find database.
");
$resultset=mysql_query("select * from emp_per order by age",$conn) or
die(mysql_error());
while($row=mysql_fetch_array($resultset))
{
echo $row[0]. $row[1]. $row[2].<br>";
}
mysql_free_result($resultset);
mysql_close($conn);
?>
•
It is also possible to order by more than one column.
When ordering by more than one column the 2nd column is only used the values in the
•
1stcolumn are equal.
SYNTAX:
SELECT column_name(s)
FROM table_name Order by column1,column2
WHAT IS AJAX?
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data
with the server behind the scenes. This means that it is possible to update parts of a web
page, without reloading the whole page.
Code explanation:
First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint
placeholder and exit the function.
Ajaxcall.php
<html>
<head>
<script>
function showUser(str)
{
if (str == "")
{
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
//true for asynchronous data
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Raj</option>
<option value="2">Radha</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
<?php
$q = $_GET['q'];
$con = mysql_connect("localhost","root","");
mysql_select_db("studend",$con);
$result = mysql_query("SELECT * FROM stud_per WHERE sno='$q'",$con);
echo "<table>
<tr>
<th>Firstname</th>
<th>City</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['sno'] . "</td>";
echo "<td>" . $row['city'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
</body>
</html>
• A variable xmlhttp is declared. Then, a new XMLHttpRequest object is created. If a your
target audience use browsers older than Internet Explorer 8, ActiveXObject is used to
create XMLHttpRequest.
• 'onreadystatechange' is a property of XMLHttpRequest object which is called whenever
'readyState' attribute is changed.
• We check whether the value of the 'readyState' property is 4, which denotes that the
operation is complete.
• If the operation is completed, the status of the response to the request is checked. It
returns the HTTP result code. Result code 200 states that the response to the request is
successful.
• Now we set the value of the string to be displayed within the div whose id is 'suggestion'
as 'responseText' property of the XMLHttpRequest object. 'responseText' is the response
to the request as text.
• By using 'open' method of XMLHttpRequest object, a new request to the server is
initialized. There are three parameters passed by this method. 'POST' determines the
type of the httprequest. 'book-suggestion.php' sets the server side file and setting the third
parameter 'true' states that the request should be handled asynchronously.
• 'send' method is used to send data contained in the 'data' variable to the server.