Inserting data to MySQL is done by using mysql_query() to execute INSERT query. Note that the query string should not end with a semicolon. Below is an example of adding a new MySQL user by inserting a new row into table user in database mysql :
Example : insert.php
Source code : insert.phps
include 'library/config.php';
include 'library/opendb.php';
mysql_select_db($mysql);
$query = "INSERT INTO user (host, user, password, select_priv, insert_priv, update_ priv) VALUES ('localhost', 'phpcake', PASSWORD('mypass'), 'Y', 'Y', 'Y')";
mysql_query($query) or die('Error, insert query failed');
$query = "FLUSH PRIVILEGES";
mysql_query($query) or die('Error, insert query failed');
include 'library/closedb.php';
?>
In the above example mysql_query() was followed by die(). If the query fail the error message will be printed and the script's execution is terminated. Actually you can use die() with any function that might not execute properly. That way you can be sure that the script won't continue to run when an error occured.
In a real application the values of an INSERT statement will be form values. As a safe precaution always escape the values using addslashes() if get_magic_quotes_gpc() returns false. Below is an example of using form values with INSERT. It's the same as above except that the new username and password are taken from $_POST :
Example : adduser.php
Source code : adduser.phps
if(isset($_POST['add']))
{
include 'library/config.php';
include 'library/opendb.php';
$username = $_POST['username'];
$password = $_POST['password'];
$query = "INSERT INTO user (host, user, password, select_priv, insert_priv, update_ priv) VALUES ('localhost', '$username', PASSWORD('$password'), 'Y', 'Y', 'Y')";
mysql_query($query) or die('Error, insert query failed');
$query = "FLUSH PRIVILEGES";
mysql_query($query) or die('Error, insert query failed');
include 'library/closedb.php';
echo "New MySQL user added";
}
else
{
?>
}
?>
Source : http://www.php-mysql-tutorial.com/
No comments:
Post a Comment