php upload file path to mysql - php

So, I am creating a very simply uploader where I take in a file/name/description and to store to store the file to the server and name/desc/filepath.
This is what my database looks like:
Basically, i take in a file, name, and description and want the file to be stored in the server. While the path/name/desc to be stored into mySQL. I also want an incrementing ID. I have a db named "test". And want to post to "test_table". The database is already created but I need to check if the table exists, if not, create it. I think I have the basics of mySQL correct below, but I need to know how to check for table/create if needed and how to set the path variable. Thanks in advance!
Also, how do I increment the ID variable in mysql with each entry? does that happen automatically or .. ?
solved

you need to upload your file to the server before inserting in the database:
if ($_FILES['fileinput']['name']!="") {
if (is_uploaded_file($_FILES['fileinput']["tmp_name"])) {
$name = date("Y-m-d : H:i:s")." ".$_FILES['fileinput']['name'];
$filevalue = $nameoffile;
$path =$file_save_path.$nameoffile;
if (move_uploaded_file($_FILES["file".$i]["tmp_name"], $uploaddir.$nameoffile)) {
$sql = "INSERT INTO test_table (name, desc, path) VALUES ($name, $desc, $path)";
mysqli_query($conn, $sql)
} else {
echo "File Upload Error. Please Try again";
}
}
}

To check, if a table exists, see this question: check if MySQL table exists or not
Essentially, this is the code to check:
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1)
echo "Table exists";
else echo "Table does not exist";
To autoinc the ID just use the autoincrement attribute to the ID field, see the documentation here for more info: https://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
Code:
ALTER TABLE test_tabel MODIFY COLUMN ID INT auto_increment
Hope this helps...

Related

i want to code if data allready exist in my database

i Just want code for if veriable $absolute_url value is already exist in mysql then show me a message i just want this Thank you..
$_SESSION['varname'] = $absolute_url;
$mailingwork = mysql_connect("localhost","root","");
mysql_select_db("inbox",$mailingwork);
if(isset($absolute_url) && !empty($absolute_url))
{
mysql_query("Insert Into deliveredinbox(mailerss) value('$absolute_url')");
}
I think you just want to check if the $absolute_url already exists in the deliveredinbox table. If so, you can do a select query as follows to count the number of rows where the absolute url is equal to the url that you want to enter to the table.
if(isset($absolute_url) && !empty($absolute_url)){
$count=mysql_query("SELECT count(*) from deliveredinbox where mailerss='$absolute_url'");
mysqli_fetch_array($count);
if($count[0]>0){
//already exists
echo "The url already exists";
}
else{
mysql_query("Insert Into deliveredinbox(mailerss) value('$absolute_url')");
}
}
Try if (isset($absolute_url)) { your code here; }. It's not precisely the right tool, but I think that it will do the trick for you.
http://php.net/manual/en/function.isset.php.
Others are absolutely right about transitioning from old mysql calls in PHP. mysqli calls are more secure. PDO will save you time in coding and are even more secure.

Get ID from PHP URL and use in a query

I've put certain values like a user id into the url e.g /index.php?id=1 in previous PHP files.
I have a HTML form that has an action like this:
<form name="staffResponse" method="post" action="respond_ticket.php?id=<?php echo $_GET['id']; ?>">
Which when you go to respond_ticket.php and simply echo the value for the id and look at the URL it does it successfully. Whats more the data that I am posting to that file is also done without problem. However I want to then write that information to a table but it does not seem to work.
Here is the respond_ticket.php file
<?php
include 'database/db.php';
$id = $_GET['id'];
$staffResponse = $_POST['staffResponse'];
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse') WHERE id='$id'";
$result = mysqli_query($connection, $sql);
if ($result === TRUE) {
echo '<p>Response ' . $staffResponse . ', has been added</p>';
}
else {
echo '<p class="warning">Unable to respond</p>';
}
?>
The db.php file has all the necessary information for connection to the database i.e name password etc. It also opens the question there too.
I keep just getting the warning message that I wrote.
you cant do an insert with a where modifier like this. change it to update ;)
UPDATE tickets SET staffResponse = '$staffResponse' WHERE id = '$id'
You are not supposed to use a WHERE clause with INSERT
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse')";
You may wish to set your tickets table up with auto increment so you dont need to insert an id if you haven't done that already.
use ON DUPLICATE UPDATE if it helps
INSERT INTO tickets (id,staffResponse) VALUES ('$id','$staffResponse')
ON DUPLICATE KEY UPDATE id=VALUES(id), staffResponse=VALUES(staffResponse)

How to update longblob image field in mysql using php

if(isset($_POST['submit']) and isset($_GET['slider_id']))
{
$date=date('Y-m-j');
$imgName=$_FILES['image']['name'];
$cont=file_get_contents($imgName);
$cont=addslashes($cont);
if($imgName=="")
{
//$imgData =addslashes(file_get_contents($_FILES['image']['name']));
$res=mysqli_query($connect,'UPDATE `slider_images` SET `image`=\''.$cont.'\' WHERE id=\''.$_GET['slider_id'].'\'');
if($res)
{
echo "Updated";
}
else
{
echo "Not Updated";
}
}
}
Not understanding the real issue behind this and i have refereed many solution's but no success in that.All solution's i found they tell to store images in folder and store the file name in database table.Reason behind storing images in database is, only 4 images are to be stored, so why not to store them in database. Please guide me through this issue. Following is the issue i am talking about.
Warning Message
Thank's in advance.
$_FILES['file']['name'] is the original name of the uploaded file from the user's computer.
$_FILES['file']['tmp_name'] will contain the temporary file name of the file on the server. This is just a temporary placeholder until you process the file.
So you should access the file like this:
$cont=file_get_contents($_FILES['image']['tmp_name']);
Sidenote: Instead of if($res){ ... } use mysqli_affected_rows() to get number of rows affected by this UPDATE query, like this:
mysqli_query($connect,"UPDATE `slider_images` SET `image`='".$cont."' WHERE id='".$_GET['slider_id']."'");
if(mysqli_affected_rows($connect)){
echo "Updated";
}else{
echo "Not Updated";
}
Here's the reference:
mysqli_affected_rows()

delete an image file using php

I am building a forum with php and MySQL and I want to append current time to each image that users upload for their profile. I used time() function on each image file uploaded and it worked for the image file but I have trouble inserting the new filename into the database. I wanted to give each image a unique name to prevent override.
OK here is what I did: I stored the current time as $time and the filename in a variable, $photo and I tried to insert that variable’s value using $photo .= $time into the database so it has the filename as I did with each uploaded image. However the original filename is inserted into the database in every attempt.
Any workarounds?
$image = $_FILES['photo']['name'];
$time = time();
$image .= $time;
delete the existing photo
delete(image_dir/$row['current_photo.jpg']);
//does not work, but i want something like that
if(move_uploaded_file($_FILES['photo']['tmp_name'], 'image_dir/$image') {
$query = "INSERT INTO profile (user_id, profile_photo) VALUES($id, $image)";
mysqli_query($dbc, $query);
if(mysqli_affected_rows($dbc) == 1) {
echo "added to the database!";
}else {
echo "failed to add photo to the database";
}
}else {
echo "failed to upload photo";
}
how can i give the uploaded image unique the name since the original image name gets inserted in the database in every try i make?
i know the code looks funny :). just want to show the logic.
If you need a unique id, you can use the uniqid function
$name=uniqid();
you may need to use
$filename=uniqid();

adding user photos to database

my question is on adding the file paths to images to a user's slot in a database. here is a sample, this is the page where the photos are to be chosen:
require_once("script.php");
<form method="post" action='golf.php'>
<?php
require_once("golf_phot.php");
?>
</div>
<input id="butt" type="submit" value="add"/>
</form>
here are the contents of golf_phot.php:
$query="SELECT category_id FROM categories WHERE category_name='golf'";
$resultt=mysql_query($query);
$row=mysql_fetch_array($resultt);
$do=$row['category_id'];
$query2="SELECT photo FROM all_photos WHERE all_photos.category_id='$do'";
$result=mysql_query($query2);
while ($row=mysql_fetch_array($result))
{
$photo=$row['photo'];
echo "<input type=\"checkbox\" name=\"addlist[]\" value=\"".$photo."\">"."<img src=\"".$photo."\">";
echo "<br>";
echo "<br>";
echo "<br>";
}
i already did the mysql connection and database selection, i won't post that but it has no issues. here are the contents of "script.php":
if(isset($_POST['addlist']))
{
$pics=$_POST['addlist'];
$n=count($pics);
//now, to open the database user_info, using the stored session
//make the session variable legit
if(isset($_SESSION['user']))
{
$user=$_SESSION['user'];
}
//get the user's id from the user_info table
$querya="SELECT * FROM user_info WHERE user_info.fb_id='$user'";
$result1=mysql_query($querya);
//now that we have the id, we can add the photos to
//user_photos, using their id as a foreign key
if(mysql_num_rows($result1)>0){
$rowa=mysql_fetch_array($result1);}
$user_id=$rowa['USER_INFO_ID'];
//before we add them, we'll need to see whether they exist or not.
//adding time:
for($i=0;$i<$n;$i++){
$data=$pics[$i];
$queryb="SELECT * FROM user_photos";
$result3=mysql_query($queryb);
if(mysql_num_rows($result3)>0){
while($rowa=mysql_fetch_array($result3))
{
$data2=$rowa['USER_PHOTOS'];
if($data==$data2)
{ $var='exists'; }
else{
$queryb="INSERT INTO user_photos(USER_PHOTOS_ID,USER_INFO_ID,USER_PHOTOS) VALUES('NULL','".$user_id."','".$data."')";
$result2=mysql_query($queryb);
}
}
}
}
// selected photos added to user's gallery!
}
the user data variables are all set as i use them elsewhere and they are successfuly added to the database, above, i include a way to see if the photo already exists, i don't add it if it does(maybe there's an issue with that?) so basically, the page with photos is loaded, the user checks on the photos they want and then they send it to the same page, where "script.php" is supposed to process the data and add it to the database. no photos are added to the database, i really can't tell what's the issue here. i kindly ask for help, even though this is probably an easy question, if you need me to clarify something, kindly ask so, meanwhile, can anybody help? thanks in advance.
One solution for check the picture is same or not is, using a hash algorithm on the pictures to determined the same pics.
i.e: (pseudo code)
$hash=sha1_file('pic-filename');
$sql='select * from image_table where hash_col ='.$hash;
if(num_rows($sql)>0)
//don't save pic.
else
// save the pic and it's hash value.
hash_col is a column in your image table that get the hash value of the particular image.
Please Try this code in your script.php. hoping this may work for you.
I Have removed the condition if(mysql_num_rows($result3)>0){
Code:
if(isset($_POST['addlist']))
{
$pics=$_POST['addlist'];
$n=count($pics);
//now, to open the database user_info, using the stored session
//make the session variable legit
if(isset($_SESSION['user']))
{
$user=$_SESSION['user'];
}
//get the user's id from the user_info table
$querya="SELECT * FROM user_info WHERE user_info.fb_id='$user'";
$result1=mysql_query($querya);
//now that we have the id, we can add the photos to
//user_photos, using their id as a foreign key
if(mysql_num_rows($result1)>0){
$rowa=mysql_fetch_array($result1);}
$user_id=$rowa['USER_INFO_ID'];
//before we add them, we'll need to see whether they exist or not.
//adding time:
for($i=0;$i<$n;$i++){
$data=$pics[$i];
$queryb="SELECT * FROM user_photos";
$result3=mysql_query($queryb);
while($rowa=mysql_fetch_array($result3))
{
$data2=$rowa['USER_PHOTOS'];
if($data==$data2)
{ $var='exists'; }
else{
$queryb="INSERT INTO user_photos(USER_PHOTOS_ID,USER_INFO_ID,USER_PHOTOS) VALUES('NULL','".$user_id."','".$data."')";
$result2=mysql_query($queryb);
}
}
}

Categories