Working with tables
1. Create a SQL query
2. Execute the query
3. Work with any results from the query
Valid SQL queries are detailled in the link given in the more detail section. As a first example, let's look at creating a table.
$query = "CREATE TABLE users (user_name TINYTEXT, user_email TINYTEXT, user_password TINYTEXT user_datereg DATETIME)";
$result = mysql_query ($query);
$error = mysql_error();
$errorno = mysql_errno();
Note:
1. $result is set to true if the query runs OK. It is set to false if there is any problem with the query.
2. $error is set with the MySQL error text if the query fails. $errorno is set with the MySQL error number if the query fails.
3. Your program needs to handle what to do if the query fails. The program continues to run irrespective of what happens to the query.
The other technique commonly used is to handle the results of a SELECT query. Here is an example using the table created above:
// Select all users who begin with 'A'
$db_connection = mysql_connect($db_host, $db_user, $db_password);
$db_select = mysql_select_db ($db_name);
$searchquery = "SELECT * FROM users WHERE user_name LIKE 'A%'";
$searchresult = mysql_query ($searchquery);
// If any results were found
if ($searchresult) {
// Loop through results returned from the query
while ($row = mysql_fetch_array($searchresult, MYSQL_NUM)) {
$username = row[0];
$useremail = row[1];
$userpassword = row[2];
$userdate = row[3];
... do what you want with the fields
}
}
Next article: HTML forms