0% found this document useful (0 votes)
159 views21 pages

PHP and Web Forms

This document discusses PHP and web forms, sending form data to a server, working with cookies and session handlers, and PHP with MySQL for interacting with databases. It covers: 1. How PHP processes data submitted through web forms using the GET and POST methods. GET sends data via the URL while POST sends it in the HTTP request body. 2. Creating HTML forms and using the $_GET and $_POST superglobals in PHP to collect submitted form data. 3. Validating form data in PHP by checking for required fields and valid formats. 4. Using cookies in PHP by creating them with setcookie(), accessing cookie values, modifying cookies, checking if they are set, and deleting cookies.

Uploaded by

A Surya Teja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
159 views21 pages

PHP and Web Forms

This document discusses PHP and web forms, sending form data to a server, working with cookies and session handlers, and PHP with MySQL for interacting with databases. It covers: 1. How PHP processes data submitted through web forms using the GET and POST methods. GET sends data via the URL while POST sends it in the HTTP request body. 2. Creating HTML forms and using the $_GET and $_POST superglobals in PHP to collect submitted form data. 3. Validating form data in PHP by checking for required fields and valid formats. 4. Using cookies in PHP by creating them with setcookie(), accessing cookie values, modifying cookies, checking if they are set, and deleting cookies.

Uploaded by

A Surya Teja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

III- ‘B’ Web Programming

14BT61202: WEB PROGRAMMING

UNIT-IV PHP AND MYSQL

PHP and Web Forms, Sending Form Data to a Server, Working with Cookies and
Session Handlers, PHP with MySQL - Interacting with the Database, Prepared
Statement, Database Transactions.

// PHP and Web Forms:


Introduction:
Let’s begin with an introduction to

How PHP is able to accept and process data submitted through a web form.
Web Forms are used to encourage:

 Registration site
 facilitate forum conversations
 collect mailing and billing addresses for online orders, and much more.
Coding HTML form: only part of what’s required to effectively accept user input.

Server-side PHP: must be ready to process the input.

There are two ways the browser client can send information to the web server.

GET and POST.

(i) GET Method

Note that the query string (name/value pairs) is sent in the URL of a GET request:

The GET method sends the encoded user information appended to the page request.

GET Method

The page and the encoded information are separated by the ? character.

Example: http://www.test.com/index.htm?name1=value1&name2=value2

UNIT-IV 1 SVEC-Autonomous
III- ‘B’ Web Programming
Important Concepts of GET Request:

GET requests can be cached.


GET requests remain in the browser history.
GET requests can be bookmarked.
GET request should NEVER be used when dealing with Sensitive Data.
GET request have Length restrictions.
GET request should be used only to retrieve data.
GET- Example:

Suppose the form contains a text-field value named email.

<input type="text" id="email" name="email" size="20" maxlength="40" />

Once this form is submitted, you can reference that text-field value like so:

$_GET['email']

for sake of convenience, nothing prevents you from first assigning this value to another

Variable

$email = $_GET['email'];

(ii) The POST Method:

Note: The Query string (name/value pairs) is sent in the HTTP message body of a POST
request.
The POST method transfers information via HTTP headers. The information is encoded as
described in case of GET method and put into a header called QUERY_STRING.

Important Concepts of POST Request:

POST requests are never cached.


POST requests do not remain in the browser history.
POST requests cannot be bookmarked.
POST requests have NO restrictions on data length

UNIT-IV 2 SVEC-Autonomous
III- ‘B’ Web Programming
POST-Example:
Suppose the form contains a text-field value named email.
<input type="text" id="email" name="email" size="20" maxlength="40" />

Once this form is submitted, you can reference that text-field value like so:

$_POST['email']

for sake of convenience, nothing prevents you from first assigning this value to another
Variable

$email = $_POST['email'];

******************************************************************************

// Sending Form Data to a Server:


The PHP superglobals $_GET and $_POST are used to collect form-data.

Example: Displays a simple HTML form with two input fields and a submit button:

<!DOCTYPE HTML>
<html>
<body>

<form action="welcome.php" method="post">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>
OUTPUT:

When the user fills out the form above and clicks the submit button, the form data is sent
for processing to a PHP file named "welcome.php". The form data is sent with the HTTP
POST method.

To display the submitted data you could simply echo all the variables. The "welcome.php"

<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>

UNIT-IV 3 SVEC-Autonomous
III- ‘B’ Web Programming
Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>

Output:
Welcome III-B
Your email address is csetitans.com

PHP- Form Validation


<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

if (empty($_POST["website"])) {

UNIT-IV 4 SVEC-Autonomous
III- ‘B’ Web Programming
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the
URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}

if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}

if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<h2>PHP Form Validation Example</h2>


<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textar
ea>
<br><br>
Gender:

UNIT-IV 5 SVEC-Autonomous
III- ‘B’ Web Programming
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>

OUTPUT:

UNIT-IV 6 SVEC-Autonomous
III- ‘B’ Web Programming
// Working with COOKIES
What is a Cookies?

A cookie is a small file that the server embeds on the user's computer.
Each time the same computer requests a page with a browser, it will send the cookie too.
With PHP, you can both create and retrieve cookie values.
Cookies are text files stored on the client computer and they are kept of use tracking
purpose
Operations in PHP-Cookies
1.) Create Cookies with PHP
2.) Accessing/Retrieve Cookies with PHP
3.) Modify Cookie value
4.) Check Cookies is set or not
5.) Check if Cookies are Enabled
6.) Deleting Cookie with PHP
1.) Create Cookies With PHP:
A cookie is created with the setcookie() function.
Syntax:

Setcookie (name, value, expire, path, domain,secure, httponly);

NOTE: Only the name parameter is required.All other parameters are optional.

Example: Create two cookies

name and age these cookies will be expired after one hour.

<?php
setcookie("name", "John Watkin", time()+(86400 * 30), "/","", 0);
setcookie("age", “36", time()+(86400 * 30), "/", "", 0);
?>
<html> <head>
<title>Setting Cookies with PHP</title> </head> <body>
<?php echo "Set Cookies“
?> </body> </html>

UNIT-IV 7 SVEC-Autonomous
III- ‘B’ Web Programming
Explanation:

The cookie will expire after 30 days (86400 * 30).


The "/" means that the cookie is available in entire website

2.) Accessing/Retrieve Cookies with PHP


PHP provides many ways to access cookies.
Simplest way is to use either
$_COOKIE
(or)
$HTTP_COOKIE_VARS variables.

Example: access all the cookies set.

<html> <head>
<title>Accessing Cookies with PHP</title> </head> <body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["age"] . "<br />";
?> </body> </html>

3.) Modify a Cookie Value


To modify a cookie, just set (again) the cookie using the setcookie()
function:

<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";

UNIT-IV 8 SVEC-Autonomous
III- ‘B’ Web Programming
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

<p><strong>Note:</strong> You might have to reload the page to see the new value of the
cookie.</p>

</body>
</html>

OUTPUT:
Cookie named 'user' is not set!
Note: You might have to reload the page to see the new value of the cookie.

4.) Check Cookie is set or not:


You can use isset() function to check if a cookie is set or not.

<html> <head>
<title>Accessing Cookies with PHP</title> </head> <body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?> </body> </html>

5.) Check if Cookies are Enabled


To create a test cookie with the setcookie() function, then count the $_COOKIE array variable:

<!DOCTYPE html>
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>

<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>

UNIT-IV 9 SVEC-Autonomous
III- ‘B’ Web Programming

</body>
</html>

OUTPUT:

Cookies are enabled.

6.) Deleting Cookie with PHP:


Officially, to delete a cookie you should call setcookie() with the name argument only but
this does not always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired.

<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html> <head>
<title>Deleting Cookies with PHP</title>
</head> <body>
<?php
echo "Deleted Cookies “
?>
</body> </html>

Summary code of COOKIES:

Setting new cookie


=============================
<?php
setcookie("name","value",time()+$int);
/*name is your cookie's name
value is cookie's value
$int is time of cookie expires*/
?>

Getting Cookie
=============================
<?php
echo $_COOKIE["your cookie name"];
?>

UNIT-IV 10 SVEC-Autonomous
III- ‘B’ Web Programming
Updating Cookie
=============================
<?php
setcookie("color","red");
echo $_COOKIE["color"];
/*color is red*/
/* your codes and functions*/
setcookie("color","blue");
echo $_COOKIE["color"];
/*new color is blue*/
?>

Deleting Cookie
==============================
<?php
unset($_COOKIE["yourcookie"]);
/*Or*/
setcookie("yourcookie","yourvalue",time()-
1);
/*it expired so it's deleted*/
?>

Advantages of COOKIES:

1. Cookies don not require any server resources since they are stored on the client.
2. Cookies are easy to implement.
3. You can configure cookies to expire when the browser session ends(session cookies) or they
can exist for a specified length of time on the client computer(persistent cookies)

Disadvantages of COOKIES:

1. Users can delete cookies.


2. Users browser can refuse cookies, so your code has to anticipate that possibility.
3. Cookies exist as plain text on the client machine and they may pose a possible security risk as
anyone can open and tamper with cookies.vv

````````````````````````````````````````````````````````````````````````````````````````````````````````````````````

// Working with PHP SESSIONS


**What is a Sessions?

A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer.
The location of the temporary file is determined by a setting in the php.ini file called
session.save_path.

UNIT-IV 11 SVEC-Autonomous
III- ‘B’ Web Programming

**When session started following things will happen:

- PHP first creates a unique identifier for that particular session which is a random string
of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
- A cookie called PHPSESSID is automatically sent to the user's computer to store unique
session identification string.
- A file is automatically created on the server in the designated temporary directory and
bears the name of the unique identifier prefixed by
sess_ ie sess_3c7foj34c3jj973hj kop2fc937e3443.
** What is Session ID?

• Session handling is essentially a clever workaround to this problem of statelessness. This


is accomplished by assigning to each site visitor a unique identifying attribute, known as
the session ID.

• (SID), and then correlating that SID with any number of other pieces of data, be it
number of monthly visits, favorite background color, or middle name—you name it.

1.) Starting a PHP Session:

A PHP session is easily started by making a call to the session_start() function.


This function first checks if a session is already started and if none is started then it starts one.
It is recommended to put the call to session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[].
These variables can be accessed during lifetime of a session.
Example:

To Start a PHP Session

A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

Example: Start a PHP Session

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html> <body>

UNIT-IV 12 SVEC-Autonomous
III- ‘B’ Web Programming
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body> </html>

2.) Modify a PHP Session Variable:

<?php
session_start();
?>
<!DOCTYPE html>
<html> <body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body> </html>

3.) Destroy a PHP Session

<?php
session_start();
?>
<!DOCTYPE html>
<html> <body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
echo "All session variables are now removed, and the session is destroyed."
?>
</body> </html>

UNIT-IV 13 SVEC-Autonomous
III- ‘B’ Web Programming
// PHP AND MYSQL- INTERACTING WITH DATABASE
**Why MYSQL for PHP?

- is very fast, reliable, easy to use.


- compiles on number of platforms
- database is stored in a tables.

Example- Database are useful for storing information in categorically.

A company may have database with following Tables:

Employee, Products, Customers, Orders

MYSQL - BASICS:

updated MySQL extension with PHP 5, known as (MySQL Improved) (and typically
referred to as mysqli)

WHY need new Extension(mysqli)?

1. new features-> prepared statements, advanced connection options, and security


enhancements.

2. native object-oriented interface that would not only more tightly integrate with other
Applications.

List of Key Enhancements in sql:

 Object oriented:
A series of classes, more convenient and efficient programming paradigm.
 Prepared Statements:
Eliminate overhead and Inconvenience when working with queries another important
security-related feature in that they prevent SQL injection attacks.
 Transactional Support:
Although MySQL’s transactional capabilities are available the mysqli extension offers
an object-oriented interface to these capabilities
 Enhanced debugging capabilities:
The mysqli extension offers numerous methods for debugging queries, resulting in a
more efficient development process.
 Embedded server support:
The mysqli extension offers methods for connecting and manipulating these embedded
MySQL databases.

UNIT-IV 14 SVEC-Autonomous
III- ‘B’ Web Programming
// Interacting With Database
The vast majority of your queries will revolve around creation, retrieval, update, and
deletion tasks, collectively known as CRUD.

Sending a Query to the Database:

The method query() is responsible for sending the query to the database.

Example:

class mysqli {
mixed query(string query [, int resultmode])
}

resultmode parameter is used to modify the behavior of this method, accepting two
Values:

i.) MYSQLI_STORE_RESULT:
Returns the result as a buffered set, meaning the entire set will be made available for
navigation at once.

ii.) MYSQLI_USE_RESULT:
Returns the result as an unbuffered set, meaning the set will be retrieved on an as-needed
basis from the server.
Unbuffered result sets increase performance for large result sets,

Retrieving Data:

The following example retrieves the sku, name, and price columns from the products table,
ordering the results by name.

<?php
$mysqli = new mysqli('localhost', 'catalog_user', 'secret', 'corporate');
// Create the query
$query = 'SELECT sku, name, price FROM products ORDER by name';
// Send the query to MySQL
$result = $mysqli->query($query, MYSQLI_STORE_RESULT);
// Iterate through the result set
while(list($sku, $name, $price) = $result->fetch_row())
printf("(%s) %s: \$%s <br />", $sku, $name, $price);
?>

UNIT-IV 15 SVEC-Autonomous
III- ‘B’ Web Programming
Output
(TY232278) AquaSmooth Toothpaste: $2.25
(PO988932) HeadsFree Shampoo: $3.99
(ZP457321) Painless Aftershave: $4.50
(KL334899) WhiskerWrecker Razors: $4.17

Deleting Data

<?php
$mysqli = new mysqli('localhost', 'catalog_user', 'secret', 'corporate');
// Create the query
$query = "DELETE FROM products WHERE sku = 'TY232278'";
// Send the query to MySQL
$result = $mysqli->query($query, MYSQLI_STORE_RESULT);
// Tell the user how many rows have been affected
printf("%d rows have been deleted.", $mysqli >affected_rows);
?>

To check Connectivity of the Database.


<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
HTML Form connect to PHP Database

<html>
<head>
<title>Database and table creation</title>
</head>

UNIT-IV 16 SVEC-Autonomous
III- ‘B’ Web Programming
<body>
<form method="post" action="createdb.php">
Username<input type="text" name="uname"><br>
password<input type="password" name="pass"><br>
<input type="submit" name="register" value="register">
</form>
</body>
</html>

Create a Database and create and enter a table (createdb.php)

<?php
if(isset($_POST['register'])){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// sql to create table


$sql = "CREATE TABLE Users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL)";

if ($conn->query($sql) === TRUE) {


echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$name = $_POST['uname'] ;
$pass = $_POST['pass'];
$sql = "INSERT INTO Users (firstname, password)
VALUES ('$name' , '$pass')";

if ($conn->query($sql) === TRUE) {


echo "<h3>New record created successfully</h3>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

UNIT-IV 17 SVEC-Autonomous
III- ‘B’ Web Programming
$conn->close();
}
else{
header("location:register.php");
}
?>

// PREPARED STATEMENTS
** Why Prepared Statements?
Some looping mechanism in query comes at a cost, because of the repeated parsing of the
almost identical query for validity, and coding convenience, because of the need to repeatedly
reconfigure the query using the new values for each iteration.
To help resolve the issues incurred by repeatedly executed queries, MySQL 4.1 introduced
prepared statements, which can accomplish the tasks described above at a significantly lower
cost of overhead, and with fewer lines of code.
Two variants of prepared statements are available:
1.) Bound parameters: The bound-parameter variant allows you to store a query on
the MySQL server, with only the changing data being repeatedly sent to the server and
integrated into the query for execution.
For instance, suppose you create a web application that allows users to manage store
products. To jumpstart the initial process, you might create a web form that accepts up to 20
product names, IDs, prices, and descriptions. Because this information would be inserted using
identical queries (except for the data, of course), it makes sense to use a boundparameter
prepared statement.
2.) Bound results: The bound-result variant allows you to use sometimes unwieldy
Indexed or Associative arrays to pull values from result sets by binding PHP variables to
corresponding retrieved fields, and then using those variables as necessary.
For instance, you might bind the URL field from a SELECT statement retrieving product
information to variables named $sku, $name, $price, and $description.

i.) Preparing the Statement for Execution:


Using the bound-parameter or bound-result prepared statement variant. prepare the
statement for execution by using the prepare() method

class mysqli_stmt {
boolean prepare(string query)
}
EXAMPLE:

<?php
// Create a new server connection

UNIT-IV 18 SVEC-Autonomous
III- ‘B’ Web Programming
$mysqli = new mysqli('localhost', 'catalog_user', 'secret', 'corporate');
// Create the query and corresponding placeholders
$query = "SELECT sku, name, price, description FROM products ORDER BY sku";
// Create a statement object
$stmt = $mysqli->stmt_init();
// Prepare the statement for execution
$stmt->prepare($query);
.. Do something with the prepared statement
// Recuperate the statement resources
$stmt->close();
// Close the connection
$mysqli->close();
?>

ii.) Executing a Prepared Statement:


When it’s executed depends upon whether you want to work with bound parameters or
bound results. Executing the statement is accomplished using the execute() method.

class stmt {
boolean execute()
}

iii.) Recuperating Prepared Statement Resources:


Once you’ve finished using a prepared statement, the resources it requires can be
recuperated with the close() method. Its prototype follows:

class stmt {
boolean close()
}

iv.) Binding Parameters:


Bound- parameter prepared statement variant, you need to call the bind_param() method
to bind variable names to corresponding fields.

class stmt {
boolean bind_param(string types, mixed &var1 [, mixed &varN])
}

UNIT-IV 19 SVEC-Autonomous
III- ‘B’ Web Programming
EXAMPLE:
Binding Parameters with the mysqli Extension

<?php
// Create a new server connection
$mysqli = new mysqli('localhost', 'catalog_user', 'secret', 'corporate');
// Create the query and corresponding placeholders
$query = "INSERT INTO products SET id=NULL, sku=?,
name=?, price=?";
// Create a statement object
$stmt = $mysqli->stmt_init();
// Prepare the statement for execution
$stmt->prepare($query);
// Bind the parameters
$stmt->bind_param('ssd', $sku, $name, $price);
// Assign the posted sku array
$skuarray = $_POST['sku'];
// Assign the posted name array
$namearray = $_POST['name'];
// Assign the posted price array
$pricearray = $_POST['price'];
// Initialize the counter
$x = 0;
// Cycle through the array, and iteratively execute the query
while ($x < sizeof($skuarray)) {
$sku = $skuarray[$x];
$name = $namearray[$x];
$price = $pricearray[$x];
$stmt->execute();
}
// Recuperate the statement resources
$stmt->close();
// Close the connection
$mysqli->close();
?>

v.) Retrieving Rows from Prepared Statements:


The fetch() method retrieves each row from the prepared statement result and assigns the
fields to the bound results.

class mysqli {
boolean fetch()
}

UNIT-IV 20 SVEC-Autonomous
III- ‘B’ Web Programming

// Database Transactions
Three new methods enhance PHP’s ability to execute MySQL transactions. the three
relevant methods concerned with committing and rolling back a transaction are introduced for
purposes of reference.

1. Enabling Autocommit Mode:


The autocommit() method controls the behavior of MySQL’s autocommit mode. Its
prototype follows:

class mysqli {
boolean autocommit(boolean mode)
}

Passing a value of TRUE via mode enables autocommit, while FALSE disables it, in either
case returning TRUE on success and FALSE otherwise.

2. Committing a Transaction:
The commit() method commits the present transaction to the database, returning TRUE
on success and FALSE otherwise. Its prototype follows:

class mysqli {
boolean commit()
}

3. Rolling Back a Transaction:


The rollback() method rolls back the present transaction, returning TRUE on success and
FALSE otherwise. Its prototype follows:

class mysqli {
boolean rollback()
}

UNIT-IV 21 SVEC-Autonomous

You might also like