Okay, before we can grab data from the database, we must know how to insert data. Assuming you have already created a database with a table name, then inserting data can be done with the INSERT SQL command. I've given an example below. Assuming that you are inserting three pieces of data simultaneously into three different fields in the MySQL database, it will look something like this: INSERT INTO `tablename` (`fieldname1`,`fieldname2`,``,`fieldname3`) VALUES('$datatobeinsertedtofieldname1','$datatobeinsertedtofieldname2', When using this query with PHP, be careful about the exact use of quote symbols and exact spelling of fieldnames and variables. This is the common cause of errors in PHP programming that involve the use of the INSERT query. Note that the table name and field names in the query command should be used with back ticks (`) , and that you need to maintain consistent cases between the actual MySQL tablenames and the ones used with your script. This will avoid case sensitivity issues, which could be common in Linux/PHP and MySQL environment. For example: if your table name is SongArchives, use also: INSERT INTO `SongArchives` ..... Finally, to formulate a complete MySQL query in PHP using the INSERT command, the following is the recommended script: <?php //Step 1 Connect to database $username = "Your MySQL username here"; $password = "Your MySQL password"; $hostname = "Hostname"; $table = "MySQL Table name where the data will be inserted"; $database = "The name of the MySQL database which holds the table"; $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL"); $selected = mysql_select_db($database,$dbhandle) or die("Could not select $database"); //Step 2. Insert other PHP scripts here (such as grabbing data from HTML forms, etc) //Step 3. Sanitize variables before inserting to database. This will prevent MySQL injection. $datatobeinsertedtofieldname1 = mysql_real_escape_string(stripslashes($datatobeinsertedtofieldname1)); $datatobeinsertedtofieldname2 = mysql_real_escape_string(stripslashes($datatobeinsertedtofieldname2)); $datatobeinsertedtofieldname3 = mysql_real_escape_string(stripslashes($datatobeinsertedtofieldname3)); mysql_query("INSERT INTO `tablename` (`fieldname1`,`fieldname2`,``,`fieldname3`) VALUES('$datatobeinsertedtofieldname1','$datatobeinsertedtofieldname2', or die(mysql_error()); ?>
blog comments powered by Disqus |
|
|
|
|
|
|
|