bidvertiser

Wednesday, October 22, 2008

Querying data from a table code

// Make a MySQL Connection
mysql_connect("localhost", "admin", "1admin") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());

// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM example")
or die(mysql_error());

// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry

echo "Name: ".$row['name'];
echo " Age: ".$row['age'];

?>

Inserting data into a table code

mysql_connect("localhost", "admin", "1admin") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
// Insert a row of information into the table "example"
mysql_query("INSERT INTO example (name, age)
VALUES('Timmy Mellowman', '23' ) ") or die(mysql_error());
mysql_query("INSERT INTO example (name, age)
VALUES('Sandy Smith', '21' ) ") or die(mysql_error());
mysql_query("INSERT INTO example (name, age)
VALUES('Bobby Wallace', '15' ) ") or die(mysql_error());
echo "Data Inserted!";
?>

MySQL Function Reference example code

if (!$link)
{ die('Could not connect: ' . mysql_error());
} mysql_select_db('mydb'); /* Update records */
mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
printf ("Updated records: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
?>

MySQL Function Reference example code

if (!$link)
{
die('Could not connect: ' . mysql_error());
} mysql_select_db('mydb'); /* this should return the correct numbers of deleted records */ mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Records deleted: %d\n", mysql_affected_rows());
/* with a where clause that is never true, it should return 0 */ mysql_query('DELETE FROM mytable WHERE 0');
printf("Records deleted: %d\n", mysql_affected_rows());
?>

MySQL Function Reference contd..

int mysql_affected_rows ([ resource $link_identifier ] )
Gets the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query associated with link_identifier.
Return Values
Returns the number of affected rows on success, and -1 if the last query failed.
If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero with MySQL versions prior to 4.1.2.
When using UPDATE, MySQL will not update columns where the new value is the same as the old value. This creates the possibility that mysql_affected_rows() may not actually equal the number of rows matched, only the number of rows that were literally affected by the query.
The REPLACE statement first deletes the record with the same primary key and then inserts the new record. This function returns the number of deleted records plus the number of inserted records.

MySQL Function Reference example code

mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
?>

$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
/* returns 2 because id,email === two fields */
echo mysql_num_fields($result);
?>

MySQL Function Reference contd..

int mysql_num_rows ( resource $result )
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
$result.
The result resource that is being evaluated.
Return value.
The number of rows in a result set on success, or FALSE on failure.

int mysql_num_fields ( resource $result )
Retrieves the number of fields from a query.
Returns the number of fields in the result set resource on success, or FALSE on failure.

MySQL Function Reference contd..

resource mysql_db_query ( string $database , string $query [, resource $link_id] ) .
Selects a database, and executes a query on it.
$database
The name of the database that will be selected.
$query
The MySQL query.
Return value.
Returns a positive MySQL result resource to the query result, or FALSE on error.

MySQL Function Reference example code

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

MySQL Function Reference contd..

string mysql_error ([ resource $link_identifier ] )
Returns the error text from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error() to retrieve the error text. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function.
$link_identifier.
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level error is generated.
Return value.
Returns the error text from the last MySQL function, or '' (empty string) if no error occurred.

int mysql_errno ([ resource $link_identifier ] )
Returns the error number from the last MySQL function or 0 (zero) if no error occurred.
bool mysql_close ([ resource $link_identifier ] )
closes the non-persistent connection to the MySQL server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is used.
Return value.
Returns TRUE on success or FALSE on failure.

mysql_connect example code

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) 
{ die('Could not connect');
}
echo 'Connected successfully';

MySQL Function Reference

resource mysql_connect ([ string $server [, string $username [, string $password [,
bool $new_link [, int $client_flags ]]]]] )
$server.
The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost.
$username.
The username.
$password.
The password.
$new_link.
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters.
$client_flags.
The client_flags parameter can be a combination of the following constants: 128 (enable LOAD DATA LOCAL handling), MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE.
Return Value.
Returns a MySQL link identifier on success, or FALSE on failure.

MySQL Functions

mysql_affected_rows — Get number of affected rows in previous MySQL operation
mysql_change_user — Change logged in user of the active connection
mysql_client_encoding — Returns the name of the character set
mysql_close — Close MySQL connection
mysql_connect — Open a connection to a MySQL Server
mysql_create_db — Create a MySQL database
mysql_data_seek — Move internal result pointer
mysql_db_name — Get result data
mysql_db_query — Send a MySQL query
mysql_drop_db — Drop (delete) a MySQL database
mysql_errno — Returns the numerical value of the error message from previous MySQL operation
mysql_error — Returns the text of the error message from previous MySQL operation
mysql_escape_string — Escapes a string for use in a mysql_query
mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
mysql_fetch_assoc — Fetch a result row as an associative array
mysql_fetch_field — Get column information from a result and return as an object
mysql_fetch_lengths — Get the length of each output in a result
mysql_fetch_object — Fetch a result row as an object
mysql_fetch_row — Get a result row as an enumerated array
mysql_field_flags — Get the flags associated with the specified field in a result
mysql_field_len — Returns the length of the specified field
mysql_field_name — Get the name of the specified field in a result
mysql_field_seek — Set result pointer to a specified field offset
mysql_field_table — Get name of the table the specified field is in
mysql_field_type — Get the type of the specified field in a result
mysql_free_result — Free result memory
mysql_get_client_info — Get MySQL client info
mysql_get_host_info — Get MySQL host info
mysql_get_proto_info — Get MySQL protocol info
mysql_get_server_info — Get MySQL server info
mysql_info — Get information about the most recent query
mysql_insert_id — Get the ID generated from the previous INSERT operation
mysql_list_dbs — List databases available on a MySQL server
mysql_list_fields — List MySQL table fields
mysql_list_processes — List MySQL processes
mysql_list_tables — List tables in a MySQL database
mysql_num_fields — Get number of fields in result
mysql_num_rows — Get number of rows in result
mysql_pconnect — Open a persistent connection to a MySQL server
mysql_ping — Ping a server connection or reconnect if there is no connection
mysql_query — Send a MySQL query
mysql_real_escape_string — Escapes special characters in a string for use in a SQL statement
mysql_result — Get result data
mysql_select_db — Select a MySQL database
mysql_set_charset — Sets the client character set
mysql_stat — Get current system status
mysql_tablename — Get table name of field
mysql_thread_id — Return the current thread ID
mysql_unbuffered_query — Send an SQL query to MySQL, without fetching and buffering the result rows

What is MySQL?

MySQL is currently the most popular open source database server in existence.
It is very commonly used in conjunction with PHP scripts to create powerful and dynamic server-side DB applications.

Friday, September 12, 2008

Example 4 file reading

PHP file reading

The fgets( ) function.
The fgets() functions is used to read a line from a file. Using this function we either read the entire line into a string or specify the number characters we like to read.
fgets ($handle, $length);
$handle - the file pointer
$length - number of bytes to read. If length is not specified it will read at the end of the line.

Example open for read

PHP file open for read

fopen ($filename, $mode);
Arguments same as before. Return value same as mode write already seen.
Read mode table.

Example code 4 create & open

PHP file create and open

The fopen( ) function.
fopen ($filename, $mode);
$filename - the name of the file. This may also include the absolute path where you want to create the file. Example, "/www/myapp/myfile.txt".
$mode - mode is used to specify how you want to create the file. For example, you can set the mode to create for read only, or create a file for read and write. Below is the list of possible modes you can use.
If successful this function returns the file handle, otherwise it returns a false value.

Other functions

bool session_is_registered ( string $name )
Finds out whether a global variable is registered in a session.

bool isset($_SESSION[$name]) may also be used.

void session_unset ( void )
The session_unset() function frees all session variables currently registered.
No value is returned.

bool session_unregister ( string $name )
session_unregister() unregisters the global variable named name from the current session.
string session_save_path ([ string $path ] )
session_save_path() returns the path of the current directory used to save session data.

bool session_destroy ( void )
session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.
Returns TRUE on success or FALSE on failure.

Monday, September 8, 2008

Session Name & ID

string session_name ([ string $name ] )
session_name() returns the name of the current session.
The session name is reset to the default value stored in session.name at request startup time.

string session_id ([ string $id ] )
session_id() is used to get or set the session id for the current session.
The constant SID can also be used to retrieve the current name and session id as a string suitable for adding to URLs.

bool session_regenerate_id ([ bool $delete_old_session ] )
session_regenerate_id() will replace the current session id with a new one, and keep the current session information.

Session Start

bool session_start ( void )
Creates a session or resumes the current one based on the current session id that's being passed via a request, such as GET, POST, or a cookie.
This function always returns TRUE.
Example:
?>

PHP Session Functions Reference

session_cache_expire — Return current cache expire
session_cache_limiter — Get and/or set the current cache limiter
session_commit — Alias of session_write_close
session_decode — Decodes session data from a string
session_destroy — Destroys all data registered to a session
session_encode — Encodes the current session data as a string
session_get_cookie_params — Get the session cookie parameters
session_id — Get and/or set the current session id
session_is_registered — Find out whether a global variable is registered in a session
session_module_name — Get and/or set the current session module
session_name — Get and/or set the current session name
session_regenerate_id — Update the current session id with a newly generated one
session_register — Register one or more global variables with the current session
session_save_path — Get and/or set the current session save path
session_set_cookie_params — Set the session cookie parameters
session_set_save_handler — Sets user-level session storage functions
session_start — Initialize session data
session_unregister — Unregister a global variable from the current session
session_unset — Free all session variables
session_write_close — Write session data and end session

What is a PHP Session?

A way to preserve certain data across subsequent accesses.

A session allows you to store user information on the server for later use (i.e. username, shopping cart items, etc).

A session stores such information in the form of session variables for as long as the user is logged in or the application is running.
SAMPLE CODE:
$_SESSION["username"] = “IMRAN";
$_SESSION[“nickname"] = “delta";

?>

PHP Form handling – POST Method


To receive data from POST method form we can use $_POST[ ] collection.
echo "Your name is: ".$_POST["txtName"]."
";
echo "Your roll number is: ".$_POST["txtRno"]."
";
echo "Your address is: ".$_POST["txtAdrs"]."
";
?>

PHP provides another collection by the name $_REQUEST[ ].
This collection may be used for both the methods; GET & POST.

foreach ($_REQUEST as $key => $value)
{
echo $key."=".$value."
";
}
?>

PHP Form handling – GET Method

HTML Forms same as before.
Two submission methods: POST and GET.






The ‘include’ and ‘require’ functions Example

Example:

The ‘include’ and ‘require’ functions

Include and require are used to reuse external php scripts that may contain HTML, PHP, etc.

DATE & TIME Formats

The basic PHP date and time functions let you format timestamps for use in database queries or simply for displaying the date and time in the browser window.
PHP includes the following date and time functions:
date(format)
Returns the current server time, formatted according to a given set of parameters.

checkdate(month, day, year)
Validates a given date. Successful validation means that the year is between 0 and 32767, the month is between 1 and 12, and the proper number of days in each month.

time()
Returns the current server time, measured in seconds since the Epoch or January 1, 1970.
a Prints "am" or "pm“
A Prints "AM" or "PM".
h Hour in 12-hour format (01 to 12)
H Hour in 24-hour format (00 to 23)
g Hour in 12-hour format without a leading zero (1 to 12)
G Hour in 24-hour format without a leading zero (0 to 23)
i Minutes (00 to 59)
s Seconds (00 to 59)
d Day of the month in two digits (01 to 31)
D Day of the week in text (Mon to Sun)
l Day of the week in long text (Monday to Sunday)
F Month in long text (January to December)
n Month in two digits (1 to 12)
Y Year in four digits (2005)
y Year in two digits (05)
s English ordinal suffix (th, nd, st)

SAMPLE CODES

PHP Contents (Continued)

PHP Strings.
•Strings can be specified using one of two sets of delimiters.
•If the string is enclosed in double-quotes ("), variables within the string will be expanded (subject to some parsing limitations).
•As in C the backslash ("\") character can be used in specifying special characters:



String manipulation functions.
•substr(,,[]);
•strlen();
•trim();
•ltrim(); // Trim left
•rtrim(); // Trim right
•strtolower();
•strtoupper();
•str_replace(,,,[]);
•strpos(, );
•strcmp(,); (Binary safe string comparison)
•strcasecmp(,); (Binary safe case-insensitive comparison)
•explode(,,[]); (Break string into array)
•implode(,); (Join array into string separated by delim)

PHP Contents (Continued)

The IF statement.
if ()
{ ; }
elseif ()
{ ; }
else
{ ; }
The inline (ternary) if.
? true : false;





The switch-case statement.
switch ()
{
case :
;
[break;]
case :
;
[break;]
default:
;
}



The for loop statement.
for (;;)
{
;
}
The foreach loop statement.
foreach ( as [ => ])
{
;
[break];
[continue];
}



The while loop statement.
while ()
{
;
}
The do-while loop statement.
do
{
;
} while ();



The PHP functions.
function ([])
{
;
[return ;]
}

PHP Contents (Continued)

Comments in PHP.
–// Comment text
–/* Multi-line comment text */
–# Comment text


Operators in PHP.
•Arithmetic Operators.
–+ (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus)
•Relational Operators.
–== (Equal), === (Equal with type comparison),
–!= (Not equal), <> (Not equal), !== (Not Equal with type comparison),
–< (Less than), > (Greater than), <= (Less than or equal to), >= (Greater than or equal to)
•Logical Operators.
–! (logical NOT), && (logical AND), (logical OR), xor (logical XOR)
•Assignment Operators.
–= (Assign), += (Addition), -= (Subtraction), *= (Multiplication), /= (Division),
–.=(Concatenation), %= (Modulus), &= (And), = (Or),
–^= (Exclusive Or), <<= (Left Shift), >>=(Right Shift)
•Concatenation Operator.
–. (dot)


Predefined Super Globals.
•$GLOBALS (Access all global variables in script)
•$_SERVER (Access web server variables)
•$_GET (Values passed to script through URL)
•$_POST (Values passed to script through HTTP Post)
•$_COOKIE (Values passed by user cookie)
•$_FILES (Values passed by HTTP Post File Uploads)
•$_ENV (Values passed to script via the environment)
•$_REQUEST (Values passed by URL, HTTP Post, or user Cookies)
•$_SESSION (Values passed through user's session)

PHP Contents

Data Types & Variable Declarations.
•Data Types.
–integer, float, boolean, string, array, object, resource, NULL
•Variable Declarations.
–$variablename = ;
–$anothervariable =& $variablename; (Assign by Reference)
•Array Declarations.
–$arrayname = array();

More on arrays.
$a[0] = "abc";
$a[1] = "def";
$b["foo"] = 13; (Associative subscript).
You can also create an array by simply adding values to the array.
When you assign a value to an array variable using empty brackets, the value will be added onto the end of the array.
$a[] = "hello"; // $a[2] == "hello"
$a[] = "world"; // $a[3] == "world"

Double dimension arrays.
$arr[2][3] = array();
$arr[0][0] = 34;

Array Functions.
•sort(); (Sort array assigns new keys)
•asort(); (Sort array maintain keys)
•rsort(); (Sort array in reverse, new keys)
•arsort(); (Sort array in reverse, maintain keys)
•count(); (Count elements)
•count(,COUNT_RECURSIVE); (Count multidimensional array)
•array_push(,); (Push item onto end of array)
•array_pop(); (Pop item off end of array)