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

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>

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

Insert Data to MySQL db from HTML form using PHP

I'm trying to insert new record to SQL database using PHP from a HTML form.
I made a form using Post method
<form name="CreatNewMCQ" action="create.php" method="POST">
with a button to submit
<button type="submit" form="CreateNewMCQ">CREATE</button>
what I want to do is when I press the button, it will call create.php which is
<?php
$servername = "localhost";
$user = "admin";
$pass = "admin";
$dbname = "examples";
// Create connection
$conn = new mysqli($servername, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_POST['id'];
$name = $_POST['name'];
$year = $_POST['year'];
$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, $name, $year)";
if ($conn->query($sql) === TRUE) {
echo "Tạo mới thành công";
} else {
echo "Lỗi: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
then insert data from form to SQL database (id, name, year from the form).
I got some errors in SQL syntax. What mistake did I make?
Make sure all post values are getting correctly. You should make a condition check before inserting the data, For ex:
$id = isset($_POST['id']) ? $_POST['id'] : '';
$name = isset($_POST['name']) ? $_POST['name'] : '';
$year = isset($_POST['year']) ? $_POST['year'] : '';
if($id && $name && $year){
$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, '$name', '$year')";
}else{
return "required fields are missing";
}
NB: Please post your html if possible.
try this:
<?php
/* Attempt MySQL server connection.*/
$servername = "localhost";
$user = "admin";
$pass = "admin";
$dbname = "examples";
$link = mysqli_connect($servername, $user, $pass, $dbname);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
$id = $_POST['id'];
$name = $_POST['name'];
$year = $_POST['year'];
$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, '$name', '$year')";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
HTML Form :
<html>
<form name="test" method="post">
Enter name:<input type="text" name="name"/> <br>
Enter year :<input type="text" name="year"/><br>
<input type="submit" name="save" value="save" />
</form>
</html>
php code :
<?php
$conn=mysql_connect("localhost","root","passward");
$select_db=mysql_select_db("Atul",$conn);
if($conn)
{
echo "connected";
}
else
{
echo "Please try again";
}
if(isset($_POST['save']))
{
$name=$_POST['name'];
$year=$_POST['year'];
$insert_record="insert into test (name,year) values("$name","$year");
$result=mysql_query($insert_record);
if($result)
{
echo "Record inserted successfully";
}
else
{
echo "please try again";
}
}
?>

php sql code not inserting into db

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);

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.

Store and Retrieve JPG in Mysql using PHP

I am trying to store jpg images into MySQL database , The insertion works but I am unable to display the results.
here is MySQL table definition:
drop table if exists product_image;
create table product_image(
id_img int not null primary key auto_increment,
name varchar(512),
img LONGBLOB NOT NULL,
id_product int not null
);
PHP script to store User input file:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" >
<input type="submit" value="Upload" name="submit">
</form>
<?php
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "store";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit'])) {
$imageName = mysql_real_escape_string($_FILES["image"]["name"]);
$imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["type"]);
if (substr($imageType, 0, 5) == "image") {
$sql = "insert into product_image (name,img,id_product) values ('$imageName','$imageData','65') ";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
echo $imageName, $imageType;
}
else {
echo "select image type:";
}
}
$conn->close();
?>
</body>
</html>
PHP script to display image:
<?php
header("content-type:image/jpg");
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "store";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$q = "select * from product_image";
$result = $conn->query($q);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$img = $row["img"];
#echo "id: " . $row["img"]. "<br>";
#echo '<img src="data:image;base64, '.$row["img"].' height="200" width="200">';
}
}
else {
echo "0 results";
}
echo $img;
$conn->close();
?>
I just see small icon when I call the PHP script to view the image. Is there any thing that i am missing.
thanks.
use something like this
<img src="data:image/jpeg;base64,<?php echo base64_encode($row['img']); ?>" class="latest_images img-responsive img-thumbnail" alt="Cinque Terre" >

Categories