Difference between revisions of "PHP111"

From mi-linux
Jump to navigationJump to search
 
 
(31 intermediate revisions by 4 users not shown)
Line 1: Line 1:
 +
[[Main Page]] >> [[CP2228|Web Application Development]] >> [[PHP|Workbook]] >> PHP and Databases
 +
 
= PHP and Databases – Making the Connection =
 
= PHP and Databases – Making the Connection =
  
To execute queries on a database is made up of 2 parts:
+
== How to connect ==
# Send the Query to the Database
+
 
# Handle the response
+
There are 3 ways to connect to a database in PHP: ([http://stackoverflow.com/questions/2190737/what-is-the-difference-between-mysql-mysqli-and-pdo source])
 +
 
 +
# (DEPRECATED) The [http://www.php.net/manual/en/ref.mysql.php mysql functions] are procedural and use manual escaping.
 +
# [http://www.php.net/manual/en/intro.mysqli.php MySQLi] is a replacement for the mysql functions, with object-oriented and procedural versions. It has support for prepared statements. '''We will use this option on this module'''
 +
# [http://php.net/manual/en/book.pdo.php PDO] (PHP Data Objects) is a general database abstraction layer with support for MySQL among many other databases. It provides prepared statements, and significant flexibility in how data is returned.
 +
 
 +
See some working examples for mi-linux here:
 +
* [https://mi-linux.wlv.ac.uk/~in9352/db/ https://mi-linux.wlv.ac.uk/~in9352/db/]
 +
 
 +
== The code ==
 +
 
 +
Here is all the code you'll need to connect to the server, run an SQL query, and display the data returned:
 +
 
 +
<pre>
 +
<?php
 +
 
 +
// Connect to server/database
 +
$mysqli = mysqli_connect("localhost", "YOUR_LOGIN", "YOUR_PASSWORD", "YOUR_DATABASE");
 +
if ($mysqli -> connect_errno) {
 +
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
 +
  exit();
 +
} else {
 +
 echo "Connected to the database successfully.";
 +
}
 +
 
 +
 
 +
// Run SQL query
 +
$res = mysqli_query($mysqli, "SELECT name, species, age FROM pet");
 +
 
 +
// Are there any errors in my SQL statement?
 +
if(!$res) {
 +
  print("MySQL error: " . mysqli_error($mysqli));
 +
  exit;
 +
}
 +
 
 +
// How many rows were returned?
 +
echo("<p>" . mysqli_num_rows($res) . " record(s) were returned...</p>");
 +
 
 +
// Loop through resultset and display each field's value
 +
while($row = mysqli_fetch_assoc($res)) {
 +
  echo $row['name']. " - ". $row['species'] ."<br>";
 +
}
 +
 
 +
?>
 +
</pre>
 +
 
 +
See the result [https://mi-linux.wlv.ac.uk/~in9352/php/php-db-pets.php here].
 +
 
 +
== The code explained ==
 +
 
 +
<pre>
 +
// Connect to server/database
 +
$mysqli = mysqli_connect("localhost", "YOUR_LOGIN", "YOUR_PASSWORD", "YOUR_DATABASE");
 +
if ($mysqli -> connect_errno) {
 +
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
 +
  exit();
 +
} else {
 +
 echo "Connected to the database successfully.";
 +
}
 +
 
 +
</pre>
 +
 
 +
The first line of code is very important as it establishes a connection to our database server, using your credentials, and specifies which database we want to use on the server.
 +
 
 +
The mysqli_connect() function takes 4 parameters:
 +
* server: "localhost" works fine here, since both PHP and MySQL are installed on the same server (mi-linux)
 +
* login: your MySQL login
 +
* password: your MySQL passord
 +
* databse: the name of YOUR database (usually "db" + your student number, e.g. db0123456)
 +
 
 +
The mysqli_connect() function returns a connection object ($mysqli in this case) that we will use again later (see below).
 +
 
 +
The if statement deals with errors, i.e. if the connection fails, it provides basic information and error messages (e.g. "Access denied" if your login/password is wrong).
 +
 
 +
<pre>
 +
// Run SQL query
 +
$res = mysqli_query($mysqli, "SELECT name, species, age FROM pet");
 +
</pre>
 +
 
 +
Once connected, the mysqli_query() function is used to RUN queries, and takes the following 2 parameters:
 +
* A connection object, as returned by mysqli_connect() (see above)
 +
* An SQL string
 +
 
 +
It returns a result-set as an object ($res in this case), i.e. a collection of 1 or more records.
 +
 
 +
<pre>
 +
// Are there any errors in my SQL statement?
 +
if(!$res) {
 +
  print("MySQL error: " . mysqli_error($mysqli));
 +
  exit;
 +
}
 +
</pre>
 +
 
 +
The above simply display any errors returned from the MySQL server, for example if you have made a mistake in your SQL statement, if you are selecting fields that don't exist etc... very useful for debugging!
 +
 
 +
<pre>
 +
// How many rows were returned?
 +
echo("<p>" . mysqli_num_rows($res) . " record(s) were returned...</p>");
 +
</pre>
  
== Connecting to the MySQL Database Server ==
+
Once you have obtained a result-set from the database, the first thing you can do is count how many records it contains, using the mysqli_num_rows() function. It takes a valid result-set as a parameter, and returns an int value (i.e. a number).
Firstly, to connect to a database we use the following:
 
$dbServer=mysql_connect ("localhost","cp1079_student","");
 
* The parameters passed to the '''mysql_connect''' statement are:
 
** The MySQL Database Server Address - this is usually running on the same machine as PHP, so "localhost" can be used
 
** A Username
 
** A Password (in this instance, there is no password for the user "demo")
 
* $dbServer is a variable we use to hold the connection to the database server.  It’s use will become clearer as we progress.
 
  
== Checking the Connection ==
+
<pre>
To check to make sure the connection is OK, you can use the following:
+
// Loop through resultset and display each field's value
if (!isset($dbServer))
+
while($row = mysqli_fetch_assoc($res)) {
{
+
  echo $row['name']. " - ". $row['species'] ."<br>";
  print ("failed to connect to server");
+
}
  exit;
+
</pre>
}
 
* if $dbServer is not set - i.e. is empty - no connection exists to the database server
 
  
== Choosing a database on the MySQL Database Server ==
+
Displaying the number of records can be useful, but what we are really after here is the data itself, i.e. the records. You can fetch ONE record from a result-set using the mysqli_fetch_assoc() function, passing the result-set as a parameter. It returns ONE record from the set, i.e. 1 pet in this case.
Next, we choose the database we want to use with the following:
 
mysql_select_db("cp1079",$dbServer);
 
* The parameters passed to the '''mysql_select_db''' statement are:
 
** the database name we want, in this case '''cp1079''' is the name of the database
 
** the database server connection that we have already opened - $dbServer
 
  
== Executing a Query ==
+
If you put the mysqli_fetch_assoc() function in a while loop (as is the case here), it will keep fetching records until you reach the end of the result-set.
To execute a query, first we have to prepare the query.  This is best accomplished using a string variable.
 
$sql = "SELECT name, species, age FROM pet";
 
When we execute the query, we need to handle the response from the Database server, so we need to use a special variable called a ''resource''
 
$queryResult = mysql_query($sql);
 
* $queryResult is the ''resource'' that holds the response from the Database server
 
* $sql is passed to the Database server using the command '''mysql_query'''
 
  
== Did it work? ==
+
Inside the loop, we can access the current record's fields like this:
We can test to see if the query executed correctly at the Database server by using the following:
 
<nowiki>if (mysql_error())
 
{
 
  print ("There has been an error<BR>".mysql_error());
 
  exit;
 
}</nowiki>
 
 
* '''mysql_error()''' is a function that will return any error messages generated by the database server based on the last instruction
 
** i.e. the mysql_query was the last instruction, if this generated errors, mysql_error() will retrieve the error message
 
** so '''if(mysql_error())''' means, if the last instruction caused errors, do the following...
 
** in our example, we output the error message and exit the program if an error was caused
 
  
== Assuming it worked... ==
+
<pre>
We can now check to see how many rows have been returned using the following:
+
$row['field_name']
<nowiki>print mysql_num_rows($queryResult)." records returned<BR>";</nowiki>
+
</pre>
* this will output the number of records returned in the $queryResult
 
8 '''NOTE:''' - this will only work for SELECT queries, as only SELECT queries return records
 
  
== Manipulating the Records returned ==
+
So for example in our case:
The most common way to manipulate the returned records, is to extract the first record returned and convert it into an array.  We do this with the following:
 
$dbRecord=mysql_fetch_array($queryResult);
 
* mysql_fetch_array extracts the first record from $queryResult into an array called $dbRecord
 
* $dbRecord will be an array containing '''ONLY''' the first record returned, not all of the records, just the first
 
  
== Printing out records returned ==
+
<pre>
As we have SELECTed three fields (name, species, age) from the table, there will be three elements created in our array.  To print out the first element (name) we can use:
+
$row['name']
print $dbRecord[0];
+
$row['species']
* THIS DOES NOT PRINT OUT THE FIRST RECORD - this ONLY prints out the first element of the array (or first field of the record) of the first record returned from the database
+
$row['age']
 +
</pre>
  
To print out the second field of the first record:
+
In this case, we simply display the name and species on a single line, separated by a - character.
print $dbRecord[1];
 
  
and so on…..
+
== You try it ==
  
== Easier access to the fields in the records ==
+
* Implement the code above
The mysql_fetch_array statement also names the elements in the array as well.
+
* Amend the code above so that it displays all 3 fields selected (name, species and age)
$dbRecord[0] is the same as $dbRecord["name"]
+
* Amend the code above so that it displays all 3 fields in an HTML table, like [https://mi-linux.wlv.ac.uk/~in9352/php/php-db-pets-table.php this]
$dbRecord[1] is the same as $dbRecord["species"]
 
$dbRecord[2] is the same as $dbRecord["age"]
 
 
= Putting it all together =
 
<nowiki><?
 
  $dbServer=mysql_connect ("localhost","cp1079_student","");
 
  if (!isset($dbServer))
 
  {
 
    print ("failed to connect to server");
 
    exit;
 
  }
 
  mysql_select_db("cp1079",$dbServer);
 
  $sql = "SELECT name, species, age FROM pet";
 
  $queryResult = mysql_query($sql);
 
  if (mysql_error())
 
  {
 
    print ("There has been an error<BR>".mysql_error());
 
    exit;
 
  }
 
  print mysql_num_rows($queryResult)." records returned<BR>";
 
  $dbRecord=mysql_fetch_array($queryResult);
 
  print "Name is ".$dbRecord["name"]." and species is ".$dbRecord["species"]." and age is " .$dbRecord["age"];
 
?></nowiki>
 
 
= BUT... =
 
This only prints out the first record - our sql query asked for all the records from the pet table.
 
  
We need a loop to loop through all the records returned.  Try replacing the last two lines of the code above with an elegant loop to iterate through the records regardless of how many records are returned, like this:
+
== Mini task ==
<nowiki>while ($dbRecord=mysql_fetch_array($queryResult))
 
{
 
  print "Name is ".$dbRecord["name"]." and species is ".$dbRecord["species"]." and age is ".$dbRecord["age"]."<BR>";
 
}</nowiki>
 
  
= Ready to try some more PHP/MySQL? =
+
Let's take a look at this week's [[PHPEX04|mini task]].
A simple example of using a HTML form to capture search requirements and execute a custom query can be found at [[PHP112|PHP112 - Simple HTML/PHP/MySQL example]]
 

Latest revision as of 11:38, 20 September 2023

Main Page >> Web Application Development >> Workbook >> PHP and Databases

PHP and Databases – Making the Connection

How to connect

There are 3 ways to connect to a database in PHP: (source)

  1. (DEPRECATED) The mysql functions are procedural and use manual escaping.
  2. MySQLi is a replacement for the mysql functions, with object-oriented and procedural versions. It has support for prepared statements. We will use this option on this module
  3. PDO (PHP Data Objects) is a general database abstraction layer with support for MySQL among many other databases. It provides prepared statements, and significant flexibility in how data is returned.

See some working examples for mi-linux here:

The code

Here is all the code you'll need to connect to the server, run an SQL query, and display the data returned:

<?php

// Connect to server/database
$mysqli = mysqli_connect("localhost", "YOUR_LOGIN", "YOUR_PASSWORD", "YOUR_DATABASE");
if ($mysqli -> connect_errno) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
  exit();
} else {
 echo "Connected to the database successfully.";
}


// Run SQL query
$res = mysqli_query($mysqli, "SELECT name, species, age FROM pet");

// Are there any errors in my SQL statement?
if(!$res) {
  print("MySQL error: " . mysqli_error($mysqli));
  exit;
}

// How many rows were returned?
echo("<p>" . mysqli_num_rows($res) . " record(s) were returned...</p>");

// Loop through resultset and display each field's value
while($row = mysqli_fetch_assoc($res)) {
  echo $row['name']. " - ". $row['species'] ."<br>";
}

?>

See the result here.

The code explained

// Connect to server/database
$mysqli = mysqli_connect("localhost", "YOUR_LOGIN", "YOUR_PASSWORD", "YOUR_DATABASE");
if ($mysqli -> connect_errno) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
  exit();
} else {
 echo "Connected to the database successfully.";
}

The first line of code is very important as it establishes a connection to our database server, using your credentials, and specifies which database we want to use on the server.

The mysqli_connect() function takes 4 parameters:

  • server: "localhost" works fine here, since both PHP and MySQL are installed on the same server (mi-linux)
  • login: your MySQL login
  • password: your MySQL passord
  • databse: the name of YOUR database (usually "db" + your student number, e.g. db0123456)

The mysqli_connect() function returns a connection object ($mysqli in this case) that we will use again later (see below).

The if statement deals with errors, i.e. if the connection fails, it provides basic information and error messages (e.g. "Access denied" if your login/password is wrong).

// Run SQL query
$res = mysqli_query($mysqli, "SELECT name, species, age FROM pet");

Once connected, the mysqli_query() function is used to RUN queries, and takes the following 2 parameters:

  • A connection object, as returned by mysqli_connect() (see above)
  • An SQL string

It returns a result-set as an object ($res in this case), i.e. a collection of 1 or more records.

// Are there any errors in my SQL statement?
if(!$res) {
  print("MySQL error: " . mysqli_error($mysqli));
  exit;
}

The above simply display any errors returned from the MySQL server, for example if you have made a mistake in your SQL statement, if you are selecting fields that don't exist etc... very useful for debugging!

// How many rows were returned?
echo("<p>" . mysqli_num_rows($res) . " record(s) were returned...</p>");

Once you have obtained a result-set from the database, the first thing you can do is count how many records it contains, using the mysqli_num_rows() function. It takes a valid result-set as a parameter, and returns an int value (i.e. a number).

// Loop through resultset and display each field's value
while($row = mysqli_fetch_assoc($res)) {
  echo $row['name']. " - ". $row['species'] ."<br>";
}

Displaying the number of records can be useful, but what we are really after here is the data itself, i.e. the records. You can fetch ONE record from a result-set using the mysqli_fetch_assoc() function, passing the result-set as a parameter. It returns ONE record from the set, i.e. 1 pet in this case.

If you put the mysqli_fetch_assoc() function in a while loop (as is the case here), it will keep fetching records until you reach the end of the result-set.

Inside the loop, we can access the current record's fields like this:

$row['field_name']

So for example in our case:

$row['name']
$row['species']
$row['age']

In this case, we simply display the name and species on a single line, separated by a - character.

You try it

  • Implement the code above
  • Amend the code above so that it displays all 3 fields selected (name, species and age)
  • Amend the code above so that it displays all 3 fields in an HTML table, like this

Mini task

Let's take a look at this week's mini task.