Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
MANAGING CONTENT Once the statement has been prepared, you call the execute() method. The affected_rows property records how many rows were affected by an INSERT, UPDATE, or DELETE query. However, if the query triggers a MySQL error, the value of affected_rows is –1. Unlike some computing languages, PHP treats –1 as true. So, you need to check that affected_rows is greater than zero to be sure that the query succeeded. If it is greater than zero, $OK is reset to true. 5. Finally, redirect the page to a list of existing records or display any error message. Add this code after. | MANAGING CONTENT Once the statement has been prepared you call the execute method. The affected_rows property records how many rows were affected by an INSERT UPDATE or DELETE query. However if the query triggers a MySQL error the value of affected_rows is -1. Unlike some computing languages PHP treats -1 as true. So you need to check that affected_rows is greater than zero to be sure that the query succeeded. If it is greater than zero OK is reset to true. 5. Finally redirect the page to a list of existing records or display any error message. Add this code after the previous step redirect if successful or display error if OK header Location http localhost phpsols admin blog_list_mysqli.php exit else error stmt- error 6. Add the following code block in the body of the page to display the error message if the insert operation fails h1 Insert New Blog Entry h1 php if isset error echo p Error error p form id form1 method post action The completed code is in blog_insert_mysqli.php in the ch13 folder. That completes the insert page but before testing it create blog_list_mysqli.php which is described in PHP Solution 13-3. To focus on the code that interacts with the database the scripts in this chapter don t validate the user input. In a real-world application you should use the techniques described in Chapter 5 to check the data submitted from the form and redisplay it if errors are detected. PHP Solution 13-2 Inserting a new record with PDO This PHP solution shows how to insert a new record in the blog table using a PDO prepared statement. If you haven t already done so create a folder called admin in the phpsols site root. 1. Copy blog_insert_01.php to the admin folder and save it as blog_insert_pdo.php. 2. The code that inserts a new record should be run only if the form has been submitted so it s enclosed in a conditional statement that checks for the name attribute of the submit button insert in the _POST array. Put the following in a PHP block above the DOCTYPE .