Making MySQL Queries

Author Topic: Making MySQL Queries  (Read 1791 times)

Offline chinmay.sahooTopic starter

  • Trade Count: (0)
  • Full Member
  • ***
  • Thank You 2
  • Posts: 158
  • Karma: 0
    • We Helpline
Making MySQL Queries
« on: 12-23-2015, 04:45:59 »
A database query from PHP is basically a MySQL command wrapped up in a tiny PHP function called mysql_query(). This is where you use the basic SQL workhorses of SELECT, INSERT, UPDATE, and DELETE that we discussed in Chapter 13. The MySQL commands to CREATE or DROP a table (but not, thankfully, those to create or drop an entire database) can also be used with this PHP function if you do not wish to make your databases using the MySQL client.

You could write a query in the simplest possible way, as follows:

mysql_query(“SELECT Surname FROM personal_info WHERE ID<10”);

PHP would dutifully try to execute it. However, there are very good reasons to split up this and similar commands into two lines with extra variables, like this:

$query = “SELECT Surname FROM personal_info WHERE ID<10”;
$result = mysql_query($query);

The main rationale is that the extra variable gives you a handle on an extremely valuable piece of information. Every MySQL query gives you a receipt whether you succeed or not— sort of like a cash machine when you try to withdraw money. If things go well, you hardly need or notice the receipt—you can throw it away without a qualm. But if a problem occurs, the receipt will give you a clue as to what might have gone wrong, similar to the “Is the machine not dispensing or is your account overdrawn?” type of message that might be printed on your
ATM receipt.

Another advantage of assigning the query string to a variable is that you can more easily view the query if you run into an error. Of course, you would accomplish this by writing the variable out to an error log—never by dumping it out to the browser in production!

The function mysql_query takes as arguments the query string (which should not have a semicolon within the double quotes) and optionally a link identifier. Unless you have multiple connections, you don’t need the link identifier. It returns a TRUE (nonzero) integer value if the query was executed successfully even if no rows were affected. It returns a FALSE integer if the query was illegal or not properly executed for some other reason.


Related Topics

  Subject / Started by Replies Last post

Started by Xatsker PHP Forum

3 Replies
Last post 02-17-2012, 04:06:57
by seoguro
7 Replies
Last post 09-22-2022, 10:26:42
by dark404
6 Replies
Last post 10-06-2022, 05:28:54
by f1dark
1 Replies
Last post 01-04-2014, 02:37:25
by Luca tall
3 Replies
Last post 09-08-2014, 00:52:42
by stonewood