step1: create a database ‘test’ and create table inside this database using the following query
1 2 3 4 5 6 |
CREATE TABLE IF NOT EXISTS `categories` ( `id` int(11) NOT NULL AUTO_INCREMENT, `ttiles` varchar(250) NOT NULL, `path` varchar(250) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; |
step2: create a folder called “fileupload” .
step3: .create a folder ‘myfolder’ inside the ‘fileupload’ folder.
step4: save the file ‘categories.php’ inside the ‘fileupload’ folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>File upload using PHP:</title> </head> <body> <table align="center"> <tbody> <tr><td> <form action="succescategories.php" method="POST" enctype="multipart/form-data"> Title: <input type="text" name="titles" > <br><br> Imagine1: <input type="file" name="filep" > <br><br> <input type="submit" value="Submit"> </form> </tr></td> </tbody> </table> </body> </html> |
step5: save the file ‘successcategories.php ‘ inside the ‘fileupload’ folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<?php $link = mysqli_connect("localhost", "root", "", "test"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Escape user inputs for security $titles = mysqli_real_escape_string($link, $_POST['titles']); /*to upload fie*/ $fileName = $_FILES["filep"]["name"]; $fileTmpLoc = $_FILES["filep"]["tmp_name"]; $pathAndName = "myfolder/".$fileName; $moveResult = move_uploaded_file($fileTmpLoc, $pathAndName); // Evaluate the value returned from the function if needed if ($moveResult == true) { $insertpath=$pathAndName; } else { $insertpath="Error in fie upload"; } // attempt insert query execution $sql = "INSERT INTO categories (ttiles,path) VALUES ('$titles','$insertpath')"; if(mysqli_query($link, $sql)){ echo "<h1>Records added successfully.</h1>"; } else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } // close connection mysqli_close($link); ?> <p><a href="categories.php">Add Category</a></p> |
step6: execute the file categories.php in the browser.