php sql code not inserting into db - php

I'm new to php and a complete noob. I used following code to insert some files to my db.
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="uploads/";
$new_size = $file_size/1024;
$new_file_name = strtolower($file);
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($file_loc,$folder.$final_file))
{
$sql = "INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";
//mysql_query($sql, $conn);
?>
<script>
alert('successfully uploaded');
window.location.href='index.php?success';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index.php?fail';
</script>
<?php
}
}
?>
Though this save the file in upload folder, it does not insert anything into the data base. No matter how many times its uploaded database remain empty. It doesn't show any error either.
My config.php file is
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "dbtuts";
$conn = new mysqli($dbhost, $dbuser, $dbpass);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
HTML part
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit" name="btn-upload">upload</button>
</form>

No DB is selected
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "dbtuts";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname); // <--- here select db first
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Then use
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="uploads/";
$new_size = $file_size/1024;
$new_file_name = strtolower($file);
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($file_loc,$folder.$final_file))
{
$sql = "INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";
if($conn->query($sql)) {
echo "Success";
} else {
echo "Failed. Error: ".$conn->error;
}
?>
<script>
alert('successfully uploaded');
window.location.href='index.php?success';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index.php?fail';
</script>
<?php
}
}
?>

I think, your sql can not get variable
You try to write like that:
$sql = "INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";

Try this
$sql = "INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";
mysqli_query($conn,$sql);

Related

Upload multiple images to database

the 5 pictures i want to upload are used to display the product with a gallery that you click on each image to see individually, i'm new to this so any feedback on how to improve my code is appreciated :)
config.php:
<?php
session_start();
// connect to database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ecommerce_site";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
manage.php:
<form method="POST" action="manage.php" enctype="multipart/form-data">
<input type="file" name="image[]" multiple>
<button type="submit" name="upload_product">Post</button>
</form>
admin-functions.php:
<?php
if (isset($_POST['upload_product'])){
$filecount = count($_FILES['image']['name']);
for($i = 0 ; $i < $filecount ; $i++){
$filename = $_FILES['image']['name'][$i];
$sql = "INSERT INTO products (picture, picture_2, picture_3, picture_4, picture_5) VALUES ('$filename', '$filename', '$filename', '$filename', '$filename',)";
if($conn->query($sql) === TRUE){
echo"success";
}
else{
echo "error";
}
move_uploaded_file($_FILES['image']['tmp_name'][$i], '../static/images/'.$filename);
}
}
$result = mysqli_query($conn, "SELECT * FROM products");
?>
database

Not able to insert proper "voice file(mp3) " into database

Able to insert the data but the format which gets inserted is not working ...tried with image files, voice files etc.
Using blob data type able to insert the file data inside the MySQL database, but the format is not working.
<?php
$server = "localhost";
$user = "USERNAME";
$pass = "PASSWORD";
$db = "databasename";
$con = new mysqli($server, $user, $pass, $db);
if ($con->connect_error) {
die("connection error");
}
$inscrutable = "insert into tables(id, data,filepath) values(1,'voice.mp3','F:\\\')";
if ($con->query($inscrutable) == true) {
echo "Inserted successfully";
} else {
echo "error" .$con->error;
}
$con->close();
Required to login to the page with a voice recorder
connecting database
//file_name config.php
<?php
$host = ""; /* Host name */
$user = ""; /* User */
$password = ""; /* Password */
$dbname = ""; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<!doctype html>
<html>
<head>
<?php
include("config.php");
if(isset($_POST['upload'])){
$maxsize = 5242880; // 5MB
$name = $_FILES['file']['name'];
$target_dir = "videos/";
$target_file = $target_dir . $_FILES["file"]["name"];
// Select file type
$audioFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Valid file extensions
$extensions_arr = array("MP3","WAV","FLAC","PCM","AIFF");
// Check extension
if( in_array($audioFileType,$extensions_arr) ){
// Check file size
if(($_FILES['file']['size'] >= $maxsize) || ($_FILES["file"]["size"] == 0)) {
echo "File too large. File must be less than 5MB.";
}else{
// Upload
if(move_uploaded_file($_FILES['file']['tmp_name'],$target_file)){
// Insert record
$query = "INSERT INTO tables(name,location) VALUES('".$name."','".$target_file."')";
mysqli_query($con,$query);
echo "Upload successfully.";
}
}
}else{
echo "Invalid file extension.";
}
}
?>
</head>
<body>
<form method="post" action="" enctype='multipart/form-data'> //must use enctype = "multipart/form-data"
<input type='file' name='file' />
<input type='submit' value='Upload' name='upload'>
</form>
</body>
</html>

Issue in uploading images to MySQL database using PHP

I have this php code to upload image to the database, I have issue
with it and I don't know what is it, the database table name is
images and the fields are id, name VARCHAR(), photo LONGBLOB.
<?php
ini_set('display_errors', '1');
$servername = "";
$username = "";
$password = "";
//$host = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
</br>
</br>
</br>
<input type="submit" name="go" value="Upload"/>
</form>
<?php
if(isset($_POST['go'])){
if(getimagesize($_FILES['image']['tmp_name']) == FALSE){
echo "Select a photo please";
}else {
$image = addslashes($_FILES['image']['tmp_name']);
$name = addslashes($_FILES['image']['name']);
$image = file_get_contents($image);
$image = base64_encode($image);
save_image($image , $name);
}
}
function save_image($image , $name){
$servername = "localhost";
$username = "cl60-shooters";
$password = "dbsjcNs-b";
$conn = new mysqli($servername, $username, $password);
$qry = "insert into images (photo , name) VALUES ('$image','$name')";
$result = mysqli_query($conn,$qry);
if($result){
echo "Successfull upload";
}else{
echo "try Again";
print_r($result);
}
}
?>
</body>
</html>
The result is as shown in the attached screenshot:
Result
Your function neglects to mention the database - you need to supply that as one of the parameters, like:
function save_image($image , $name){
$servername = "localhost";
$username = "cl60-shooters";
$password = "dbsjcNs-b";
$database='xxxxxxxx';/* enter correct db name */
$conn = new mysqli( $servername, $username, $password, $database );
$qry = "insert into images (`photo`, `name`) VALUES ('$image','$name')";
$result = mysqli_query($conn,$qry);
if($result){
echo "Successfull upload";
}else{
echo "try Again";
print_r($result);
}
}
FYI that said your code is vulnerable to sql injection - better to use prepared statements!
You're not using database name in the mysqli constructor. It should be like the following:
$servername = "localhost";
$username = "cl60-shooters";
$password = "dbsjcNs-b";
$database = "database_name_here";
$conn = new mysqli($servername, $username, $password, $database);
Hope it should work now.

Try uploading csv file to mysql using php and mysql

Good day everyone, I am quite new to php and I really need some help. I am trying to upload a csv file to mysql database using php and html form, but it is giving me the following errors:
Notice: Undefined index: temp_name in C:\xampp\htdocs\import csv\importcsv.php on line 23
Warning: fopen(): Filename cannot be empty in C:\xampp\htdocs\import csv\importcsv.php on line 24
Warning: fgetcsv() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\import csv\importcsv.php on line 26
Warning: fclose() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\import csv\importcsv.php on line 30 successfully imported
here is my code
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '';
$db = 'mydb';
$table = 'user';
$conn = mysqli_connect($db_host, $db_user, $db_pwd) or die("Cant connect to database");
if(!mysqli_select_db($conn,$db))
die("Cant select to database");
if(isset($_POST['submit'])){
$fname = $_FILES['sel_file']['name'];
echo 'upload file name: '.$fname.' ';
$chk_ext = explode(".", $fname);
if(strtolower(end($chk_ext)) == "csv"){
$filename = $_FILES['sel_file']['temp_name'];
$handle = fopen($filename, "r");
while(($data = fgetcsv($handle, 1000, ",")) != FALSE){
$sql = "INSERT into user(name,email,phone) values('$data[0]', '$data[1]', '$data[2]')";
mysql_query($sql) or die(mysql_error());
}
fclose($handle);
echo "successfully imported";
}
else{
echo "Invalid file";
}
}
?>
<h1>Import csv file</h1>
<form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post' enctype="multipart/form-data">
Import File : <input type='file' name='sel_file' size='20'>
<input type='submit' name='submit' value='submit'>
</form>
Can anyone please help me out
I have updated some lines in your code.
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '';
$db = 'mydb';
$table = 'user';
$conn = mysqli_connect($db_host, $db_user, $db_pwd, $db) or die("Cant connect to database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (isset($_POST['submit'])) {
$fname = $_FILES['sel_file']['name'];
echo 'upload file name: ' . $fname . ' ';
$chk_ext = explode(".", $fname);
if (strtolower(end($chk_ext)) == "csv") {
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle, 1000, ",")) != FALSE) {
$sql = "INSERT into user(name,email,phone) values('".$data[0]."', '".$data[1]."', '".$data[2]."')";
mysqli_query($conn, $sql) or die(mysqli_error($conn));
}
fclose($handle);
echo "successfully imported";
} else {
echo "Invalid file";
}
}
?>
<h1>Import csv file</h1>
<form action='<?php echo $_SERVER["PHP_SELF"]; ?>' method='post' enctype="multipart/form-data">
Import File : <input type='file' name='sel_file' size='20'>
<input type='submit' name='submit' value='submit'>
</form>

upload file to sql sever with php

I try to upload file to a database by using php.
Here is my code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db ='testdb';
// Create connection
mysql_connect($servername, $username, $password);
mysql_select_db("testdb");
if(isset($_POST['submit']))
{
$UploadName = $_FILES['UploadFileField']['name'];
$UploadTmp = $_FILES['UploadFileField']['tmp_name'];
$UploadName = preg_replace("#[^a-z0-9.]#i","",$UploadName);
if (!$UploadTmp)
{
die ("No File Selected, Please Upload Again");
} else
{
move_uploaded_file($UploadTmp,"uploaded/$UploadName");
$url = "http://localhost/uploadandview/uploaded/$UploadName";
mysql_query("INSERT INTO `videos` VALUE('1','$UploadName','$url')");
}}?>
But i have a proplem, I can't upload any file mp3/mp4, just only upload file text, such as .doc,pdf, css, etc...
Please help me!
Try this code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db ='testdb';
// Create connection
mysql_connect($servername, $username, $password);
mysql_select_db("testdb");
if(isset($_POST['submit']))
{
$UploadName = $_FILES['UploadFileField']['name'];
$UploadTmp = $_FILES['UploadFileField']['tmp_name'];
$UploadName = preg_replace("#[^a-z0-9.]#i","",$UploadName);
if (!$UploadTmp)
{
die ("No File Selected, Please Upload Again");
} else
{
move_uploaded_file($UploadTmp,"uploaded/".$UploadName);
$url = "http://localhost/uploadandview/uploaded/".$UploadName;
mysql_query("INSERT INTO `videos` VALUE('1','$UploadName','$url')");
}} ?>

Categories