I am kinda new to PHP and I am buliding a music library as a school project.
There is a Table 'albums' which holds 'id' and 'name'.
and a table 'songs' containing 'id','name','album_id' and 'path'.
Long story short,I am trying to display all the songs that are in the selected album.
user creates an album and then uploads songs into it.that part works great and the DB is filled in correctly.
problem is, once I select an album to view the songs that are in it I get nothing.
<?php
$album_id = $_GET['id'];
//display songs from selected album
$query = mysql_query("SELECT * FROM songs WHERE album_id = $album_id");
while ($fetch_songs = mysql_fetch_array($query)) {
$song_name = $fetch_songs['name'];
$song_path = $fetch_songs['path'];
?>
play song
<br/>
<b><?php echo $song_name; ?></b>
<?php
}
?>
</div>
I believe using a href would be the simplest option, yet I've tried also audio controls and even trying to upload an image with img src istead of an MP3 and still no success, I just get an empty page.
this is the code for song uploading to DB.
if (isset($_POST["upload"])) {
$name = $_POST['name'];
$album_id = $_POST['album'];
$file_name = $_FILES['file']['name'];
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$random_name = rand();
if (empty($name) || empty($file_name)) {
echo "Please fill all fields in the form ! <br/>";
} else {
move_uploaded_file($file_tmp, 'music/' . $random_name . '.mp3');
mysql_query("INSERT INTO songs VALUES ('','$name','$album_id','$random_name.mp3')");
echo "File uploaded ! </br></br>";
}
}
?>
Thanks for any help.
try this code :
while ($fetch_songs = mysql_fetch_array($query, MYSQL_ASSOC))
more information : http://php.net/manual/en/function.mysql-fetch-array.php
Related
I am trying to upload image but getting my own exception :
Image is not valid, please select a proper image.
I reviewed my code and researched on google and in stackoverflow as well. But did not get any proper solution. It is my code given below for uploading image
.
Code :
$fetchName = "SELECT FirstNameMiddleName, LastName FROM mmb WHERE UserId = ".$_SESSION['UserId'];
$fetchNameFire = mysqli_query($conn, $fetchName);
$resultName = mysqli_fetch_assoc($fetchNameFire);
$filename = $_FILES["aadhaarphoto"]["name"]."_".$_SESSION['UserId']."_".$resultName['FirstNameMiddleName']."_".$resultName['LastName'];
$tempname = $_FILES["aadhaarphoto"]["tmp_name"];
$folder = "AadhaarCards/".$filename;
//====================================================
$allowedExtension = array('jpg','png','gif','JPG','PNG','GIF');
$ext = pathinfo($filename,PATHINFO_EXTENSION);
//====================================================
if(!in_array($ext,$allowedExtension))
{
//echo mysqli_error($conn);
echo 'Image is not valid, please select a proper image';
}
else
{
$updateUser = "UPDATE mmb SET Address = '$UserAddress', DOB = '$UserDOB', Phone = '$UserPhone', Whatsapp = '$UserWhatsapp', AadhaarCardNo = '$UserAadhaarNo', AadhaarCardPhoto = '$folder' WHERE UserId = ".$_SESSION['UserId'];
$updateUserFire = mysqli_query($conn, $updateUser);
if($updateUserFire)
{
move_uploaded_file($tempname, $folder);
}
else
{
echo mysqli_error($conn);
}
}
It looks like you are appending things on to the end of the file name.
$filename = $_FILES["aadhaarphoto"]["name"]."_".$_SESSION['UserId']."_".$resultName['FirstNameMiddleName']."_".$resultName['LastName'];
So if the file name was "image.jpg" it would become something like "image.jpg_123_John_Doe". The file extension is now "jpg_123_John_Doe", which is not on your list.
If you change your code like this it should work.
$ext = pathinfo($_FILES["aadhaarphoto"]["name"],PATHINFO_EXTENSION);
thank you in advance for your help, i need to make a system were i can upload and update a file into my database record. To do so i made this code but for some reason i cant seem to see what i have done wrong i can update the "status and so on" but the file is not uploaded into my desired directory and the record is missing in my database too, so all the rest works just fine, except the file itself, does not get updated. Here is my code, again thanks in advance!
<?php
if(isset($_POST['submit_btn']))
{
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
require 'modules/conn.php';
$target = "../account-files/";
$target = $target . basename( $_FILES['Filename']['name']);
}
$id = $_REQUEST['id'];
$status = $_REQUEST['status'];
$counts = $_REQUEST['counts'];
$Filename=basename( $_FILES['Filename']['name']);
$query = mysqli_query($conn,"UPDATE files SET id ='".$_POST['id']."', status ='".$_POST['status']."', counts ='".$_POST['counts']."', Filename ='".$_POST['Filename']."' WHERE id = '".$id."'") or die(mysqli_error($conn));
header("location: ../my-account/");
}
?>
Everything else gets updated in my database, but as i said, the file and the record of the file name does not, also its not uploaded into my directory. Please help me, an example would be very much appreciated.
Updated code i can get the records into the database but still no upload into the directory.
$target = "../account-files/";
$target = $target . basename( $_FILES['Filename']['name']);
if(isset($_POST['submit_btn']))
{
move_uploaded_file($_FILES['Filename']['tmp_name'], $target);
require 'modules/conn.php';
$id = $_REQUEST['id'];
$status = $_REQUEST['status'];
$counts = $_REQUEST['counts'];
$Filename=basename( $_FILES['Filename']['name']);
$query = mysqli_query($conn,"UPDATE files SET id = $id, status = '$status', counts = $counts , Filename = '$Filename' WHERE id = '$id'") or die(mysqli_error($conn));
header("location: ../my-account/");
}
This last solution is correct i hope i can contribute also to other members, see solution credits bellow at the correct reply to my post, that guy rocks! Thumbs up so what was the error? Simple, the path i had was wrong...
this one is wrong:
$target = "../account-files/";
This is correct and fixes all
$target = "account-files/";
Do you really have the POST['Filename']? I think you should put the variables in you query instead of .POST
Try the code below:
if(isset($_POST['submit_btn']))
{
$target_dir = "../account-files/";
$target_file = $target_dir . basename( $_FILES['Filename']['name']);
move_uploaded_file($_FILES['Filename']['tmp_name'], $target_file);
require 'modules/conn.php';
$id = $_REQUEST['id'];
$status = $_REQUEST['status'];
$counts = $_REQUEST['counts'];
$Filename=basename( $_FILES['Filename']['name']);
$query = mysqli_query($conn,"UPDATE files SET id = $id, status =
'$status', counts = $counts , Filename = '$Filename' WHERE id =
'".$id."'") or die(mysqli_error($conn));
header("location: ../my-account/");
}
And also please make sure that you have the enctype="multipart/form-data" on your form tag.
You make some mistakes:
how you can upload the file first and then determine the target
why are you updating id? while id is its primary key
i
if(isset($_POST['submit_btn'])){
$target = "../account-files/";
$fname = $_FILES['filename']['name'];
if(!empty($target) && !empty($fname)){
move_uploaded_file($_FILES['filename']['tmp_name'], $target.$fname);
}
}
I want to upload 1000 images in just one click via URL. I have 1000 Image URLs stored in MYSQL database.
So please any one give me PHP code to upload that 1000 images via URL through mysql database.
Currently I am using the bellow code:-
It upload one image per click by posting URL of image...
But i want to upload 1000 image in one click by getting URLs from databse
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<div>";
$oid = $row['tid'];
$th= $row['q'];
echo "</div>";
$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');
if($url){
$file = fopen($url,"rb");
$directory = "thumbnail/";
$valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp");
$ext = end(explode(".",strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$filename = "$oid.$ext";
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo 'File uploaded successfully';
echo '**$$**'.$filename;
}
else{
echo 'File does not exists';
}
}
else{
echo 'Invalid URL';
}
}
else{
echo 'Please enter the URL';
}
}
Thanks a lot.... …
The code you have is outdated and a lot more complex than needed. This is not a site where you get code because you ask, this is a learning environment.
I'll give you an example on which you can continue:
// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
$imgSource = file_get_contents($fItems['url']); // get the image
// Check if it didn't go wrong:
if( $imgSource!==false ){
// Which directory to put the file in:
$newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/";
// The name of the file:
$newFilename = basename($fItems['url'], $imgSource);
// Save on your server:
file_put_content($newLocation.$newFilename);
}
// Update the row in the DB. If something goes wrong, you don't have to do all of them again:
mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}
Relevant functions:
file_get_contents() - Get the content of the image
file_put_contents() - Place the content given in this function in a file specified
basename() - given an url, it gives you the filename only
Important:
You are using mysql_query. This is deprecated (should no longer be used), use PDO or mysqli instead
I suggest you make this work from the commandline and add an echo after the update so you can monitor progress
I have a website. In this website I can upload images that are then placed into my SQL database. From here I select the images from the database and show them as thumbnails in the photo gallery, when clicked on the image it shows a large version where you can vote/like and comments etc.
Now what I am trying to do is make 3 category pages, basically 3x the photo gallery that shows the thumbnails.
I have 3 different tables in my database where I insert the images in to.
So I copied the photo gallery 3x and the original upload table in the database 3x.
How ever I do not want to create 3 upload.php files for each photo gallery.php file.
What I'm trying to do is have 3 radio button choices on my upload page and with the choice made there, the image gets uploaded into the matching database table (photo1, 2 or 3).
I have been trying to do this with Functions etc. but I just can't get it to work, I am probably doing something really simple, really stupid.
This is the code i have for the radio button and getting the image:
$titel = "Image";
$query = "SELECT * FROM `i268296_studie`.`fotos` ORDER BY foto_ID DESC";
$result = mysqli_query($conn, $query) or die("query error " . mysqli_error($conn) );
$fotos = array();
//create array from images in database
while($data = mysqli_fetch_assoc($result))
{
$fotos[] = array('src' => $data['src'], 'id' => $data['foto_ID']);
}
?>
<section id="upload">
<form method="post" action="upload.php" enctype="multipart/form-data">
<label for="bestand">Upload image:</label><br><br>
<input type="file" name="bestand" id="file"><br><br>
<label for="categorie"> Categorie: </label>
<input type="radio" name="cat" value="cat1">Portrait
<input type="radio" name="cat" value="cat2">Landscape
<input type="radio" name="cat" value="cat3">Other
<input type="submit" name="submit" value="Upload">
</form>
</section>
<?php
}
?>
<section class="images">
<?php
//show image thumbnails in photogallery
foreach($fotos as $foto)
{
?>
<img class="image" src="<?php echo 'upload/thumb/t_'.$foto['src'];?>">
<?php
}
?>
</section>
The above code I have 3 times (surrounded by HTML etc. as the photo gallery pages).
This is my Upload file (i'll leave most of the thumbnail making code out of it since it's only about the upload part).
$titel = "Image";
$dir='upload/';
$allowedExts = array("jpg", "jpeg", "gif", "png");
$answer= $_POST['cat'];
//Properties of the to be uploaded file
$fileName = $_FILES["bestand"]["name"]; //file name
$fileType = $_FILES["bestand"]["type"]; //file format
$fileSize = $_FILES["bestand"]["size"]; //file size
$tmpName = $_FILES["bestand"]["tmp_name"]; //temporary save location for file
$error = $_FILES["bestand"]["error"]; //error check for file
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
//select image from database and check if it already exists
$sql = "SELECT * FROM `i268296_studie`.`fotos` WHERE src = '$fileName'";
$result = mysqli_query($conn, $sql) or die("query error " . mysqli_error($conn) );
$data = mysqli_fetch_assoc($result);
$num_rows=mysqli_num_rows($result);
if($num_rows > 0)
{
echo 'File already exists <br>';
echo '<a href="fotogallerij.php">Return to homepage/a>';
}
else
{
// if file doesn't exist move to database, create thumbnail path
if (move_uploaded_file( $tmpName,$dir.$fileName))
{
function category($cat, $titel, $filename)
{
global $conn;
$query = "INSERT INTO `i268296_studie`.`$cat` (`titel`, `src`) VALUES ('$titel', '$fileName')"; //INSERT file into database
$result = mysqli_query($conn, $query) or die("query error " . mysqli_error($conn) );
}
$tname = 't_'.$fileName;
$tpath = $dir.'thumb/';
$tnamestate = $tpath.$tname;
$tptype = substr($fileType,6);
$ttype = "imagecreatefrom$tptype";
$name = $fileName;
$path = $dir;
$namestate = $path.$name;
$width = 100;
$height = 100;
list($width_orig, $height_orig) = getimagesize("$namestate");
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig)
{
$width = $height*$ratio_orig;
}
else
{
$height = $width/$ratio_orig;
}
How ever I am staring myself blind on how to fix it or where to place it so it works.
I hope my explanation and question is clear to you guys trying to help me, if not please let me know what I can change or do to help :)
edit:
The errors I am getting are:
Undefined variable: titel
Undefined variable: fileName
Undefined variable: conn
mysqli_query() expects parameter 1 to be mysqli, null given
When I do not pick a radio button but just upload it directly i just get 1 error:
Undefined index: cat
And it uploads it into the 3rd category
Edit 2:
Changed the function with the global $conn in it.
1 function category($cat, $titel, $fileName) {
2 global $conn;
3 $query = "INSERT INTO `i268296_studie`.`$cat` (`titel`, `src`) VALUES ('$titel', '$fileName')";
4 $result = mysqli_query($conn, $query) or die("query error " . mysqli_error($conn) );
5 }
1: you need these variables from the context calling the function
2: you need the global $conn variable in the function context to be able to run the query
3: use a function parameter for the table to upate call
4: it would be better to return results instead of breaking inside the function
The calling code would be like the following:
if ($answer == "cat1") {
category("fotos", $titel, $fileName); // or "foto2", $titel, $fileName .....
}
Please mind the comments about injection vulnerabilities.
Also read this: http://php.net/manual/it/language.variables.scope.php
I need a help to upload and show an image from a database in PHP, I created a database that name is students contains the ID, image size,and image name, is there is a way to do that?
I searched on youtube about this but I found this code, but this code save to a directory.
<?php
$name = $_FILES["myfile"] ["name"];
$type = $_FILES["myfile"] ["type"];
$size = $_FILES["myfile"] ["size"];
$temp = $_FILES["myfile"] ["tmp_name"];
$name = $size.$size .$name ;
$error = $_FILES["myfile"] ["error"];
if ($error > 0){
die ("Error uploading image");
}else{
move_uploaded_file($temp,"uploaded/".$name);
echo "Upload Completed";
}
?>
So, is there any way to save an image to a database and view it from a database?
You can save it into a MySQL table as a Blob but this isn't a really a good idea. Explanation here: http://www.hockinson.com/programmer-web-designer-denver-co-usa.php?s=47
Do what FDl said in the comments. Give each image a unique name and save it to your server, then save its unique name into your database.