Apa itu situs web basis data mysql?

Artikel berikut adalah kutipan dari PHP & MySQL. Novice to Ninja, 7th Edition, panduan praktis untuk mempelajari semua alat, prinsip, dan teknik yang diperlukan untuk membuat aplikasi web profesional. Dalam tutorial terakhir dalam seri ini, Anda akan belajar cara mengambil informasi yang disimpan dalam database MySQL dan menampilkannya di halaman web untuk dilihat semua orang


  • Menyiapkan Lingkungan Pengembangan PHP Anda dengan Docker
  • Panduan Pemula untuk PHP
  • Memperkenalkan MySQL. Panduan Pemula
  • Menampilkan Data dari MySQL di Web. sebuah Pendahuluan

Ini dia — hal-hal yang Anda daftarkan. Dalam bab ini, Anda akan mempelajari cara mengambil informasi yang disimpan dalam database MySQL dan menampilkannya di halaman web untuk dilihat semua orang

Sejauh ini, Anda telah menulis kode PHP pertama Anda dan mempelajari dasar-dasar MySQL, mesin basis data relasional, dan PHP, bahasa skrip sisi server

Now you’re ready to learn how to use these tools together to create a website where users can view data from the database and even add their own

Note. as in Chapter 3, I’m using “MySQL” here to refer to the database protocol. Your PHP scripts will do the same. There are numerous references in this chapter — and in the PHP code you’ll write — to “MySQL”, even though we’re actually connecting to a MariaDB database

Apa itu situs web basis data mysql?

The Big Picture

Before we leap forward, it’s worth taking a step back for a clear picture of our ultimate goal. We have two powerful tools at our disposal. the PHP scripting language and the MySQL database engine. It’s important to understand how these will fit together

The purpose of using MySQL for our website is to allow the content to be pulled dynamically from the database to create web pages for viewing in a regular browser. So, at one end of the system you have a visitor to your site using a web browser to request a page. That browser expects to receive a standard HTML document in return. At the other end you have the content of your site, which sits in one or more tables in a MySQL database that only understands how to respond to SQL queries (commands)

Apa itu situs web basis data mysql?

As shown in the image above, the PHP scripting language is the go-between that speaks both languages. It processes the page request and fetches the data from the MySQL database using SQL queries just like those you used to create a table of jokes in Chapter 3. It then spits it out dynamically as the nicely formatted HTML page that the browser expects

Just so it’s clear and fresh in your mind, this is what happens when there’s a visitor to a page on your website

  1. The visitor’s web browser requests the web page from your web server
  2. The web server software (typically Apache or NGINX) recognizes that the requested file is a PHP script, so the server fires up the PHP interpreter to execute the code contained in the file
  3. Certain PHP commands (which will be the focus of this chapter) connect to the MySQL database and request the content that belongs in the web page
  4. The MySQL database responds by sending the requested content to the PHP script
  5. The PHP script stores the content into one or more PHP variables, then uses
    $myObject = new SomeClass();    // create an object
    $myObject->someProperty = 123;  // set a property's value
    echo $myObject->someProperty;   // get a property's value
    
    1 statements to output the content as part of the web page
  6. The PHP interpreter finishes up by handing a copy of the HTML it has created to the web server
  7. The web server sends the HTML to the web browser as it would a plain HTML file, except that instead of coming directly from an HTML file, the page is the output provided by the PHP interpreter. The browser has no way of knowing this, however. As far as the browser is concerned, it’s requesting and receiving a web page like any other

Creating a MySQL User Account

In order for PHP to connect to your MySQL database server, it will need to use a username and password. So far, all that your joke database contains is a number of pithy bon mots, but before long it may contain sensitive information like email addresses and other private details about the users of your website. For this reason, MySQL is designed to be very secure, giving you tight control over what connections it will accept and what those connections are allowed to do

The Docker environment already contains a MySQL user in Chapter 3, which you’ve already used to log in to the MySQL server

You could connect to the database from your PHP script using the same username (

$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
2) and password (
$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
2), but it’s useful to create a new account — because if you have a web server, you may want to use it to host more than one website. By giving each website its own user account, you’ll have more control over who has access to the data for any given site. If you’re working with other developers, you can give them access to the sites they’re working on, but no more

You should create a new user account with only the specific privileges it needs to work on the

$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
4 database that your website depends upon. Let’s do that now

Untuk membuat pengguna, buka MySQL Workbench dan sambungkan ke server Anda. Then run the following queries


CREATE USER 'ijdbuser'@'%' IDENTIFIED BY 'mypassword';
GRANT ALL PRIVILEGES ON `ijdb`.* TO 'ijdbuser'@'%';

The first query is fairly self explanatory. It creates a user called

$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
5 with the password
$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
6. The
$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
7 sign after the username indicates that the database can be connected to from any location. The second query gives the user full acces to the
$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
4 schema, as a result this user can see and modify all the tables, columns and data in the
$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
4 schema but has no access to anything outside it

Now that the user

$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
5 has been created, we can use it to connect to the database. It’s possible to set up a connection in MySQL Workbench with this user, but since the permissions are limited, it’s better to keep MySQL Workbench using the
$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
2 account. Instead, we’re going to use the new user when connecting from a PHP script

Connecting to MySQL with PHP

Before you can retrieve content from your MySQL database for inclusion in a web page, you must know how to establish a connection to MySQL from inside a PHP script. So far, you’ve used an application called MySQL Workbench to connect to your database. Just as MySQL Workbench can connect directly to a running MySQL server, so too can your own PHP scripts

Although this chapter talks entirely about connecting to MySQL from PHP, we’re actually connecting to the MariaDB database discussed in the previous chapter. PHP can’t see any difference between MySQL and MariaDB, as they’re interchangeable. I’ll refer to the database as MySQL throughout, because all of the commands used could be used to connect to a MySQL or MariaDB database server

The original MySQL database provided a standardized method for clients such as MySQL Workbench and PHP to communicate with the server. MariaDB copied that standard, and all the commands in PHP use the name MySQL, so to keep things simple, I’ll use the term MySQL throughout this chapter to refer to the database

There are three methods of connecting to a MySQL server from PHP

  • the MySQL library
  • the MySQLi library
  • the PDO library

These all essentially do the same job — connecting to the database and sending queries to it — but they use different code to achieve it

The MySQL library is the oldest method of connecting to the database and was introduced in PHP 2. 0. The features it contains are minimal, and it was superseded by MySQLi as of PHP 5. 0 (released in 2004)

To connect and query the database using the old MySQL library, functions such as

$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
2 and
$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
3 are used. These functions have been deprecated — meaning they should be avoided — since PHP 5. 5, and have been removed from PHP entirely since PHP 7. 0

Although most developers saw the reason for the change as soon as PHP 5. 0 was released, there are still hundreds of articles and code examples on the Web using these now non-existent

$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
4 functions — despite the fact that MySQLi has effectively been the preferred library for fifteen years

If you come across a code example that contains the line

$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
2, check the date of the article. It’s probably from the early 2000s, and in programming, you should never trust anything that old. Banyak hal berubah setiap saat — itulah sebabnya buku ini ada di edisi ketujuh

Di PHP5. 0, the MySQLi library — standing for “MySQL Improved” — was released to address some of the limitations in the original MySQL library. Anda dapat dengan mudah mengidentifikasi penggunaan MySQLi, karena kode akan menggunakan fungsi seperti

$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
6 dan
$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
7

Tak lama setelah rilis perpustakaan MySQLi di PHP 5. 0, PHP5. 1 dirilis, dengan sejumlah besar perubahan yang membantu membentuk cara kita menulis PHP hari ini (kebanyakan berkaitan dengan pemrograman berorientasi objek, yang akan Anda lihat nanti di buku ini). Salah satu perubahan besar dalam PHP 5. 1 was that it introduced a third library, PDO (PHP Data Objects), for connecting to MySQL databases

Ada beberapa perbedaan antara PDO dan MySQLi, tetapi yang utama adalah Anda dapat menggunakan pustaka PDO untuk terhubung ke hampir semua server basis data — seperti server Oracle, atau Microsoft SQL Server. Untuk pengembang, keuntungan terbesar dari pendekatan generik ini adalah, setelah Anda mempelajari cara menggunakan pustaka untuk berinteraksi dengan database MySQL, sangat mudah untuk berinteraksi dengan server database lain.

Bisa dibilang, menulis kode untuk PDO lebih mudah, dan ada beberapa nuansa yang dapat membuat kode PDO lebih mudah dibaca — parameter bernama dalam pernyataan yang disiapkan menjadi manfaat utama. (Don’t worry, I’ll explain what that means later on. )

For these reasons, most recent PHP projects use the PDO library, and it’s the library I’m going to show you how to use in this book. For more information on the differences, take a look at the SitePoint article “Re-introducing PDO – the Right Way to Access Databases in PHP”

After that little history lesson, you’re probably eager to get back to writing code. Here’s how you use PDO to establish a connection to a MySQL server

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')

For now, think of

$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
8 as a built-in function, just like the
$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
9 function we used in Chapter 2. If you’re thinking “Hey, functions can’t have spaces in their names. ”, you’re smarter than the average bear, and I’ll explain exactly what’s going on here in a moment. Bagaimanapun, dibutuhkan tiga argumen

  • a string specifying the type of database (
    new PDO('mysql:host=hostname;dbname=database', 'username',
      'password')
    
    00), the hostname of the server (
    new PDO('mysql:host=hostname;dbname=database', 'username',
      'password')
    
    01), and the name of the database (
    new PDO('mysql:host=hostname;dbname=database', 'username',
      'password')
    
    02)
  • the MySQL username you want PHP to use
  • the MySQL password for that username

You may remember from Chapter 2 that PHP functions usually return a value when they’re called. This

$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
8 “function” returns a value called a
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
04 object that identifies the connection that’s been established. Since we intend to make use of the connection, we should hold onto this value by storing it in a variable. Here’s how that looks, with the necessary values filled in to connect to your database

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');

You can probably see what’s going on with the last two arguments. they’re the username and password you created earlier in this chapter

The first argument is a little more complicated. The

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
05 part tells PDO to use the database (also referred to as a schema) called
$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
4. Any query run from PHP will default to tables in that schema.
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
07 will select records from the
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
08 table in the
$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
4 schema

Even if you’re familiar with PHP, PDO and MySQL already, the

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
10 part looks confusing. Normally, this would be
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
11 (referring to the local computer, the same machine running PHP) or pointing to a specific domain name where the database is hosted, such as
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
12

Why is it

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
10, and what does
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
14 refer to here? In Docker, each service is given a name. If you examine the
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
15 file that configures the server, the database service is called
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
14, and in Docker, one service can connect to another using the other service’s name

Arguments aside, what’s important to see here is that the value returned by

$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
8 is stored in a variable named
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
18

The MySQL server is a completely separate piece of software from the web server. Therefore, we must consider the possibility that the server may be unavailable or inaccessible due to a network outage, or because the username/password combination you provided is rejected by the server, or because you just forgot to start your MySQL server. In such cases,

$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
8 won’t run, and will throw a PHP exception

Note. at least by default, PHP can be configured so that no exception is thrown and it simply won’t connect. This isn’t generally desirable behavior, as it makes it much more difficult to work out what went wrong

If you’re wondering what it means to “throw a PHP exception”, brace yourself. You’re about to discover some more features of the PHP language

A PHP exception is what happens when you tell PHP to perform a task and it’s unable to do it. PHP will try to do what it’s told, but will fail; and in order to tell you about the failure, it will throw an exception at you. An exception is little more than PHP just crashing with a specific error message. When an exception is thrown, PHP stops. No lines of code after the error will be executed

As a responsible developer, it’s your job to catch that exception and do something about it so the program can continue

Note. if you don’t catch an exception, PHP will stop running your PHP script and display a spectacularly ugly error message. That error message will even reveal the code of your script that threw the error. In this case, that code contains your MySQL username and password, so it’s especially important to avoid the error message being seen by users

To catch an exception, you should surround the code that might throw an exception with a

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
20 statement

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}

You can think of a

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
20 statement like an
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
22 statement, except that the second block of code is what happens if the first block of code fails to run

Confused yet? I know I’m throwing (no pun intended) a lot of new concepts at you, but it will make more sense if I put it all together and show you what we have

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';

As you can see, this code is a

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
20 statement. In the
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
24 block at the top, we attempt to connect to the database using
$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
8. If this succeeds, we store the resulting PDO object in
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
18 so that we can work with our new database connection. If the connection is successful, the
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
27 variable is set to a message that will be displayed later

Importantly, inside a

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
20 statement, any code after an exception has been thrown won’t get executed. In this case, if connecting to the database throws an exception (maybe the password is wrong, or the server isn’t responding), the
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
27 variable will never get set to “Database connection established”

If our database connection attempt fails, PHP will throw a

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
30, which is the type of exception that
$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
8 throws. Our
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
32 block, therefore, says that it will catch a PDOException (and store it in a variable named
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
33). Inside that block, we set the variable
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
27 to contain a message about what went wrong

However, this error message isn’t particularly useful. All it tells us is that PDO couldn’t connect to the database server. It would be better to have some information about why that was — for example, because the username and password were invalid

The

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
33 variable contains details about the exception that occurred, including an error message describing the problem. We can add this to the output variable using concatenation

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    'mypassword');
   $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server: ' . $e->getMessage();
}

include  __DIR__ . '/../templates/output.html.php';

Catatan. the

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
33 variable isn’t a string, but an object. We’ll come to what that means shortly. For now, though, all you need to know is that the code
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
37 gets the error message based on the specific exception that occurred

Like an

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
22 statement, one of the two branches of a
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
20 statement is guaranteed to run. Either the code in the
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
24 block will execute successfully, or the code in the
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
32 block will run. Regardless of whether the database connection was successful, there will be a message in the
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
27 variable — either the error message, or the message saying the connection was successful

Finally, regardless of whether the

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
24 block was successful, or the
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
32 block runs, the template
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
45 is included. This is a generic template that just displays some text to the page

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Script Output</title>
  </head>
  <body>
      <?php echo $output; ?>
  </body>
</html>

The complete code can be found in Example. MySQL-Connect

When the template is included, it will display either the error message or the “Database connection established” message

I hope the aforementioned code is now making some sense to you. Feel free to go back to the start of this section and read it all again if you’re lost, as there were some tricky concepts in there. Once you have a firm grip on the code, however, you’ll probably realize that I’ve still left one mystery unexplained. PDOs. Just what exactly is

$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
8, and when I said it returns a “PDO object”, just what exactly is an object?

Note. all downloaded sample code includes a schema called

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
47 and a user called
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
47, so that you’re able to run it regardless of what you called your schema and user. A file containing the database is provided as
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
49, which you can import

If you use the web-based sample code viewer provided, the

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
50 database will be created as you load a sample, but any changes to this schema will be lost when you view another sample. (You can mess things up, and switching to another sample and back will reset it, but if you want to keep any changes you make, make them in the schema you created. )

If you want to load the sample data into your schema using MySQL Workbench, import

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
49 from the
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
52 directory by selecting Data Import/Restore. Then select Import from self-contained file, browse to
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
49, and select your schema name in default target schema. If you have created any tables with the same name, they’ll be overwritten and all records lost

A Crash Course in Object-oriented Programming

You may have noticed the word “object” beginning to creep into my vocabulary in the previous section. PDO adalah ekstensi Objek Data PHP, dan

$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
8 mengembalikan objek PDO. In this section, I’d like to explain what objects are all about

Perhaps you’ve come across the term object-oriented programming (OOP) in your own explorations of PHP or of programming in general. OOP is an advanced style of programming that’s especially suited to building really complex programs with a lot of parts. Most programming languages in active use today support OOP. Some of them even require you to work in an OOP style. PHP is a little more easygoing about it, and leaves it up to the developer to decide whether or not to write their scripts in the OOP style

So far, we’ve written our PHP code in a simpler style called procedural programming, and we’ll continue to do so for now, with a more detailed look at objects later on. Gaya prosedural sangat cocok untuk proyek yang relatif sederhana yang sedang kami tangani saat ini. Namun, hampir semua proyek kompleks yang Anda temui menggunakan OOP, dan saya akan membahasnya lebih detail nanti di buku ini.

Konon, ekstensi PDO yang akan kita gunakan untuk terhubung dan bekerja dengan database MySQL dirancang dengan gaya pemrograman berorientasi objek. Artinya, daripada sekadar memanggil fungsi untuk terhubung ke MySQL dan kemudian memanggil fungsi lain yang menggunakan koneksi itu, pertama-tama kita harus membuat objek PDO yang akan mewakili koneksi database kita, lalu menggunakan fitur objek tersebut untuk bekerja dengan

Membuat objek sangat mirip dengan memanggil fungsi. Faktanya, Anda sudah melihat cara melakukannya

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');

Kata kunci

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_55 memberi tahu PHP bahwa Anda ingin membuat objek baru. Anda kemudian meninggalkan spasi dan menentukan nama kelas, yang memberi tahu PHP jenis objek apa yang ingin Anda buat. Kelas adalah sekumpulan instruksi yang akan diikuti PHP untuk membuat objek. Anda dapat menganggap kelas sebagai resep, seperti kue, dan objek sebagai kue sebenarnya yang dihasilkan dari mengikuti resep. Kelas yang berbeda dapat menghasilkan objek yang berbeda, seperti halnya resep yang berbeda dapat menghasilkan masakan yang berbeda

Sama seperti PHP hadir dengan banyak fungsi bawaan yang dapat Anda panggil, PHP hadir dengan pustaka kelas tempat Anda dapat membuat objek.

$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
8, oleh karena itu, memberi tahu PHP untuk membuat objek
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
04 baru — yaitu, objek baru dari kelas
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
04 bawaan

In PHP, an object is a value, just like a string, number, or array. You can store an object in a variable or pass it to a function as an argument — all the same stuff you can do with other PHP values. Objects, however, have some useful additional features

First of all, an object behaves a lot like an array, in that it acts as a container for other values. As we saw in Chapter 2, you can access a value inside an array by specifying its index (for example,

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
59). When it comes to objects, the concepts are similar but the names and code are different. Rather than accessing the value stored in an array index, we say that we’re accessing a property of the object. Instead of using square brackets to specify the name of the property we want to access, we use arrow notation (
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
60) — for instance,
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
61

$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value

Whereas arrays are normally used to store a list of similar values (such as an array of birthdays), objects are used to store a list of related values (for example, the properties of a database connection). Still, if that’s all objects did, there wouldn’t be much point to them. we might just as well use an array to store these values, right? Of course, objects do more

In addition to storing a collection of properties and their values, objects can contain a group of functions designed to bring us more useful features. A function stored in an object is called a method (one of the more confusing names in the programming world, if you ask me). Metode hanyalah fungsi di dalam kelas. Lebih membingungkan lagi, ketika kita mulai menulis kelas kita sendiri, metode ditentukan menggunakan kata kunci

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
62. Bahkan pengembang berpengalaman sering salah menggunakan fungsi dan metode secara bergantian

Untuk memanggil metode, kami kembali menggunakan notasi panah —

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
63

$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method

Sama seperti fungsi mandiri, metode dapat menerima argumen dan mengembalikan nilai

Pada tahap ini, ini mungkin terdengar agak rumit dan tidak berguna, tapi percayalah. menyatukan kumpulan variabel (properti) dan fungsi (metode) ke dalam bundel kecil yang disebut objek menghasilkan kode yang jauh lebih rapi dan lebih mudah dibaca untuk tugas tertentu — bekerja dengan database hanyalah salah satunya. Suatu hari, Anda bahkan mungkin ingin mengembangkan kelas khusus yang dapat Anda gunakan untuk membuat objek rancangan Anda sendiri

Namun, untuk saat ini, kami akan tetap menggunakan kelas yang disertakan dengan PHP. Mari terus bekerja dengan objek

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_04 yang telah kita buat, dan lihat apa yang dapat kita lakukan dengan memanggil salah satu metodenya

Konfigurasi Koneksi

Sejauh ini, saya telah menunjukkan kepada Anda cara membuat objek

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
04 untuk membuat koneksi dengan database MySQL Anda, dan cara menampilkan pesan kesalahan yang berarti ketika terjadi kesalahan

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_0

Namun, dengan asumsi koneksi berhasil, Anda perlu mengonfigurasinya sebelum digunakan. You can configure your connection by calling some methods of your new

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
04 object

Sebelum mengirim kueri ke database, kita harus mengonfigurasi pengkodean karakter koneksi database kita. Seperti yang saya sebutkan secara singkat di Bab 2, Anda harus menggunakan teks berenkode UTF-8 di situs web Anda untuk memaksimalkan rentang karakter yang dimiliki pengguna saat mengisi formulir di situs Anda. Secara default, ketika PHP terhubung ke MySQL, ia menggunakan pengkodean ISO-8859-1 (atau Latin-1) yang lebih sederhana daripada UTF-8. Jika kita membiarkannya apa adanya, kita tidak akan dapat dengan mudah memasukkan karakter China, Arab, atau sebagian besar non-Inggris

Meskipun Anda 100% yakin bahwa situs web Anda hanya akan digunakan oleh penutur bahasa Inggris, ada masalah lain yang disebabkan karena tidak mengatur rangkaian karakter. Jika halaman web Anda tidak disetel ke UTF-8, Anda akan mengalami masalah saat orang menulis karakter tertentu seperti kutipan keriting

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
67 ke dalam kotak teks, karena karakter tersebut akan muncul di database sebagai karakter yang berbeda

Oleh karena itu, kita sekarang perlu menyetel objek ________18______04 baru kita untuk menggunakan pengkodean UTF-8

Kita dapat menginstruksikan PHP untuk menggunakan UTF-8 saat menanyakan database dengan menambahkan

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
69 ke string koneksi. Tidak ada kerugian untuk melakukan ini, asalkan skrip PHP Anda juga dikirim ke browser sebagai
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
70 (yang merupakan default di versi PHP terbaru)

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_1

Catatan. jika Anda mencari, Anda akan menemukan berbagai cara untuk menyetel rangkaian karakter, dan edisi sebelumnya dari buku ini menginstruksikan Anda untuk menggunakan kode ini

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_2

Ini karena, hingga PHP 5. 3. 6, opsi charset tidak diterapkan dengan benar oleh PHP. Karena ini diperbaiki dalam versi PHP apa pun yang sebenarnya akan Anda gunakan, menyetel charset sebagai bagian dari string koneksi adalah pilihan yang lebih disukai

Kode lengkap yang kami gunakan untuk terhubung ke MySQL dan kemudian mengkonfigurasi koneksi itu, oleh karena itu, ditampilkan di bawah ini

Contoh. MySQL-Connect-Lengkap

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_3

Jalankan contoh ini di browser Anda. (Jika Anda telah menempatkan kode basis data Anda di

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
71 di dalam direktori
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
72 dan file
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
45 di dalam direktori
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
74, URL untuk halaman tersebut adalah
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
75. )

Jika server Anda aktif dan berjalan, dan semuanya berfungsi dengan baik, Anda akan melihat pesan yang menunjukkan keberhasilan

Apa itu situs web basis data mysql?

Jika PHP tidak dapat terhubung ke server MySQL Anda, atau jika nama pengguna dan kata sandi yang Anda berikan salah, Anda malah akan melihat layar yang mirip dengan yang ditunjukkan di bawah ini. Untuk memastikan kode penanganan kesalahan Anda berfungsi dengan baik, Anda mungkin ingin salah mengeja kata sandi untuk mengujinya

Apa itu situs web basis data mysql?

Berkat blok

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_32 kami, pesan kesalahan dari database telah disertakan di halaman

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_4

Metode

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_77 mengembalikan pesan yang menjelaskan pengecualian yang terjadi. Ada beberapa metode lain — termasuk
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_78 dan
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
79 — untuk mengembalikan nama file dan nomor baris tempat pengecualian dilemparkan. Anda dapat menghasilkan pesan kesalahan yang sangat mendetail seperti ini

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_5

Ini sangat berguna jika Anda memiliki situs web besar dengan lusinan file penyertaan. Pesan kesalahan akan memberi tahu Anda file mana yang harus dicari dan di baris mana kesalahan terjadi

Jika Anda penasaran, coba masukkan beberapa kesalahan lain dalam kode koneksi basis data Anda (misalnya, nama basis data yang salah eja) dan amati pesan kesalahan mendetail yang dihasilkan. Setelah selesai, dan koneksi database Anda berfungsi dengan benar, kembali ke pesan kesalahan sederhana. Dengan cara ini, pengunjung Anda tidak akan dibombardir dengan gobbledygook teknis jika masalah nyata muncul dengan server database Anda

Dengan koneksi dibuat dan database dipilih, Anda siap untuk mulai menggunakan data yang disimpan dalam database

Anda mungkin bertanya-tanya apa yang terjadi pada koneksi dengan server MySQL setelah skrip selesai dijalankan. Jika Anda benar-benar menginginkannya, Anda dapat memaksa PHP untuk memutuskan sambungan dari server dengan membuang objek

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
04 yang mewakili koneksi Anda. Anda melakukan ini dengan menyetel variabel yang berisi objek ke
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
81

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_6

Yang mengatakan, PHP akan secara otomatis menutup semua koneksi database yang terbuka ketika selesai menjalankan skrip Anda, sehingga Anda biasanya dapat membiarkan PHP membersihkan setelah Anda

Mengirim Query SQL dengan PHP

Di Bab 3, kita terhubung ke server database MySQL menggunakan MySQL Workbench, yang memungkinkan kita mengetik kueri SQL (perintah) dan melihat hasil kueri tersebut dengan segera. Objek

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_04 menawarkan mekanisme serupa — metode exec

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_7

Di sini,

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_83 adalah string yang berisi kueri SQL apa pun yang ingin Anda jalankan

Seperti yang Anda ketahui, jika ada masalah dalam mengeksekusi kueri (misalnya, jika Anda membuat kesalahan pengetikan dalam kueri SQL), metode ini akan menampilkan

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
30 untuk Anda tangkap

Perhatikan contoh berikut, yang mencoba membuat tabel lelucon yang kita buat di Bab 3

Contoh. MySQL-Buat

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_8

Perhatikan bahwa kami menggunakan teknik pernyataan

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_20 yang sama untuk menangani kemungkinan kesalahan yang dihasilkan oleh kueri. Dimungkinkan untuk menggunakan beberapa blok
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_20 untuk menampilkan pesan kesalahan yang berbeda — satu untuk koneksi dan satu lagi untuk kueri — tetapi ini dapat menghasilkan kode tambahan yang cukup banyak

Sebagai gantinya, saya telah memilih untuk menggunakan pernyataan

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
24 yang sama untuk memuat koneksi dan kueri. Blok
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_20 akan berhenti mengeksekusi kode setelah terjadi kesalahan, jadi jika terjadi kesalahan selama koneksi database, baris
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
89 tidak akan pernah berjalan, memastikan bahwa, jika kueri dikirim ke database, koneksi harus dibuat

Pendekatan ini memberi kita sedikit kontrol atas pesan kesalahan yang ditampilkan, tetapi menghemat pengetikan pernyataan

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
20 untuk setiap operasi basis data. Nanti di buku ini, kita akan membaginya menjadi blok-blok yang berbeda, tetapi untuk saat ini, pertahankan semua operasi basis data di blok
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
24 yang sama

Contoh ini juga menggunakan metode

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_92 untuk mengambil pesan kesalahan mendetail dari server MySQL. Gambar berikut menunjukkan kesalahan yang ditampilkan saat, misalnya, tabel lelucon sudah ada

Apa itu situs web basis data mysql?

Untuk kueri

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_93,
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
94, dan
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
95 (yang berfungsi untuk memodifikasi data yang disimpan), metode
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
96 mengembalikan jumlah baris tabel (entri) yang dipengaruhi oleh kueri. Pertimbangkan perintah SQL berikut, yang kami gunakan di Bab 3 untuk mengatur tanggal semua lelucon yang berisi kata "programmer"

Contoh. Pembaruan MySQL

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_9

Dengan menyimpan nilai yang dikembalikan dari metode exec di

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
97, kita dapat menggunakan variabel dalam variabel
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
27 untuk dicetak di template

Gambar di bawah menunjukkan output dari contoh ini, dengan asumsi hanya ada satu lelucon "programmer" di database Anda

Apa itu situs web basis data mysql?

Jika Anda me-refresh halaman untuk menjalankan kueri yang sama lagi, Anda akan melihat perubahan pesan, seperti yang diperlihatkan dalam gambar berikut. Ini menunjukkan bahwa tidak ada baris yang diperbarui, karena tanggal baru yang diterapkan pada lelucon sama dengan tanggal yang ada

Apa itu situs web basis data mysql?

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_99 kueri diperlakukan sedikit berbeda, karena dapat mengambil banyak data, dan PHP menyediakan cara untuk menangani informasi tersebut

Penanganan new PDO('mysql:host=hostname;dbname=database', 'username', 'password') _99 Kumpulan Hasil

Untuk sebagian besar kueri SQL, metode

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_96 berfungsi dengan baik. Kueri melakukan sesuatu ke database Anda, dan Anda mendapatkan jumlah baris yang terpengaruh (jika ada) dari nilai pengembalian metode.
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_99 kueri, bagaimanapun, membutuhkan sesuatu yang sedikit lebih menarik daripada
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
96. Anda akan ingat bahwa
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_99 kueri digunakan untuk melihat data yang disimpan dalam database. Alih-alih hanya memengaruhi database,
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_99 kueri memiliki hasil — dan kami memerlukan metode untuk mengembalikannya

Metode kueri terlihat seperti

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_96, yang menerima kueri SQL sebagai argumen untuk dikirim ke server basis data. Apa yang dikembalikan, bagaimanapun, adalah objek
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_07, yang mewakili kumpulan hasil yang berisi daftar semua baris (entri) yang dikembalikan dari kueri

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
0

Asalkan tidak ada kesalahan yang ditemukan dalam memproses kueri, kode ini akan menyimpan kumpulan hasil (dalam bentuk objek

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
07) ke dalam variabel
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
09. Kumpulan hasil ini berisi teks dari semua lelucon yang disimpan di tabel
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
08. Karena tidak ada batasan praktis untuk jumlah lelucon dalam basis data, kumpulan hasil bisa sangat besar

Saya sebutkan kembali di Bab 2 bahwa

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_11 loop adalah struktur kontrol yang berguna ketika kita perlu mengulang tetapi tidak tahu berapa kali. Kami tidak dapat menggunakan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_12 loop, karena kami tidak tahu berapa banyak rekaman yang dikembalikan kueri. Memang, Anda bisa menggunakan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_11 loop di sini untuk memproses baris dalam kumpulan hasil satu per satu

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
1

Kondisi untuk loop

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_11 mungkin berbeda dari kondisi yang biasa Anda gunakan, jadi izinkan saya menjelaskan cara kerjanya. Pertimbangkan kondisi sebagai pernyataan dengan sendirinya

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
2

The

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
15 method of the
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
07 object returns the next row in the result set as an array (we discussed arrays in Chapter 2). Ketika tidak ada lagi baris di set hasil,
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
15 mengembalikan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
18 sebagai gantinya. (Ini adalah satu kasus di mana meminta objek PDO untuk melakukan sesuatu yang tidak dapat dilakukan — karena
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
15 tidak dapat mengembalikan baris berikutnya ketika tidak ada baris yang tersisa di set hasil — tidak akan melempar
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
30. Jika ya, kami tidak dapat menggunakan metode
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
15 dalam kondisi loop
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
11 seperti yang kami lakukan di sini. )

Sekarang, pernyataan di atas memberikan nilai ke variabel

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
23, tetapi, pada saat yang sama, pernyataan secara keseluruhan mengambil nilai yang sama. Inilah yang memungkinkan Anda menggunakan pernyataan sebagai kondisi dalam
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
11 loop. Karena perulangan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_11 akan terus berulang hingga kondisinya bernilai
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
18, perulangan ini akan terjadi sebanyak jumlah baris dalam kumpulan hasil, dengan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
23 mengambil nilai baris berikutnya setiap kali perulangan dijalankan. Yang tersisa untuk diketahui adalah bagaimana mengambil nilai dari variabel
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
23 setiap kali loop berjalan

Baris dari kumpulan hasil yang dikembalikan oleh

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
15 direpresentasikan sebagai larik asosiatif, dengan indeks yang dinamai sesuai kolom tabel di kumpulan hasil. Jika
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_23 adalah baris dalam himpunan hasil kita,
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
31 adalah nilai dalam kolom
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
32 dari baris tersebut

Tujuan kami dalam kode ini adalah untuk menyimpan teks dari semua lelucon sehingga kami dapat menampilkannya dalam template PHP. Cara terbaik untuk melakukannya adalah dengan menyimpan setiap lelucon sebagai item baru dalam array,

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
33

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
3

Dengan lelucon yang ditarik dari database, sekarang kita dapat meneruskannya ke template PHP

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
34

Untuk meringkas, inilah kode pengontrol untuk contoh ini sejauh ini

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
4

Variabel

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_33 adalah larik yang menyimpan daftar lelucon. Jika Anda menulis isi array dalam PHP, akan terlihat seperti ini

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
5

Namun, data telah diambil dari database daripada diketik secara manual dalam kode

Anda akan menyadari bahwa ada dua variabel berbeda yang ditetapkan —

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
33 dan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
37 — bergantung pada berhasil atau tidaknya blok
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
24

Dalam templat

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_34, kita perlu menampilkan konten larik ________26______33 atau pesan kesalahan yang terkandung dalam variabel
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
37

Untuk memeriksa apakah suatu variabel telah diberi nilai atau tidak, kita dapat menggunakan fungsi

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
42 yang kita gunakan sebelumnya untuk memeriksa apakah suatu formulir telah dikirimkan. Templat dapat menyertakan pernyataan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_43 untuk menentukan apakah akan menampilkan kesalahan atau daftar lelucon

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
6

Tidak ada yang baru di sini, tetapi untuk menampilkan lelucon, kita perlu menampilkan konten larik

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
33. Tidak seperti variabel lain yang telah kami gunakan hingga saat ini, larik
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
33 berisi lebih dari sekadar satu nilai

Cara paling umum untuk memproses array di PHP adalah dengan menggunakan loop. Kami telah melihat

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_11 loop dan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
12 loop. Loop
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_48 sangat membantu untuk memproses array

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
7

Alih-alih kondisi, tanda kurung di bagian atas loop

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
48 berisi larik, diikuti dengan kata kunci
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
50, lalu nama variabel baru yang akan digunakan untuk menyimpan setiap item larik secara bergantian. Badan perulangan kemudian dieksekusi sekali untuk setiap item dalam larik. Setiap kali item tersebut disimpan dalam variabel yang ditentukan, sehingga kode dapat mengaksesnya secara langsung

Adalah umum untuk menggunakan

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_48 loop dalam template PHP untuk menampilkan setiap item dari array secara bergantian. Begini cara mencari array ________26______33 kami

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
8

Dengan perpaduan kode PHP untuk mendeskripsikan loop dan kode HTML untuk menampilkannya, kode tersebut terlihat agak tidak rapi. Oleh karena itu, biasanya menggunakan cara penulisan alternatif

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
48 loop saat digunakan dalam template

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_9

Kedua potongan kode tersebut secara fungsional identik, tetapi yang terakhir terlihat lebih bersahabat bila dicampur dengan kode HTML. Beginilah bentuk kode ini terlihat di template

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
0

Hal yang sama dapat dilakukan dengan

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
43 pernyataan, membuatnya lebih baik untuk melihat di dalam template HTML dengan menghindari kawat gigi

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
1

Dengan alat baru ini, kita dapat menulis template kita untuk menampilkan daftar lelucon

Contoh. MySQL-ListJokes

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
2

Baik teks

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_37 ditampilkan di halaman atau setiap lelucon ditampilkan dalam satu paragraf (
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
56) yang terkandung dalam kutipan blok (
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
57), karena kami secara efektif mengutip penulis setiap lelucon di halaman ini

Karena lelucon mungkin berisi karakter yang dapat ditafsirkan sebagai kode HTML (misalnya, ________26______58,

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
59, atau
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
60), kita harus menggunakan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
61 untuk memastikan bahwa lelucon tersebut diterjemahkan ke dalam entitas karakter HTML (yaitu,
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
62,
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
63, dan ________66)

Gambar berikut menunjukkan tampilan halaman ini setelah Anda menambahkan beberapa lelucon ke database

Apa itu situs web basis data mysql?

Ingat bagaimana kami menggunakan

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_11 loop di controller kami untuk mengambil baris dari hasil
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
07 yang ditetapkan satu per satu?

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
3

Ternyata

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
07 objek dirancang untuk berperilaku seperti array saat Anda meneruskannya ke
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
48 loop. Oleh karena itu, Anda dapat sedikit menyederhanakan kode pemrosesan database Anda menggunakan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
48 loop alih-alih
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
11 loop

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
4

Saya akan menggunakan formulir ________26______48 yang lebih rapi ini di sisa buku ini

Alat bagus lainnya yang ditawarkan PHP adalah cara singkat untuk memanggil perintah

$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
1 — yang, seperti yang telah Anda lihat, perlu sering kita gunakan. Pernyataan
$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
_1 kami terlihat seperti ini

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
5

Sebagai gantinya, kita bisa menggunakan ini

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
6

Ini melakukan hal yang persis sama.

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
74 berarti
$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
1 dan memberi Anda cara yang sedikit lebih pendek untuk mencetak variabel. Namun, ada batasan untuk ini. jika Anda menggunakan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_74, Anda hanya dapat mencetak. Anda tidak dapat menyertakan pernyataan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_43, pernyataan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
12, dan seterusnya, meskipun Anda dapat menggunakan gabungan, dan dapat diikuti dengan pemanggilan fungsi

Ini adalah template yang diperbarui menggunakan gema steno

Contoh. MySQL-ListJokes-Singkatan

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
7

Saya akan menggunakan notasi steno jika sudah berlaku sejak saat ini

Catatan. dalam versi PHP sebelum 5. 4, notasi steno ini membutuhkan pengaturan PHP yang tidak umum untuk diaktifkan, sehingga tidak disarankan karena alasan kompatibilitas. Menggunakan notasi steno dapat menyebabkan kode Anda berhenti berfungsi saat berpindah dari server yang mengaktifkannya ke server yang tidak mengaktifkannya

Mulai dari PHP5. 4 (jadi versi apa pun yang secara realistis akan Anda temui hari ini), gema steno berfungsi terlepas dari pengaturan PHP, sehingga Anda dapat menggunakannya dengan aman tanpa khawatir itu mungkin tidak berfungsi di semua server

Berpikir ke depan

Pada contoh yang baru saja kita lihat, kita membuat template,

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
34, yang berisi semua HTML yang diperlukan untuk menampilkan halaman. Namun, seiring pertumbuhan situs web kami, kami akan menambahkan lebih banyak halaman. Kami pasti menginginkan halaman agar orang-orang dapat menambahkan lelucon ke situs web, dan kami juga memerlukan halaman beranda dengan beberapa teks pengantar, halaman dengan detail kontak pemilik, dan, seiring pertumbuhan situs, bahkan mungkin

Saya sedikit melompat ke depan di sini, tetapi selalu ada baiknya mempertimbangkan bagaimana sebuah proyek akan tumbuh. Jika kita menerapkan pendekatan yang baru saja kita gunakan untuk

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
34 ke template lainnya —
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
81,
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
82,
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
83,
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
84 dan seterusnya — kita akan mendapatkan banyak kode berulang

Setiap halaman di situs web akan membutuhkan template yang akan terlihat seperti ini

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
8

Sebagai seorang programmer, mengulang kode adalah salah satu hal terburuk yang dapat Anda lakukan. Faktanya, programmer sering mengacu pada prinsip KERING, yang merupakan singkatan dari "Jangan ulangi dirimu sendiri". Jika Anda mendapati diri Anda mengulang bagian kode, hampir pasti ada solusi yang lebih baik

Semua pemrogram terbaik itu malas, dan mengulang kode berarti mengulang pekerjaan. Menggunakan pendekatan salin/tempel untuk templat ini membuat situs web sangat sulit dipelihara. Bayangkan ada bagian footer dan navigasi yang ingin kita tampilkan di setiap halaman. Template kami sekarang akan terlihat seperti ini

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
_9

Kami akan mengalami masalah di tahun 2022. Jika template untuk semua halaman di situs web — misalnya,

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
34
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
81,
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
82,
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
83 dan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
84 — berisi kode dalam struktur di atas, untuk memperbarui tahun dalam pemberitahuan hak cipta menjadi “2022”, Anda harus membuka setiap

Kita bisa pintar dan membuat tanggal secara dinamis dibaca dari jam server (

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
90 jika Anda penasaran. ) untuk menghindari masalah ini, tetapi bagaimana jika kami ingin menambahkan tag
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
91 yang disertakan di setiap laman?

Mengubah lima atau enam templat mungkin sedikit mengganggu, tetapi tidak akan menimbulkan banyak masalah. Namun, bagaimana jika website bertambah hingga puluhan atau ratusan halaman?

Masalah ini dapat diselesaikan dengan serangkaian

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
92 pernyataan. Sebagai contoh

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
_0

Tetapi metode ini membutuhkan kewaskitaan. kita perlu mengantisipasi dengan tepat perubahan apa yang mungkin perlu dilakukan di masa mendatang dan menggunakan pernyataan

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
92 yang relevan di tempat yang kita perkirakan akan terjadi perubahan

Dalam contoh di atas, misalnya, mudah untuk menambahkan entri menu baru dengan menambahkannya ke

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
94, tetapi menambahkan tag
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
91 ke setiap halaman, atau bahkan sesuatu yang sepele seperti menambahkan kelas CSS ke elemen
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
96, tetap berarti membuka setiap template

Tidak ada cara untuk memprediksi secara akurat semua perubahan yang mungkin diperlukan selama masa hidup situs web, jadi pendekatan yang saya tunjukkan di awal bab ini sebenarnya lebih baik

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
_1

Jika kami selalu menyertakan template ini, yang akan kami sebut

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
97, variabel
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
27 dapat disetel ke beberapa kode HTML dan menampilkannya di halaman dengan navigasi dan footer. Manfaatnya adalah, untuk mengubah tanggal di setiap halaman situs web, kita hanya perlu mengubahnya di satu lokasi

Saya juga menyelinap dalam variabel

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
99 sehingga setiap pengontrol dapat menentukan nilai yang muncul antara
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
00 dan
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
01 tag bersama dengan beberapa CSS (tersedia sebagai
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
02 dalam kode contoh) untuk membuat halaman sedikit lebih cantik

Apa itu situs web basis data mysql?

Pengontrol apa pun sekarang dapat menggunakan

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
03 dan memberikan nilai untuk
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
27 dan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
99

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
_06 kami menggunakan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
97 diberi kode seperti yang ditunjukkan di bawah ini

Contoh. MySQL-ListJokes-Layout-1

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
_2

Tapi tunggu. Apa yang terjadi dengan

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_27 di blok
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
24? . loop membuat string yang berisi kode HTML untuk daftar lelucon

Pada prinsipnya, inilah yang kami inginkan terjadi. variabel

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_27 berisi kode HTML yang akan disisipkan di antara navigasi dan footer di
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
97, tapi saya pikir Anda akan setuju bahwa kodenya sangat jelek

Saya sudah menunjukkan cara menghindari pencampuran kode HTML dan PHP melalui pernyataan

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
92. Seperti yang kita lakukan sebelumnya, sebaiknya pindahkan HTML untuk menampilkan lelucon ke filenya sendiri — tetapi kali ini, hanya kode HTML yang unik untuk halaman daftar lelucon

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
34 di
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
74 direktori harus berisi kode ini

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
_3

Yang penting, ini hanya kode untuk menampilkan lelucon. Itu tidak berisi navigasi, footer,

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
16 tag atau apa pun yang kita ingin diulang pada setiap halaman;

Untuk menggunakan templat ini, Anda dapat mencoba yang berikut ini

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
_4

Atau jika Anda sangat pintar

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
_5

Dengan pendekatan ini, logika Anda akan sepenuhnya masuk akal. Kita perlu menyertakan

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_34. Sayangnya, pernyataan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_92 hanya mengeksekusi kode dari file yang disertakan pada titik yang disebut. Jika Anda menjalankan kode di atas, hasilnya akan menjadi seperti ini

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
_6

Karena

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
34 disertakan terlebih dahulu, dikirim ke browser terlebih dahulu. Apa yang perlu kita lakukan adalah memuat
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_34, tetapi alih-alih mengirim output langsung ke browser, kita perlu menangkapnya dan menyimpannya dalam variabel
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
27 sehingga dapat digunakan nanti oleh
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
97

Pernyataan

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_92 tidak mengembalikan nilai, jadi
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
24 tidak memiliki efek yang diinginkan, dan PHP tidak memiliki pernyataan alternatif untuk melakukannya. Namun, itu tidak berarti bahwa itu tidak mungkin

PHP memang memiliki fitur berguna yang disebut "buffer output". Mungkin terdengar rumit, tetapi konsepnya sebenarnya sangat sederhana. when you use

$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
1 to print something, or
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
92 to include a file that contains HTML, usually it’s sent directly to the browser. Dengan memanfaatkan buffering keluaran, alih-alih mengirim keluaran langsung ke browser, kode HTML disimpan di server dalam "buffer", yang pada dasarnya hanyalah sebuah string yang berisi semua yang telah dicetak sejauh ini.

Lebih baik lagi, PHP memungkinkan Anda mengaktifkan buffer dan membaca isinya kapan saja

Ada dua fungsi yang kita butuhkan

  • try {
      ⋮ do something risky
    }
    catch (ExceptionType $e) {
      ⋮ handle the exception
    }
    
    27, yang memulai buffer keluaran. Setelah memanggil fungsi ini, apa pun yang dicetak melalui
    $myObject = new SomeClass();    // create an object
    $myObject->someProperty = 123;  // set a property's value
    echo $myObject->someProperty;   // get a property's value
    
    _1 atau HTML yang dicetak melalui
    $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
      'mypassword');
    
    92 akan disimpan dalam buffer daripada dikirim ke browser
  • try {
      ⋮ do something risky
    }
    catch (ExceptionType $e) {
      ⋮ handle the exception
    }
    
    30, yang mengembalikan konten buffer dan menghapusnya

Seperti yang mungkin sudah Anda duga, "ob" pada nama fungsi adalah singkatan dari "output buffer"

Untuk menangkap konten dari file yang disertakan, kita hanya perlu menggunakan kedua fungsi ini

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
_7

Saat kode ini berjalan, variabel

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
27 akan berisi HTML yang dibuat di template
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
34

Kami akan menggunakan pendekatan ini mulai sekarang. Setiap halaman akan terdiri dari dua template

  • $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
      'mypassword');
    
    97, yang berisi semua HTML umum yang dibutuhkan oleh setiap halaman
  • template unik yang hanya berisi kode HTML yang unik untuk halaman tersebut

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
_06 lengkap terlihat seperti ini

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
_8

Mari buat tautan "Beranda" berfungsi dengan menambahkan file

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
71. Kami bisa meletakkan apa saja di halaman ini. lelucon terbaru, lelucon terbaik bulan ini, atau apapun yang kita suka. Untuk saat ini, kami akan tetap sederhana dan hanya memiliki pesan yang mengatakan "Selamat datang di Internet Joke Database"

Buat file bernama

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_82 di folder
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
74

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
_9

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_71 kami jauh lebih sederhana daripada
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
34. Itu tidak mendapatkan informasi apa pun dari database, jadi tidak memerlukan koneksi database dan kami tidak memerlukan pernyataan
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
20, jadi kami hanya akan memuat dua templat dan mengatur variabel
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
99 dan
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
27

Contoh. MySQL-ListJokes-Layout-3

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    'mypassword');
   $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server: ' . $e->getMessage();
}

include  __DIR__ . '/../templates/output.html.php';
0

Catatan. itu praktik yang baik untuk hanya terhubung ke database jika Anda perlu. Basis data adalah hambatan kinerja yang paling umum di banyak situs web, jadi sebaiknya buat koneksi sesedikit mungkin

Uji apakah kedua halaman berfungsi di browser Anda. Anda harus memiliki daftar lelucon yang terlihat saat Anda mengunjungi

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
43 dan pesan selamat datang di
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
43. Kedua halaman harus berisi navigasi dan footer

Coba ubah

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_97. Perubahan yang Anda buat akan muncul di kedua halaman. Jika situs memiliki lusinan halaman, perubahan tata letak akan memengaruhi setiap halaman

Memasukkan Data ke dalam Database

Di bagian ini, saya akan mendemonstrasikan cara menggunakan alat yang Anda inginkan untuk memungkinkan pengunjung situs menambahkan lelucon mereka sendiri ke database

Jika Anda ingin membiarkan pengunjung situs Anda memasukkan lelucon baru, Anda jelas memerlukan formulir. Ini adalah template untuk formulir yang sesuai dengan tagihan

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    'mypassword');
   $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server: ' . $e->getMessage();
}

include  __DIR__ . '/../templates/output.html.php';
_1

Simpan ini sebagai

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_81 di direktori
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
74

Bagian terpenting dari elemen

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
_48 adalah atribut
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
49. Atribut
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
_49 memberi tahu browser ke mana mengirim data setelah formulir dikirimkan. Ini bisa menjadi nama file, seperti
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
51

Namun, jika Anda mengosongkan atribut dengan menyetelnya ke

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
52, data yang diberikan oleh pengguna akan dikirim kembali ke halaman yang sedang Anda lihat. Jika URL browser menunjukkan halaman sebagai
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
53, itu adalah data yang akan dikirim saat pengguna menekan tombol Add

Mari kaitkan formulir ini dengan contoh sebelumnya, yang menampilkan daftar lelucon di database. Buka

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_97 dan tambahkan URL ke tautan "Tambahkan Lelucon baru" yang mengarah ke
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
53

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    'mypassword');
   $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server: ' . $e->getMessage();
}

include  __DIR__ . '/../templates/output.html.php';
_2

Meskipun Anda memiliki

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_97 terbuka, sertakan lembar gaya
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
57 dari Bab 2 seperti yang saya miliki di atas. Sekarang, setiap form yang ditampilkan di dalam layout akan memiliki style yang kita gunakan sebelumnya

Saat formulir ini dikirimkan, permintaan akan menyertakan variabel —

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
32 — yang berisi teks lelucon seperti yang diketik di area teks. Variabel ini kemudian akan muncul di array
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
59 yang dibuat oleh PHP

Mari buat

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
_53 di direktori
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
72. Logika dasar untuk pengontrol ini adalah

  • Jika tidak ada variabel
    $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
      'mypassword');
    
    _32 POST yang disetel, tampilkan formulir
  • Jika tidak, masukkan lelucon yang disediakan ke dalam database

Buat kerangka ini

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
_53

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    'mypassword');
   $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server: ' . $e->getMessage();
}

include  __DIR__ . '/../templates/output.html.php';
_3

Pernyataan

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
43 pembuka ini memeriksa apakah array
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
59 berisi variabel bernama
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
32. Jika disetel, formulir telah dikirimkan. Jika tidak, formulir dari
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_81 dimuat ke dalam variabel
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
27 untuk ditampilkan di browser

Jika Anda membuka

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
_53 di browser Anda saat ini, Anda akan melihat formulirnya, tetapi mengetik lelucon dan menekan Tambah tidak akan berfungsi, karena kami belum melakukan apa pun dengan data yang terkandung di
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
70

Untuk memasukkan lelucon yang dikirimkan ke dalam database, kita harus mengeksekusi kueri

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
94 menggunakan nilai yang disimpan di
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
70 untuk mengisi kolom
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
32 dari tabel
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
08. Ini mungkin mengarahkan Anda untuk menulis beberapa kode seperti ini

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    'mypassword');
   $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server: ' . $e->getMessage();
}

include  __DIR__ . '/../templates/output.html.php';
_4

Namun, ada masalah serius dengan kode ini. isi

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
70 sepenuhnya berada di bawah kendali pengguna yang mengirimkan formulir. Jika pengguna jahat mengetikkan beberapa kode SQL jahat ke dalam formulir, skrip ini akan memasukkannya ke server MySQL Anda tanpa pertanyaan. Jenis serangan ini disebut serangan injeksi SQL, dan pada masa awal PHP ini adalah salah satu lubang keamanan paling umum yang ditemukan dan dieksploitasi oleh peretas di situs web berbasis PHP. (Di banyak ceruk pemrograman, serangan injeksi SQL masih sangat efektif, karena pengembang tidak mengharapkannya. Pertimbangkan upaya luar biasa ini untuk menyebabkan kamera lalu lintas menjatuhkan basis data mereka. “Plat Nomor Injeksi SQL Berharap untuk Menggagalkan Kamera Lalu Lintas Euro”. )

Seorang pengguna mungkin mengetik ini ke dalam kotak teks

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    'mypassword');
   $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server: ' . $e->getMessage();
}

include  __DIR__ . '/../templates/output.html.php';
_5

Kueri yang dikirim ke database adalah sebagai berikut

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    'mypassword');
   $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server: ' . $e->getMessage();
}

include  __DIR__ . '/../templates/output.html.php';
_6

Tetapi bagaimana jika pengguna mengetik berikut ini

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    'mypassword');
   $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server: ' . $e->getMessage();
}

include  __DIR__ . '/../templates/output.html.php';
_7

Dalam hal ini, kueri yang dikirim ke database adalah ini

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    'mypassword');
   $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server: ' . $e->getMessage();
}

include  __DIR__ . '/../templates/output.html.php';
_8

Karena lelucon berisi karakter kutipan, MySQL akan mengembalikan kesalahan, karena akan melihat kutipan sebelum "mendapatkan" sebagai akhir dari string

Untuk menjadikan ini kueri yang valid, kita perlu meng-escape semua tanda kutip dalam teks sehingga kueri yang dikirim ke database menjadi this

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    'mypassword');
   $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server: ' . $e->getMessage();
}

include  __DIR__ . '/../templates/output.html.php';
_9

Data tidak dimasukkan jika berisi kutipan merupakan masalah yang mengganggu bagi pengguna. Mereka akan kehilangan apa pun yang mereka ketik. Tetapi pengguna jahat dapat menyalahgunakan ini. Di versi PHP yang lebih lama, dimungkinkan untuk menjalankan beberapa kueri dari PHP dengan memisahkannya dengan titik koma (

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
76)

Bayangkan jika pengguna mengetik ini ke dalam kotak

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Script Output</title>
  </head>
  <body>
      <?php echo $output; ?>
  </body>
</html>
0

Ini akan mengirimkan kueri berikut ke database

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Script Output</title>
  </head>
  <body>
      <?php echo $output; ?>
  </body>
</html>
1

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
77 adalah satu baris komentar di MySQL, jadi baris terakhir akan diabaikan, dan kueri
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
94 akan dijalankan, diikuti dengan kueri
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
93 yang telah diketik pengguna ke dalam kotak. Faktanya, pengguna dapat mengetik kueri apa pun yang mereka suka ke dalam kotak dan kueri tersebut akan dijalankan di database

Kutipan Ajaib

Pada hari-hari awal PHP, serangan injeksi SQL sangat ditakuti sehingga tim di belakang PHP menambahkan beberapa perlindungan bawaan terhadap injeksi SQL ke bahasa tersebut. Pertama, mereka menonaktifkan kemampuan untuk mengirim banyak kueri sekaligus. Kedua, mereka menambahkan sesuatu yang disebut kutipan ajaib. Fitur pelindung PHP ini secara otomatis menganalisis semua nilai yang dikirimkan oleh browser dan menyisipkan garis miring terbalik (

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
80) di depan karakter "berbahaya" seperti apostrof — yang dapat menyebabkan masalah jika disertakan dalam kueri SQL secara tidak sengaja

Masalah dengan fitur kutipan ajaib adalah menyebabkan banyak masalah seperti yang dicegah. Pertama-tama, karakter yang terdeteksi, dan metode yang digunakan untuk membersihkannya (mengawalinya dengan garis miring terbalik), hanya valid dalam beberapa keadaan. Bergantung pada pengkodean karakter situs Anda dan server basis data yang Anda gunakan, langkah-langkah ini bisa jadi sama sekali tidak efektif

Kedua, ketika nilai yang dikirimkan digunakan untuk beberapa tujuan selain membuat kueri SQL, garis miring terbalik tersebut bisa sangat mengganggu. Fitur kutipan ajaib akan menyisipkan garis miring terbalik palsu ke nama belakang pengguna jika berisi apostrof

Singkatnya, fitur kutipan ajaib adalah ide yang buruk — sedemikian rupa sehingga dihapus dari PHP dari versi 5. 4. Namun, karena usia PHP dan jumlah kode di luar sana, Anda mungkin menemukan beberapa referensi untuk itu, jadi ada baiknya memiliki pemahaman dasar tentang apa yang seharusnya dilakukan oleh fitur kutipan ajaib.

Setelah kutipan ajaib diidentifikasi sebagai ide yang buruk, saran dari pengembang PHP adalah untuk mematikannya. Namun, ini berarti bahwa ada beberapa server web yang dimatikan dan yang lainnya dihidupkan. Ini memusingkan para pengembang. mereka harus menginstruksikan semua orang yang akan menggunakan kode mereka untuk mematikannya — yang tidak mungkin dilakukan di beberapa server bersama — atau menulis kode tambahan untuk memperhitungkannya

Sebagian besar pengembang memilih yang terakhir, dan Anda mungkin menemukan beberapa kode seperti ini

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Script Output</title>
  </head>
  <body>
      <?php echo $output; ?>
  </body>
</html>
2

Jika Anda melihat pernyataan

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_43 seperti ini di kode lawas yang telah diberikan kepada Anda untuk dikerjakan, Anda dapat menghapus seluruh blok dengan aman, karena tidak ada kode di dalam pernyataan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
43 yang akan dieksekusi pada versi PHP terbaru

Jika Anda melihat kode seperti ini, itu berarti pengembang asli memahami masalah kutipan ajaib dan melakukan yang terbaik untuk mencegahnya. Mulai dari PHP5. 4 (yang tidak boleh Anda temukan, karena tidak lagi didukung),

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
83 akan selalu mengembalikan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
18 dan kode tidak akan pernah dieksekusi

Yang benar-benar perlu Anda ketahui tentang kutipan ajaib adalah bahwa itu adalah solusi yang buruk untuk masalah yang dihadapi. Tentu saja, tanpa kutipan ajaib, Anda perlu mencari solusi berbeda untuk masalah tersebut. Untungnya, kelas PDO dapat melakukan semua kerja keras untuk Anda, dengan menggunakan sesuatu yang disebut “prepared statements”

Pernyataan yang Disiapkan

Pernyataan yang disiapkan adalah jenis kueri SQL khusus yang telah Anda kirimkan ke server basis data Anda sebelumnya, memberi server kesempatan untuk mempersiapkannya untuk dieksekusi — tetapi tidak benar-benar mengeksekusinya. Anggap saja seperti menulis skrip ________43______85. Kode ada di sana, tetapi tidak benar-benar dijalankan sampai Anda mengunjungi halaman di browser web Anda. Kode SQL dalam pernyataan yang disiapkan dapat berisi placeholder yang akan Anda berikan nilainya nanti, saat kueri akan dieksekusi. Saat mengisi tempat penampung ini, PDO cukup pintar untuk menjaga dari karakter "berbahaya" secara otomatis

Inilah cara menyiapkan kueri

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_94 dan kemudian menjalankannya dengan aman dengan
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
70 sebagai teks lelucon

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Script Output</title>
  </head>
  <body>
      <?php echo $output; ?>
  </body>
</html>
3

Mari kita uraikan ini, satu pernyataan pada satu waktu. Pertama, kami menulis kueri SQL kami sebagai string PHP dan menyimpannya dalam variabel (

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
88) seperti biasa. Namun, yang tidak biasa tentang kueri
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_94 ini adalah tidak ada nilai yang ditentukan untuk kolom
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
32. Sebagai gantinya, ini berisi placeholder untuk nilai ini (
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
91). Jangan khawatir tentang bidang
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
92 tadi;

Selanjutnya, kita memanggil metode persiapan objek PDO kita (

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
18), meneruskan kueri SQL kita sebagai argumen. Ini mengirimkan kueri ke server MySQL, memintanya bersiap untuk menjalankan kueri. MySQL belum dapat menjalankannya, karena tidak ada nilai untuk kolom ________26______32. Metode
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
_95 mengembalikan objek
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
07 (ya, jenis objek yang sama yang memberi kita hasil dari kueri
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
99), yang kita simpan di
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
98

Sekarang MySQL telah menyiapkan pernyataan kami untuk dieksekusi, kami dapat mengirimkannya nilai yang hilang dengan memanggil metode ________43______99 dari objek

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
07 kami (
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
98). Kami memanggil metode ini satu kali untuk setiap nilai yang akan diberikan (dalam hal ini, kami hanya perlu menyediakan satu nilai — teks lelucon), memberikan argumen sebagai placeholder yang ingin kami isi (
try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
02) dan nilai yang ingin kami isi . Karena MySQL tahu kami mengirimkannya nilai diskrit, bukan kode SQL yang perlu diuraikan, tidak ada risiko karakter dalam nilai ditafsirkan sebagai kode SQL. Saat menggunakan pernyataan yang disiapkan, kerentanan injeksi SQL tidak mungkin terjadi

Akhirnya, kami memanggil metode

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_07 objek
try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
05 untuk memberi tahu MySQL untuk mengeksekusi kueri dengan nilai yang kami berikan. (Ya, metode
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_07 ini disebut
try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
05, tidak seperti metode serupa dari objek
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
04, yang disebut
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
96. PHP memiliki banyak kekuatan, tetapi konsistensi bukanlah salah satunya. )

Satu hal menarik yang akan Anda perhatikan tentang kode ini adalah kami tidak pernah memberi tanda kutip di sekitar teks lelucon.

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
91 ada di dalam kueri tanpa tanda kutip, dan ketika kami memanggil
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
99 kami memberikannya teks lelucon biasa dari larik
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
59. Saat menggunakan pernyataan yang disiapkan, Anda tidak memerlukan tanda kutip karena database (dalam kasus kami, MySQL) cukup cerdas untuk mengetahui bahwa teks adalah string dan akan diperlakukan seperti itu saat kueri dijalankan

Pertanyaan yang tersisa dalam kode ini adalah bagaimana menetapkan tanggal hari ini ke bidang

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
92. Kita bisa menulis beberapa kode PHP mewah untuk menghasilkan tanggal hari ini dalam format
try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
14 yang dibutuhkan MySQL, tetapi ternyata MySQL sendiri memiliki fungsi untuk melakukan ini —
try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
15

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Script Output</title>
  </head>
  <body>
      <?php echo $output; ?>
  </body>
</html>
4

Fungsi MySQL

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
15 digunakan di sini untuk menetapkan tanggal saat ini sebagai nilai kolom
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
92. MySQL sebenarnya memiliki lusinan fungsi ini, tetapi saya akan memperkenalkannya hanya sesuai kebutuhan

Sekarang setelah kami memiliki pertanyaan, kami dapat melengkapi pernyataan

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
43 yang kami mulai sebelumnya untuk menangani pengiriman formulir "Tambahkan Lelucon"

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Script Output</title>
  </head>
  <body>
      <?php echo $output; ?>
  </body>
</html>
5

Tapi tunggu. Pernyataan

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_43 ini memiliki satu trik lagi. Setelah kami menambahkan lelucon baru ke database, alih-alih menampilkan template PHP seperti sebelumnya, kami ingin mengarahkan browser pengguna kembali ke daftar lelucon. Dengan begitu, pengguna dapat melihat lelucon yang baru ditambahkan di antara mereka. Itulah yang dilakukan oleh dua baris di akhir pernyataan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
43 di atas

Untuk mencapai hasil yang diinginkan, insting pertama Anda mungkin memungkinkan pengontrol mengambil daftar lelucon dari database setelah menambahkan lelucon baru dan menampilkan daftar menggunakan templat ________26______34 seperti biasa. Masalah dengan melakukan ini adalah bahwa daftar lelucon, dari sudut pandang browser, akan menjadi hasil dari mengirimkan formulir "Tambahkan Lelucon". If the user were then to refresh the page, the browser would resubmit that form, causing another copy of the new joke to be added to the database. Ini jarang merupakan perilaku yang diinginkan

Alih-alih, kami ingin browser memperlakukan daftar lelucon yang diperbarui sebagai halaman web biasa yang dapat dimuat ulang tanpa mengirimkan ulang formulir. Cara melakukannya adalah dengan menjawab pengiriman formulir browser dengan pengalihan HTTP — respons khusus yang memberi tahu browser untuk menavigasi ke halaman lain. (HTTP adalah singkatan dari HyperText Transfer Protocol, dan merupakan bahasa yang menjelaskan komunikasi permintaan/respons yang dipertukarkan antara browser web pengunjung dan server web Anda. )

Fungsi PHP

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
_22 menyediakan cara untuk mengirim respons server khusus seperti ini, dengan memungkinkan Anda memasukkan tajuk khusus ke dalam respons yang dikirim ke browser. Untuk menandakan pengalihan, Anda harus mengirim
try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
23 header dengan URL halaman yang ingin Anda arahkan ke browser

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Script Output</title>
  </head>
  <body>
      <?php echo $output; ?>
  </body>
</html>
6

Dalam hal ini, kami ingin mengirim browser ke

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
06. Berikut adalah dua baris yang mengarahkan browser kembali ke pengontrol kami setelah menambahkan lelucon baru ke database

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Script Output</title>
  </head>
  <body>
      <?php echo $output; ?>
  </body>
</html>
7

Di bawah ini adalah kode lengkap dari pengontrol

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
53

Contoh. MySQL-AddJoke

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Script Output</title>
  </head>
  <body>
      <?php echo $output; ?>
  </body>
</html>
8

Saat Anda meninjau ini untuk memastikan semuanya masuk akal bagi Anda, perhatikan bahwa kode yang terhubung ke database dengan membuat objek

$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method
8 harus ada sebelum kode apa pun yang menjalankan kueri database. Tetapi koneksi database tidak diperlukan untuk menampilkan formulir "Tambahkan Lelucon". Koneksi hanya dilakukan ketika formulir telah dikirimkan

Muat ini dan tambahkan satu atau dua lelucon baru ke database melalui browser Anda

Itu dia. Anda dapat melihat lelucon yang ada di — dan menambahkan lelucon baru ke — database MySQL Anda

Menghapus Data dari Database

Di bagian ini, kami akan membuat satu peningkatan terakhir pada situs basis data lelucon kami. Di sebelah setiap lelucon di halaman lelucon (

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
06), kami akan menempatkan tombol berlabel Hapus. Saat diklik, itu akan menghapus lelucon itu dari database dan menampilkan daftar lelucon yang diperbarui

Jika Anda menyukai tantangan, Anda mungkin ingin mencoba menulis fitur ini sendiri sebelum membaca untuk melihat solusi saya. Meskipun kami menerapkan fitur baru, kami terutama akan menggunakan alat yang sama seperti yang digunakan pada contoh sebelumnya di bab ini. Berikut beberapa petunjuk untuk memulai

  • Anda memerlukan pengontrol baru (
    try {
      $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
        ’mypassword’);
      $output = 'Database connection established.';
    }
    catch (PDOException $e) {
      $output = 'Unable to connect to the database server.';
    }
    
    include  __DIR__ . '/../templates/output.html.php';
    
    28)
  • Perintah SQL
    new PDO('mysql:host=hostname;dbname=database', 'username',
      'password')
    
    _93 akan diperlukan, yang saya perkenalkan di Bab 3
  • Untuk menghapus lelucon tertentu di pengontrol Anda, Anda harus mengidentifikasinya secara unik. Kolom
    try {
      $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
        ’mypassword’);
      $output = 'Database connection established.';
    }
    catch (PDOException $e) {
      $output = 'Unable to connect to the database server.';
    }
    
    include  __DIR__ . '/../templates/output.html.php';
    
    _30 di tabel
    new PDO('mysql:host=hostname;dbname=database', 'username',
      'password')
    
    08 dibuat untuk melayani tujuan ini. Anda harus memberikan ID lelucon untuk dihapus dengan permintaan untuk menghapus lelucon. Cara termudah untuk melakukannya adalah dengan menggunakan bidang formulir tersembunyi

Paling tidak, luangkan waktu sejenak untuk memikirkan bagaimana Anda akan melakukan pendekatan ini. Saat Anda siap untuk melihat solusinya, baca terus

Untuk memulainya, kita perlu mengubah kueri ________18______99 yang mengambil daftar lelucon dari database. Selain kolom

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_32, kita juga harus mengambil kolom
try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
30 agar kita dapat mengidentifikasi setiap lelucon secara unik

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Script Output</title>
  </head>
  <body>
      <?php echo $output; ?>
  </body>
</html>
_9

Kita juga harus memodifikasi loop

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_11 yang menyimpan hasil database ke dalam array
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
33. Alih-alih hanya menyimpan teks dari setiap lelucon sebagai item dalam larik, kami menyimpan ID dan teks dari setiap lelucon. Salah satu cara untuk melakukan ini adalah membuat setiap item dalam larik
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
33 menjadi larik dengan caranya sendiri

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
0

Catatan. jika Anda sudah beralih menggunakan

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
48 loop untuk memproses baris hasil database Anda, itu juga akan berfungsi dengan baik

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
1

Setelah loop ini berjalan dengan sendirinya, kita akan memiliki larik

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
33, yang setiap itemnya merupakan larik asosiatif dengan dua item. ID lelucon dan teksnya. Untuk setiap lelucon (
try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
40), oleh karena itu kami dapat mengambil ID-nya (
try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
41) dan teksnya (
try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
42)

Langkah kita selanjutnya adalah memperbarui templat

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_34 untuk mengambil setiap teks lelucon dari struktur larik baru ini, serta menyediakan tombol Hapus untuk setiap lelucon

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
2

Berikut adalah sorotan dari kode yang diperbarui ini

  • Setiap lelucon akan ditampilkan dengan formulir, yang jika dikirimkan akan menghapus lelucon itu. Kami memberi sinyal ini ke pengontrol baru,
    try {
      $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
        ’mypassword’);
      $output = 'Database connection established.';
    }
    catch (PDOException $e) {
      $output = 'Unable to connect to the database server.';
    }
    
    include  __DIR__ . '/../templates/output.html.php';
    
    28, menggunakan atribut
    try {
      ⋮ do something risky
    }
    catch (ExceptionType $e) {
      ⋮ handle the exception
    }
    
    49 formulir
  • Karena setiap lelucon dalam larik
    $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
      'mypassword');
    
    _33 sekarang diwakili oleh larik dua item alih-alih string sederhana, kita harus memperbarui baris ini untuk mengambil teks lelucon. Kami melakukan ini menggunakan
    try {
      $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
        ’mypassword’);
      $output = 'Database connection established.';
    }
    catch (PDOException $e) {
      $output = 'Unable to connect to the database server.';
    }
    
    include  __DIR__ . '/../templates/output.html.php';
    
    _47 bukan hanya
    try {
      $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
        ’mypassword’);
      $output = 'Database connection established.';
    }
    catch (PDOException $e) {
      $output = 'Unable to connect to the database server.';
    }
    
    include  __DIR__ . '/../templates/output.html.php';
    
    48
  • Saat kami mengirimkan formulir untuk menghapus lelucon ini, kami mengirimkan ID lelucon yang akan dihapus. Untuk melakukan ini, kami memerlukan bidang formulir yang berisi ID lelucon, tetapi kami lebih memilih untuk menyembunyikan bidang ini dari pengguna; . Nama bidang ini adalah
    try {
      $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
        ’mypassword’);
      $output = 'Database connection established.';
    }
    catch (PDOException $e) {
      $output = 'Unable to connect to the database server.';
    }
    
    include  __DIR__ . '/../templates/output.html.php';
    
    _30, dan nilainya adalah ID lelucon yang akan dihapus (
    try {
      $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
        ’mypassword’);
      $output = 'Database connection established.';
    }
    catch (PDOException $e) {
      $output = 'Unable to connect to the database server.';
    }
    
    include  __DIR__ . '/../templates/output.html.php';
    
    51). Berbeda dengan teks lelucon, ID bukanlah nilai yang dikirimkan pengguna, jadi tidak perlu khawatir membuatnya aman untuk HTML dengan
    $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
      'mypassword');
    
    61. Kami dapat yakin itu akan menjadi angka, karena ini dibuat secara otomatis oleh MySQL untuk kolom
    try {
      $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
        ’mypassword’);
      $output = 'Database connection established.';
    }
    catch (PDOException $e) {
      $output = 'Unable to connect to the database server.';
    }
    
    include  __DIR__ . '/../templates/output.html.php';
    
    30 saat lelucon ditambahkan ke database
  • Tombol kirim (
    try {
      $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
        ’mypassword’);
      $output = 'Database connection established.';
    }
    catch (PDOException $e) {
      $output = 'Unable to connect to the database server.';
    }
    
    include  __DIR__ . '/../templates/output.html.php';
    
    _54) mengirimkan formulir saat diklik. Atribut nilainya memberinya label Hapus
  • Terakhir, kami menutup formulir untuk lelucon ini

Catatan. jika Anda tahu HTML Anda, Anda mungkin berpikir form dan input tag berada di luar elemen blockquote, karena itu bukan bagian dari teks yang dikutip (lelucon)

Sebenarnya, itu benar. formulir dan inputnya harus benar-benar sebelum atau sesudah blockquote. Sayangnya, membuat struktur tag tersebut terlihat jelas membutuhkan sedikit kode CSS (cascading style sheets) yang benar-benar di luar cakupan buku ini.

Daripada mengajari Anda teknik tata letak CSS dalam buku tentang PHP dan MySQL, saya memutuskan untuk menggunakan markup yang tidak sempurna ini. Jika Anda berencana untuk menggunakan kode ini di dunia nyata, Anda harus menginvestasikan waktu untuk mempelajari CSS (atau setidaknya mendapatkan layanan dari ahli CSS). Dengan begitu, Anda dapat mengambil kendali penuh atas markup HTML Anda tanpa mengkhawatirkan CSS yang diperlukan agar terlihat bagus. Jika Anda ingin mempelajari lebih lanjut tentang tata letak CSS, lihat CSS Master, Edisi ke-3, oleh Tiffany Brown

Tambahkan CSS berikut ke

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
_02 untuk membuat tombol muncul di sebelah kanan lelucon dan buat garis di antaranya

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
3

Gambar berikut menunjukkan seperti apa daftar lelucon dengan tombol Hapus yang ditambahkan

Apa itu situs web basis data mysql?

Tapi tunggu. Sebelum kita melanjutkan untuk membuat tombol Hapus berfungsi, mari mundur sebentar dan perhatikan baik-baik baris ini

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
4

Di sini, kami mengulangi objek

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_07, yang memberi kami variabel
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
23 yang berisi kunci
try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
30 dan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
32 bersama dengan nilai yang sesuai, dan kami menggunakannya untuk membuat larik lain dengan kunci dan nilai yang sama

Anda mungkin sudah menyadari bahwa ini sangat tidak efisien. Kami dapat mencapai hal yang sama menggunakan kode ini

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
5

Tapi seperti yang kita tahu, ini juga bisa dicapai dengan

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
48 loop

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
6

Dalam contoh ini, kami menggunakan

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_48 untuk mengulangi catatan dari database dan membuat larik. Kami kemudian mengulang array dengan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
48 loop lainnya di template. Kami hanya bisa menulis ini

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
7

Sekarang, ketika

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
33 diulangi di dalam template, itu bukan array tetapi objek
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
07. Namun, itu tidak berpengaruh pada output dan menghemat beberapa kode. In fact, we can omit the
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
09 variable altogether and load the
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
07 object directly into the
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
33 variable. Pengontrol
try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
_06 lengkap sekarang terlihat seperti ini

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
8

Sekarang kita bahkan tidak memiliki

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
11 loop iterasi pada record di controller, tetapi hanya iterasi pada record secara langsung di template, menyimpan beberapa kode dan membuat halaman dieksekusi sedikit lebih cepat, karena sekarang hanya loop pada record sekali

Kembali ke tombol Hapus baru kami. yang tersisa untuk membuat fitur baru ini berfungsi adalah menambahkan

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
28 yang relevan untuk mengeluarkan kueri
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
93 ke database

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
_9

Kode lengkap untuk

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}
_06 dan
try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
28 yang diperbarui tersedia sebagai Contoh. MySQL-DeleteJoke

Potongan kode ini berfungsi persis seperti yang kami tambahkan untuk memproses kode "Tambahkan Lelucon" sebelumnya di bab ini. Kita mulai dengan menyiapkan kueri

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
_93 dengan placeholder untuk ID lelucon yang ingin kita hapus

Tip. Anda mungkin berpikir bahwa pernyataan yang disiapkan tidak diperlukan dalam contoh ini untuk melindungi database kami dari serangan injeksi SQL, karena ID lelucon disediakan oleh bidang formulir tersembunyi yang tidak terlihat oleh pengguna. Faktanya, semua bidang formulir — bahkan yang tersembunyi — pada akhirnya berada di bawah kendali pengguna. Ada add-on browser yang didistribusikan secara luas, misalnya, yang akan membuat bidang formulir tersembunyi terlihat dan tersedia untuk diedit oleh pengguna. Ingat. nilai apa pun yang dikirimkan oleh browser pada akhirnya dicurigai dalam hal melindungi keamanan situs Anda

Kami kemudian mengikat nilai yang dikirimkan dari

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
_75 ke placeholder tersebut dan menjalankan kueri. Setelah kueri itu tercapai, kami menggunakan fungsi PHP _______46_______22 untuk meminta browser mengirim permintaan baru untuk melihat daftar lelucon yang diperbarui

Catatan. jika Anda menangani sendiri contoh ini, insting pertama Anda mungkin adalah menyediakan hyperlink Hapus untuk setiap lelucon, alih-alih bersusah payah menulis seluruh formulir HTML yang berisi tombol Hapus untuk setiap lelucon di halaman. Memang, kode untuk tautan semacam itu akan jauh lebih sederhana

$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
0

Singkatnya, hyperlink tidak boleh digunakan untuk melakukan tindakan (seperti menghapus lelucon). Mereka hanya boleh digunakan untuk menyediakan tautan ke beberapa konten terkait. Hal yang sama berlaku untuk formulir dengan

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
_77, yang seharusnya hanya digunakan untuk melakukan kueri data yang ada. Tindakan hanya boleh dilakukan sebagai hasil dari formulir dengan
try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
78 yang dikirimkan

Alasannya adalah karena formulir dengan

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
_78 diperlakukan berbeda oleh browser dan perangkat lunak terkait. Jika Anda mengirimkan formulir dengan
try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
_78 lalu mengklik tombol segarkan di browser Anda, misalnya, browser akan menanyakan apakah Anda yakin ingin mengirim ulang formulir. Peramban tidak memiliki perlindungan serupa terhadap pengiriman ulang terkait tautan dan formulir dengan
try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';
77

Mesin telusur dan perayap web lainnya juga akan mengikuti semua tautan di situs Anda untuk mengetahui kapan harus menampilkan laman situs Anda di hasil penelusuran

Jika situs Anda menghapus lelucon karena hyperlink diikuti, Anda dapat menemukan lelucon Anda dihapus setiap kali mesin pencari menemukan situs Anda

Misi selesai

Di bab ini, Anda mempelajari semua tentang PHP Data Objects (PDO), kumpulan kelas PHP bawaan (

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
04,
new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')
30, dan
$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');
07) yang memungkinkan Anda untuk berinteraksi dengan server database MySQL dengan membuat objek dan kemudian memanggil metode yang mereka gunakan. . Saat Anda melakukannya, Anda juga mempelajari dasar-dasar pemrograman berorientasi objek (OOP) — yang bukan prestasi berarti bagi pemula PHP

Dengan menggunakan objek PDO, Anda membangun situs web berbasis database pertama Anda, yang menerbitkan

$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value
4 database secara online dan memungkinkan pengunjung untuk menambah dan menghapus lelucon

Di satu sisi, Anda bisa mengatakan bab ini mencapai misi yang dinyatakan dalam buku ini. untuk mengajari Anda cara membangun situs web berbasis database. Tentu saja, contoh dalam bab ini hanya berisi hal-hal yang sangat penting. Di sisa buku ini, saya akan menunjukkan cara menyempurnakan kerangka yang Anda pelajari untuk dibuat di bab ini

In Chapter 5, we’ll return to the SQL Query window in MySQL Workbench. We’ll learn how to use relational database principles and advanced SQL queries to represent more complex types of information, and give our visitors credit for the jokes they add

We hope you’ve enjoyed this excerpt from PHP & MySQL. Novice to Ninja, 7th Edition. The full book is available on SitePoint Premium and from your favorite book and ebook retailers

Share This Article

Tom Butler

Tom Butler is a web developer and university lecturer. He has a PhD in the area of software engineering best practices and enjoys evaluating different approaches to programming problems

What is MySQL for website?

MySQL is a relational database management system that's capable of handling multiple users and databases . It runs as a server and is installed on your WordPress hosting server. Think of it as a digital filing cabinet that organizes and stores all of the data on your website.

Why do I need MySQL for a website?

MySQL is an open source relational database management system. For WordPress sites, that means it helps you store all your blog posts, users, plugin information, etc . It stores that information in separate “tables” and connects it with “keys”, which is why it's relational.

What is a database website?

A website database is an information storage system that allows access through a website . The database stores information, such as usernames and passwords, to create a better user experience. MySQL is a common choice for a website database, whereas PHP is a server-side language for accessing the database.

What is MySQL database browser?

The MySQL Database Browser included in RazorSQL allows users to browse database objects and structures . It displays information about the following types of objects for MySQL versions 5 or newer. Older versions of MySQL include a subset of these objects.