User Tools

Site Tools


en:web_development:databases:php

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
en:web_development:databases:php [2021/12/23 15:23]
mag [Foreach]
en:web_development:databases:php [2023/08/16 09:33] (current)
Line 17: Line 17:
     include('footer.php');     include('footer.php');
 ?></code> ?></code>
 +
 +==== Objects ====
 +  * Objects are an advanced data structure and we won't go into it too much here, but you'll need to understand a little bit to use the PHP database connection in this actviity.
 +  * An object is like a named array where you can access each element by name.
 +  * But an object also has functions built into. Recall that in Javascript, <html>audio</html> has built-in functions like <html>.play()</html>, <html>.paused()</html> and built-in information like <html>.paused</html>. That's because <html>audio</html> is an object.
 +  * Similarly, in PHP, an object can have both data and functions. For example, a database connection object can have information about the connection and also have functions to extract data.
 +  * Whereas you access the information in an array using <html> [] </html>, we access information and functions using <html>-></html>.
 +  * To use an abstract example, we could create an object called $table.
 +  * We could set the number of legs on the table as follows.
 +<code>$table->legs = 4;</code>
 +  * We could also move the table to another location as follows.
 +<code>$table->move($location);</code>
 +  * There is a whole school of programming based on objects (Object-oriented programming) and objects could be the subject of many classes, but this is all you need to know to use the database connection.
  
 ==== PDO Connection ==== ==== PDO Connection ====
Line 22: Line 35:
   * Copy the following code at the top of the first PHP block.   * Copy the following code at the top of the first PHP block.
 <code>    // Set up database connection <code>    // Set up database connection
-    define ('DBCONNECT', "../../pdo.php"); // database connection+    define ('DBCONNECT', "/home/dh_9m7wr9/pdo.php"); // database connection
     include_once DBCONNECT;     include_once DBCONNECT;
-    $db  = 'webdev';+    $db  = 'techschoolwebdev';
     $dsn = "mysql:host=$db_host;dbname=$db;charset=utf8mb4";     $dsn = "mysql:host=$db_host;dbname=$db;charset=utf8mb4";
     try      try 
Line 37: Line 50:
   * In the next line we define the database name (<html>$db  = 'webdev';</html>) because each application / site could use a different database so we need to define it inside the application / site.   * In the next line we define the database name (<html>$db  = 'webdev';</html>) because each application / site could use a different database so we need to define it inside the application / site.
   * The fourth line creates a string with all our connection details including the host, user name and the character set we'll use. <html>$dsn = "mysql:host=$db_host;dbname=$db;charset='utf8mb4'";</html>   * The fourth line creates a string with all our connection details including the host, user name and the character set we'll use. <html>$dsn = "mysql:host=$db_host;dbname=$db;charset='utf8mb4'";</html>
-  * The final block sets up the connection. This primarily occurs in <html>$pdo = new MyPDO($dsn, $db_user, $db_pass, $db_options);</html>, where <html>$pdo</html> is an object (a more advanced type of variable) that includes both the database connection and the functions needed to access the data.+  * The final block sets up the connection. This primarily occurs in <html>$pdo = new MyPDO($dsn, $db_user, $db_pass, $db_options);</html>, where <html>$pdo</html> is an object that includes both the database connection and the functions needed to access the data.
   * We wrap the connection in a <html>try</html> / <html>catch</html> block to handle any errors that may occur if the connection fails. In such a case, our code will throw an exception that includes a message and the error code.   * We wrap the connection in a <html>try</html> / <html>catch</html> block to handle any errors that may occur if the connection fails. In such a case, our code will throw an exception that includes a message and the error code.
   * It's not necessary to remember all this. It's sufficient to know where to find it and to include it in your code each for each site.   * It's not necessary to remember all this. It's sufficient to know where to find it and to include it in your code each for each site.
Line 51: Line 64:
   * Next, we need to set up the query by sending only that data to the database.   * Next, we need to set up the query by sending only that data to the database.
 <code>    $rslt  = $pdo->prepare($query);</code> <code>    $rslt  = $pdo->prepare($query);</code>
-  * <html>$rslt</html> is now a variable that holds the result of our query.+  * <html>$rslt</html> is now an object that holds the result of our query.
   * We can now safely send our parameters and have the database run our query.   * We can now safely send our parameters and have the database run our query.
 <code>    $rslt->execute($args);</code> <code>    $rslt->execute($args);</code>
-  * The final step is to retrieve the results of the query, which we do in a loop+  * The final step is to retrieve the results of the query, which we do in a loop to get our data line by line.
- +
-==== While Loops ==== +
-  * Just as in Javascript, PHP has many types of loops. The next we'll look at is the 'while loop'+
-  * Add the following code inside a PHP block. It might be best to put it at the end to keep it separate. Change my name to yours so you can find your results in the logs. +
-<code>    $i = 0; +
-    while ($i < 10) { +
-        error_log("MURRAY: the value of i is $i"); +
-        $i++; +
-    }</code> +
-  * <html>$i = 0;</html> defines a variable and sets it to '0'+
-  * <html>while ($i < 10) {}</html> runs the code inside <html> {} </html> as long as $i is less than 10. +
-  * <html>error_log("MURRAY: the value of i is $i");</html> outputs a string containing the value of <html>$i</html> to the logs so we can see it. +
-  * Finally, <html>$i++;</html> increments <html>$i</html> each loop so that it doesn't go on forever. +
-  * Open the page 'mysql.php' and check your logs using Putty. +
-<code>cat /var/log/apache2/error.log | grep 'MURRAY'</code> +
-  * You should see your text ten times with the number increasing from 0 to 9. +
-  * So this is another way of running the same code multiple times. +
-  * Let's use it to get our data line by line.+
   * Add the following code after <html>$rslt->execute($args);</html>   * Add the following code after <html>$rslt->execute($args);</html>
 <code>    while ($row = $rslt->fetch()) { <code>    while ($row = $rslt->fetch()) {
Line 78: Line 73:
     }</code>     }</code>
   * This code fetches the a single row of data from our query result <html>$rslt</html> and stores it in the variable <html>$row</html>.   * This code fetches the a single row of data from our query result <html>$rslt</html> and stores it in the variable <html>$row</html>.
- 
-==== Displaying Arrays ==== 
- 
   * Let's display that row in our error log. Place the following code inside the <html>{}</html>.   * Let's display that row in our error log. Place the following code inside the <html>{}</html>.
 <code>        error_log("MURRAY: query response row - " . print_r($row,1));</code> <code>        error_log("MURRAY: query response row - " . print_r($row,1));</code>
   * If you refresh your page and check your logs, you'll see the data from our database.   * If you refresh your page and check your logs, you'll see the data from our database.
-  * Notice the new command <html>print_r</html>. This is more flexible than <html>echo</html>, which can't print arrays or objects.+  * Notice the new use of two parameters with <html>print_r</html>.
   * The first parameter <html>$row</html> is the content to be displayed.   * The first parameter <html>$row</html> is the content to be displayed.
   * The second parameter <html> 1 </html> tells <html>print_r</html> to convert the first parameter to a string, which can then be displayed using <html>echo</html> or <html>error_log</html>.   * The second parameter <html> 1 </html> tells <html>print_r</html> to convert the first parameter to a string, which can then be displayed using <html>echo</html> or <html>error_log</html>.
Line 123: Line 115:
     }     }
 ?> ?>
-            </body>+            </tbody>
         </table>         </table>
     </main></code>     </main></code>
Line 157: Line 149:
  
 ==== Repackaging Data ==== ==== Repackaging Data ====
-  * While what we've done is great, it feels like we're reprinting data unnecessarily.+  * While what we've done is great, it feels like we're reprinting data (first published etc) unnecessarily.
   * It would be better to present one line for each hero with a list of movies they've appeared in.   * It would be better to present one line for each hero with a list of movies they've appeared in.
   * To do that, let's repackage the data into another array.   * To do that, let's repackage the data into another array.
Line 165: Line 157:
   * Here we are creating an array called <html>$hero_data</html> for all the heroes and inside that, we are creating an array for each character (<html>$hero_data[$row['character_name']]</html>).   * Here we are creating an array called <html>$hero_data</html> for all the heroes and inside that, we are creating an array for each character (<html>$hero_data[$row['character_name']]</html>).
   * The character array has an element called 'hero_villain' with the value extracted from the current row of data.   * The character array has an element called 'hero_villain' with the value extracted from the current row of data.
-  * Notice that in PHP we can name an array element. This isn't possible in Javascript, where array elements are always numbered. 
   * The trick is that if the character is repeated, it will overwrite the existing data and we don't mind. That is, <html>$hero_data['Black Widow']['hero_villain']</html> will be 'Hero' every time, so we don't mind if it's overwritten.   * The trick is that if the character is repeated, it will overwrite the existing data and we don't mind. That is, <html>$hero_data['Black Widow']['hero_villain']</html> will be 'Hero' every time, so we don't mind if it's overwritten.
   * Do the same for 'first_appeared' and 'power'.   * Do the same for 'first_appeared' and 'power'.
Line 173: Line 164:
 <code>        $hero_data[$row['character_name']]['movies'       .= $row['movie'] . "<br>";</code> <code>        $hero_data[$row['character_name']]['movies'       .= $row['movie'] . "<br>";</code>
   * The <html><br></html> added after each movie will move each to its own line in the table cell so it's easier for the user to read.   * The <html><br></html> added after each movie will move each to its own line in the table cell so it's easier for the user to read.
- 
-==== Foreach ==== 
-  * There's another loop that is extremely useful for processing arrays. It's the 'foreach' loop. 
-  * Add the following code to the end of the last block of PHP code. 
-<code>    $my_array = array('item1' => 'dog', 'item2' => 'elephant', 'item3' => 'rabbit'); 
-    foreach($my_array as $name => $item) { 
-        error_log("MURRAY: $name is a $item"); 
-    }</code> 
-  * The first line creates an array, but unlike the arrays we've seen, each item in the array is named. 
-  * Instead of referring to an item by number (<html>$my_array[0]</html>) we can refer to each item by name (<html>$my_array['item2']</html>). 
-  * The second line sets up the loop. It says 'run through this code for each item in the array <html>$my_array</html>, where the reference for each item is <html>$name</html> and the item itself is <html>$item</html>'. 
-  * We can now refer to the name and the actual item by using the variables <html>$name</html> and <html>$item</html>. 
-  * <html>error_log</html> then reproduces these values so that we can read them in the error log. 
-  * Try it now to be sure you understand it. 
-  * The value of this is that we don't need any extra code to determine the length of the array. 
   * Now, to display our hero data, we can loop through the <html>$hero_data</html> array.   * Now, to display our hero data, we can loop through the <html>$hero_data</html> array.
 <code>    foreach($hero_data as $name => $details) { <code>    foreach($hero_data as $name => $details) {
Line 201: Line 177:
                     <td><?php echo $details['movies'];?></td>                     <td><?php echo $details['movies'];?></td>
                 </tr></code>                 </tr></code>
-  * Run this code to see that it shows a single row per hero and lists all the movies (all those captured in the database) in the last cell.+  * Run this code to see that it shows a single table row per hero and lists all the movies (all those captured in the database) in the last cell.
   * Here's the final code in case you are having trouble with placement of the various items.   * Here's the final code in case you are having trouble with placement of the various items.
 <code><?php <code><?php
en/web_development/databases/php.1640301830.txt.gz · Last modified: 2023/08/16 09:33 (external edit)