Low cost ecommerce web development India flash website design
How do I resolve errors in my SQL
queries?
If something goes wrong when you try to deal with PHP and SQL together, it's
often difficult to find the cause. The trick is to get PHP to tell you where the
problem is, bearing in mind that you must be able to hide this information from
visitors when the site goes live.
PHP provides the mysql_error function, which returns a detailed error message
from the last MySQL operation performed.
It's best used in conjunction with the trigger_error function (which will be
discussed in more detail in Chapter 10), which allows you to control the output
of the error message. Let's modify the basic connection code we saw earlier:
File: 6.php (excerpt)
// Make connection to MySQL server
if (!$dbConn = mysql_connect($host, $dbUser, $dbPass)) {
trigger_error('Could not connect to server: ' . mysql_error());
die();
}
// Select the database
if (!mysql_select_db($dbName)) {
trigger_error('Could not select database: ' . mysql_error());
die();
}
The same approach can be used with queries:
File: 6.php (excerpt)
// A query to select all articles
$sql = "SELECT * FROM articles ORDER BY title";
// Run the query, identifying the connection
if (!$queryResource = mysql_query($sql, $dbConn)) {
trigger_error('Query error ' . mysql_error() . ' SQL: ' . $sql);
}
It can be a good idea to return the complete query itself, as we've done in the
above example, particularly when you've built it using PHP variables. This allows
you to see exactly what query was performed and, if necessary, execute it directly
against MySQL to identify exactly where it went wrong.
The MySQL class discussed above will automatically use mysql_error and
trigger_error should it encounter a problem.
website designer freelance ASP PHP ecommerce web developer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110