Results of Inserting MySQL PHP in Echo

Instructions:
Insert SQL
SQL, or Structured Query Language, provides a range of statements for managing MySQL data. The following sample code demonstrates a typical insert statement:
INSERT INTO product VALUES (1, ‘Hat’);
This statement specifies the table and provides values to insert into each column. The following alternative version may also be used:
INSERT INTO product (productID, productName) VALUES (1, ‘Hat’);
In this case the statement specifies the name of each column in the table as well as the values to insert. Some developers prefer this because it is easier to verify that each data item has been included in the values section.
PHP Execution
PHP scripts can execute insert statements on MySQL tables. The following sample code demonstrates:
$insert_query="INSERT INTO product (productID, productName) VALUES (1, ‘Hat’)";
mysql_query($insert_query);
The first line here stores the query string as a variable, and then the second executes it on the database. The "mysql_query" statement in PHP allows developers to execute various types of query, including updates and inserts. Once this line executes, the script has attempted to insert the data on the specified table, but the developer does not necessarily know that it has been successful.
Result
To verify the success of an insert operation, the PHP developer can retrieve the result of the "mysql_query" function. The following extended line of code demonstrates:
$insert_result=mysql_query($insert_query);
When PHP executes any query, it returns a Boolean value indicating true if the query was successful and false if it was unsuccessful. This is often a worthwhile step, particularly in cases where the query update has some other effect within the system. When connecting to and querying a database, many things can cause problems, such as a failure in the database connection or on the data server. The script can use the Boolean result value to respond to the success or failure of the operation.
Output
In response to the query result, some developers output HTML and text to the browser. The following sample PHP code demonstrates, after the insert query:
echo "<p>".$insert_result."</p>";
Alternatively, the developer can output a custom message, as follows:
if($insert_result) echo "<p>Thanks! Your insert was successful.</p>";
else echo "<p>Whoops! Something went wrong.</p>"
In both cases, the result is sent to the user’s browser in HTML markup structures. If something does go wrong during the insert process, at least the user will know.
Sign up for our daily email newsletter:
You must log in to post a comment.