When coding in PHP you may at some point need to run queries in a MySQL database. Just like many other database applications, MySQL has several types of queries to perform adding, updating and removing of data.
All of the various types of queries are processed by the mysql_query() function.
To run an insert query:
$sql = "INSERT INTO `users` (`UserID`, `name`, `email`) VALUES (NULL, '$name', '$email');"; mysql_query($sql) or die('Unable to process query: '.mysql_error());
Here we are placing the query into the $sql variable, the second line then processes the query. If the query could not be run, the script exits and shows the error that was produced. We are inserting this data into the users table which has columns of UserID, name, and email.
To update a record in the users table you would run:
$sql = "UPDATE `users` SET `name` = '$name', `email` = '$email' WHERE `UserID` = $_POST[id] LIMIT 1"; mysql_query($sql) or die("Unable to process query: " . mysql_error());
Here you specify the table right after the UPDATE and then specify all fields you wish to update after the SET. The last half of the query we are specifying which record we wish to update and limiting the update to only one record.
Now to delete a record or multiple records, you would use:
$sql = "DELETE FROM users WHERE UserID = '$UserID' LIMIT 1"; mysql_query($sql);
This is a very short query that shows the table which we would like to delete a record from and the criteria that we would like to remove. Since we only wish to remove one record, LIMIT 1 is added to make sure we only remove one record.
Anytime that you run a query, you need to make sure that you escape all of your user input variables. If you fail to do this, you risk the chance of somebody performing an SQL injection on your database. One of the easiest ways to perform this is to use the mysql_escape_string() function which preps the variables for use in your query.




