Entries by admin

foreach loop

April 6, 2011 | Filed Under Control Structures, PHP Tutorial | Leave a Comment

The foreach loop is used to loop through arrays.

Syntax:

foreach ($array as $value)
{
code to be executed;
}

foreach ($array as $key => $value)
{
code to be executed;
}

For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) – so on the next loop iteration, you’ll be looking at the next array value.

Example1:
Code:

$arr = array(4,6,8,10);
foreach ($arr as &$value) {
    $value = $value * 3;
	echo $value;
}

Output:

12 18 24 30

Example2:
Code:

 &$value) {
   $value = $value * 3;
	echo "key: $key, value: $value ";
}

Output:

key: 0, value: 12
key: 1, value: 18
key: 2, value: 24
key: 3, value: 30

Article written by admin

for Loop

April 6, 2011 | Filed Under Control Structures, PHP Tutorial | Leave a Comment

The for loop is used when you know how many times the code should run.

Syntax:

for (init; condition; increment)
{
code to be executed;
}

Description:

The first argument “init” Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop)

The second argument “condition” Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.

The third argument “increment” Mostly used to increment a counter (but can be any code to be executed at the end of the loop)

Each of the expressions can be empty or contain multiple expressions separated by commas.

Example1:
Code:

for ($i = 2; $i <= 6; $i++)
 {
    echo $i;
}

Output:

2 3 4 5 6

Example2:
Code:


for  ($i = 2; ; $i++) {
      if ($i > 6) {
        break;
    }
    echo $i."
"; }

Output:

2 3 4 5 6

Example3:
Code:

$i = 2;
for (; ; ) {
    if ($i > 6) {
        break;
    }
    echo $i."
"; $i++; } Output: 2 3 4 5 6

Example4:
Code:

for ($i = 2, $j = 0; $i <= 6; $j += $i, print $i, $i++);

Output:

2 3 4 5 6

Article written by admin

do…while statement

April 6, 2011 | Filed Under Control Structures, PHP Tutorial | Leave a Comment

The do…while statement will always execute the condition, and repeat the loop while the condition is true.

The main difference from “while loops” is that the first iteration of a do-while loop is guaranteed to run, whereas it’s may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately).

Syntax:

do
{
code to be executed;
}
while (condition);

Example1:
Code:

$i = 0;
do {
    echo $i;
} while ($i > 0);

Output:

0

Example2:
Code:

$i=1;
do
  {
  $i++;
  echo "The number is " .$i . "";
  }
while ($i<=5);

Output:

The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

Article written by admin

while Loop

April 5, 2011 | Filed Under Control Structures, PHP Tutorial | Leave a Comment

It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won’t even be run once.

Syntax:

while (condition)
{
code to be executed;
}
Example:
Code:

$i=1;
while($i<=10)
 {
  echo "The number  is " . $i . "";
  $i++;
  }

Output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

Article written by admin

if….elseif…else statement

April 5, 2011 | Filed Under Control Structures, PHP Tutorial | Leave a Comment

You can use the if….elseif…else statement to select one of several blocks of code to be executed.

Syntax:

if (condition)
{
code to be executed if condition is true;
}
elseif (condition)
{
if condition is true;
}
else
{
code to be executed if condition is false;
}

Example:
Code:

$p=5;
$q=8;
if ($p > $q) {
    echo "p is bigger than ";
} elseif ($p == $q) {
    echo "p is equal to q";
} else {
    echo "p is smaller than q";
}

Output:

p is smaller than q

Article written by admin

if….else statement

April 5, 2011 | Filed Under Control Structures, PHP Tutorial | Leave a Comment

You can use the if….else statement to execute some code if a condition is true and another code if a condition is false.

Syntax:

if (condition)
{
code to be executed if condition is true;

}
else
{
code to be executed if condition is false;
}

Example:
Code:

$p=4;
$q=7;
if ($p > $q) {
    echo "p is bigger than q";
} else {
    echo   "p is NOT bigger than q";
}

Output:

p is NOT bigger than q

Article written by admin

if Statement

April 5, 2011 | Filed Under Control Structures, PHP Tutorial | Leave a Comment

You can use the if statement to execute some code only if a specified condition is true.

Syntax:

if (condition)
{
code to be executed if condition is true;
}

Example:
Code:

$p=5;
$q=3;
if ($p > $q)
    echo "p is bigger than q";

Output:

p is bigger than q

Article written by admin

mysql_list_tables

April 5, 2011 | Filed Under MySQL Functions, PHP Tutorial | Leave a Comment

This function return List of tables in a MySQL database.

Syntax: mysql_list_tables (database, connection)

Description:

The first argument “database” is Required.It specifies the name of the database.

The second argument “connection” is Optional.It specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used.

This function deprecated. It is preferable to use mysql_query() to issue TABLES [FROM db_name] [LIKE 'pattern'] statement instead.

Example:
Code:

$database_name = 'company';

if (!mysql_connect('localhost','mysql_user', 'mysql_password')) {
   echo 'Could not connect to mysql';
    exit;
}

$sql = "SHOW TABLES FROM $database_name";
$result = mysql_query($sql);

if (!$result) {
    echo "DB Error, could not list tables\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_row($result))  {
    echo "Table: {$row[0]}\n";
}

mysql_free_result($result);

Output:

Table: companydata

Article written by admin

mysql_insert_id()

April 5, 2011 | Filed Under MySQL Functions, PHP Tutorial | Leave a Comment

This function returns the AUTO_INCREMENT ID generated from the previous INSERT operation.

Syntax: mysql_insert_id(connection)

Description:

The argument “connection” is Optional. It specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used.

This function returns 0 if the previous operation does not generate an AUTO_INCREMENT ID, or FALSE on
MySQL connection failure.

Example:
Code:

$con = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$con)
   {
  die('Could  not connect:' . mysql_error());
   }

$db_selected = mysql_select_db("company",$con);

$sql = "INSERT INTO companydata VALUES (5,'smith',3000)";
$result = mysql_query($sql,$con);
echo "ID of last inserted record is: " . mysql_insert_id();

mysql_close($con);

Output:

ID of last inserted record is: 5

Article written by admin

mysql_real_escape_string()

April 5, 2011 | Filed Under MySQL Functions, PHP Tutorial | Leave a Comment

This function escapes special characters in a string for use in an SQL statement

The following characters are affected:

* \x00
* \n
* \r
* \
* ‘
* ”
* \x1a

Syntax: mysql_real_escape_string(string,connection)

Description:

The first argument “string” is Required. It specifies the string to be escaped.

The second argument “connection” is Optional. It specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used.

This function returns the escaped string on success, or FALSE on failure.

Example1:
Code:


$connection = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    OR die(mysql_error());

$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
            mysql_real_escape_string($user),
            mysql_real_escape_string($password));

Example2:
Code:


$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);

$_POST['username'] = 'Tom';
$_POST['password']  = "' OR ''='";

echo $query;
Article written by admin

mysql_escape_string()

April 5, 2011 | Filed Under MySQL Functions, PHP Tutorial | Leave a Comment

This function Escapes a string for use in a mysql_query

Syntax: mysql_escape_string (unescaped_string )

Description:

The argument “unescaped_string” is Required.It specifies the string that is to be escaped.

This function will escape the unescaped_string, so that it is safe to place it in a mysql_query(). This function is deprecated.

This function is identical to mysql_real_escape_string() except that mysql_real_escape_string() takes a connection handler and escapes the string according to the current character set. mysql_escape_string() does not take a connection argument and does not respect the current charset setting.

Example:
Code:

$item = "samsung's mobile";
$escaped_item = mysql_escape_string($item);
printf("Escaped string: %s\n", $escaped_item);

Output:

Escaped string: samsung\’s mobile

Article written by admin

mysql_drop_db()

April 5, 2011 | Filed Under MySQL Functions, PHP Tutorial | Leave a Comment

This function Drop (delete) a MySQL database.

Syntax: mysql_drop_db (database_name , connection )

Description:

The first argument “database_name” is Required.It specifies to drop the database.

The second argument “connection” is Optional. It specifies the MySQL connection to close. If not specified, the last connection opened by mysql_connect() is used.

It is preferable to use mysql_query() to issue a sql DROP DATABASE statement instead.

Example:
Code:

$connection = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if  (!$connection) {
    die('Could   not connect: ' . mysql_error());
}

$sql = 'DROP DATABASE library';
if  (mysql_query($sql, $connection)) {
    echo "Database library was successfully dropped\n";
} else {
    echo 'Error dropping database: ' . mysql_error() . "\n";
}

Output:

Database library was successfully dropped

Article written by admin

mysql_stat()

April 5, 2011 | Filed Under MySQL Functions, PHP Tutorial | Leave a Comment

The function returns the current system status of the MySQL server.

Syntax: mysql_stat(connection)
Description:

The argument “connection” is Optional. It specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used.

This function returns status on success, or NULL on failure.

Example:
Code:

$connection = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$connection)
  {
  die('Could not connect: ' . mysql_error());
  }

$db_selected = mysql_select_db("company", $connection);

echo mysql_stat();

Output:

Uptime: 18463 Threads: 1 Questions: 10 Slow queries: 0 Opens: 12
Flush tables: 1 Open tables: 0 Queries per second avg: 0.001

Article written by admin

mysql_pconnect()

April 5, 2011 | Filed Under MySQL Functions, PHP Tutorial | Leave a Comment

This function Open a persistent connection to a MySQL server.

mysql_pconnect() works much like mysql_connect() but with two major differences.

First, when connecting, the function would first try to find a (persistent) link that’s already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, The connection will not be closed when the execution of the script ends (mysql_close() will not close connection opened by mysql_pconnect()). It will stay open for future use

Syntax: mysql_pconnect(server,user,pwd,clientflag)

Description:

The first argument “server” is Optional. It specifies the server to connect to (can also include a port number. e.g. “hostname:port” or a path to a local socket for the localhost). Default value is “localhost:3306″

The second argument “user” is Optional. It specifies the username to log in with. Default value is the name of the user that owns the server process.

The third argument “password” is Optional. It specifies the password to log in with. Default is “”.

The fourth argument “clientflag” Can be a combination of the following constants:

* MYSQL_CLIENT_SSL – Use SSL encryption
* MYSQL_CLIENT_COMPRESS – Use compression protocol
* MYSQL_CLIENT_IGNORE_SPACE – Allow space after function names
* MYSQL_CLIENT_INTERACTIVE – Allow interactive timeout seconds of inactivity before closing the connection

Example:
Code:

$con = mysql_pconnect("localhost","mysql_user","mysql_pwd");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
Article written by admin

mysql_unbuffered_query()

April 4, 2011 | Filed Under MySQL Functions, PHP Tutorial | Leave a Comment

This function Send an SQL query to MySQL, without fetching and buffering the result rows.

Unlike mysql_query(), this function does not fetch and buffer the recordset automatically. This saves some memory with large SQL queries, and you can start working on the result set immediately after the first row has been retrieved.

Syntax: mysql_unbuffered_query(query,connection)

Description:
The first argument “query” is Required. It specifies the SQL query to send (should not end with a semicolon).

The second argument “connection” is Optional. It Specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used.

This function returns the query handle for SELECT queries, TRUE/FALSE for other queries, or FALSE on failure.

Note: The benefits of mysql_unbuffered_query() come at a cost: You cannot use mysql_num_rows() and mysql_data_seek() on a result set returned from mysql_unbuffered_query().

Example:
Code:

$con = mysql_connect("localhost","mysql_user","mysql_pwd");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

$sql = "SELECT  * FROM companydata";

mysql_unbuffered_query($sql,$con);

mysql_close($con);
Article written by admin

mysql_list_processes()

April 4, 2011 | Filed Under MySQL Functions, PHP Tutorial | Leave a Comment

This function return the current MySQL server threads.

Syntax: mysql_list_processes(connection)

Description:

The argument “connection” is Optional. It specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used.

This function returns a result pointer containing the current processes on success, or FALSE on failure

Example:
Code:

$con = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

$my_list = mysql_list_processes($con);
while ($row = mysql_fetch_assoc($my_list))
  {
  print_r($row);
  }

mysql_close($con);

Output:

Array (
[Id] => 2
[User] =>
[Host] =>
localhost:1306
[db] =>
[Command] => Processlist
[Time] => 0
[State] =>
[Info] =>
)

Article written by admin

mysql_get_server_info()

April 4, 2011 | Filed Under MySQL Functions, PHP Tutorial | Leave a Comment

This function return MySQL server information.

Syntax: mysql_get_server_info(connection)

Description:

The argument “connection” is Optional. It specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used.

This function returns the MySQL server version on success, or FALSE on failure.

Example:
Code:

$connection=  mysql_connect('localhost',  'mysql_user', 'mysql_password');
if (!$connection) {
    die('Could not connect: ' . mysql_error());
}
echo("MySQL server version:". mysql_get_server_info());

Output:

MySQL server version:5.0.45-community-nt

Article written by admin

mysql_field_flags()

April 4, 2011 | Filed Under MySQL Functions, PHP Tutorial | Leave a Comment

This function returns the flags of a field in a recordset.

Syntax: mysql_field_flags(data,field_offset)

Description:

The first argument “data” is Required. It specifies which data pointer to use. The data pointer is the result from the mysql_query() function.

The second argument “field_offset” is Required. It specifies which field to start returning. 0 indicates the first field.

This function gets field data from the mysql_query() function and returns a string on success, or FALSE on failure or when there are no more rows.

Possible return values:
* auto_intcrement – 1 if AUTO_INCREMENT is set
* binary – 1 if the field has the BINAR attribute set
* blob – 1 if the field is a BLOB
* enum – 1 if the field is an ENUM field
* multiple_key – 1 if the field is a non-unique key
* not_null – 1 if the field cannot be NULL
* primary_key – 1 if the field is a primary key
* timestamp – 1 if the field is a timestamp field
* unique_key – 1 if the field is a unique key
* unsigned – 1 if the field is unsigned
* zerofill – 1 if the field is zero-filled

Example:
Code:

$con = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

$db_selected = mysql_select_db("company",$con);

$sql = "SELECT * from companydata";
$result = mysql_query($sql,$con);

$flags = mysql_field_flags($result, 0);
echo $flags;

mysql_close($con);

Output:

not_null primary_key

Article written by admin

mysql_fetch_lengths()

April 4, 2011 | Filed Under MySQL Functions, PHP Tutorial | Leave a Comment

This function return the length of each output in a result.

Syntax: mysql_fetch_lengths(data)

Description:

The argument “data” is Required. It specifies which data pointer to use. The data pointer is the result from the mysql_query() function.

The row is retrieved by mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_object(), or mysql_fetch_row().

This function returns a numeric array on success, or FALSE on failure or when there are no more rows.

Example:
Code:

$con = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

$db_selected = mysql_select_db("company",$con);
$sql = "SELECT * from companydata WHERE id=2";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_row($result));
print_r(mysql_fetch_lengths($result));

mysql_close($con);

Output:

Array (
[0] => 2
[1] => aquib
[2] => 6000 )

Array (
[0] => 1
[1] => 5
[2] => 4 )

Article written by admin

mysql_thread_id()

April 4, 2011 | Filed Under MySQL Functions, PHP Tutorial | Leave a Comment

This function Return the ID.

Syntax: mysql_thread_id(connection)

Description:

The argument “connection” is Optional. It specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used.

This function returns the thread ID on success, or FALSE failure.

Example:
Code:

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$thread_id = mysql_thread_id($link);
if ($thread_id){
    printf("current thread id is %d\n", $thread_id);
}

Output:

current thread id is285

Article written by admin

© PHPInterviewQuestion.com 2009 - 2012

eXTReMe Tracker