Forum Moderators: coopster
The whole script works well except for the UPDATE addresses which doesn't update the database. All variables contain correct values at the point of update and all table names are correct. Can anyone see the problem from the code below and additionally do I need to 'lock' the table in some way as the code increments the id value if it is not an existing customer?
//open a database and store the data in it.
$dbcnx = @mysql_connect('localhost', 'user', 'pw');
if (!$dbcnx) {
exit('<p>Unable to connect to the ' .
'database server at this time.</p>');
}
if (!@mysql_select_db('user')) {
exit('<p>Unable to locate the store ' .
'database at this time.</p>');
}
$emails = @mysql_query('SELECT id, email, FROM customers');
if (!$emails) {
exit('<p> Error generating a customer number from the database<br />' .
'Error: ' . mysql_error() . '</p>');
}
while ($temail = mysql_fetch_array($emails)) {
$id = $temail['id'];
$email = $temail['email'];
if ($email == $strEmail) {
$customerid = $id;
$customer_exists = 1; //for checks if customer exists
//update the addresses in case they have changed
$sql = "UPDATE customers SET
address='$address',
deladdress='$delAddress'
WHERE id='$customerid'";
break;
}
else {
$id++; //if this is a new customer, use the next id number.
$customerid = $id;
}
}
The code then carries on to store all data where it should be with the newly created customer id and this works fine other than the fact I am not sure whether the customer id may get duplicated if multiple users access the database at the same time.
It never mentioned that you have to terminate the query in my 'teach yourself to be a webmaster in a jiffy' book :)
Do you happen to know the answer to my other question; Do I need to lock the table in some way? The book doesn't say anything about it but I did think I might get a problem with multiple users accessing the database. Am I right to assume that mysql locks the table automatically while a script is using it?
As far as unique identifiers, you are best off using AUTO_INCREMENT with your MySQL database. You'll find that you won't get any duplicates that way.
So long as you never run two separate versions of the same DB that you must someday merge together, auto increment is perfect. Otherwise, you may consider using a randomly generated 32 character alphanumeric string that you check for redundancy. For a very large table, this may not work as well since the redundancy checks eventually get unbearable slow.
SELECT LAST_INSERT_ID() [dev.mysql.com] AS lastID;