uploadify and sql query - php

i am using uploadify script to upload files as my school project.
//die($_SESSION['ID'].'.....'.$_SESSION['level']);
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$filename = substr(md5(time()), 0, 8)."-".$_FILES['Filedata']['name'];
$targetFile = str_replace('//','/',$targetPath) . $filename;
$time = time();
$ID = $_SESSION['ID'];
$sql = mysql_query("INSERT INTO files VALUES(NULL, '$ID', '$targetFile', '$time')");
move_uploaded_file($tempFile,$targetFile);
echo "1";
}
On top $_SESSION['id'] is working, however when i entered inside $sql, it return as 0. Any idea why? i have rechecked everything.
Confused.
Thank you

It seems SESSION doesn't work well with uploadify, i solved it with scriptData uploadify.
Thank you for all answers.

Must be the type of your mysql column.
Be sure your are using varchar/text because '$ID' is a string : if your type is int (or similar) then you WILL have 0 inserted.

Couple things wrong here. You should first be explicitly naming your fields in the $sql:
$sql = 'insert into tablename (fileid,filename,d_uploaded) values ('.$ID.', \''.$targetFile.'\', '.$time.');';
Most ID fields won't be VARCHAR they will be INT. All VARCHAR is a text field and all INT are numeric. You don't escape out your INT fields but you need to escape your VARCHAR.
Also don't insert NULL fields to get an auto increment field. By doing the SQL the way I have above you get the benefit of being able to only code the SQL fields you are inserting and the rest of the fields in the table will insert default values.

Try using INSERT INTO files SET field=value, field=value, .. and remember to sanitize user input (like $_REQUEST) using mysql_real_escape_string() (and if you have magic quotes enabled to disable them if you decide to use mysql_real_escape_string().

Related

How to send duble variable into one database(table) field?

In the first variable I store the name of a picture. The second one stores the path to this picture. The MySQL field should get both of them in order so I can access it from browser. How can I do this? I've already tried this:
$path = 'www.something.com/images/';
$sql = "INSERT INTO tb_user_info " . "(user_image)"."VALUES( '$path'.'$user_pic')";
Well first of all, you should be using prepared statements with mysqli or pdo. But to answer your question.
$path = 'www.something.com/images/' . $user_pic;
$sql = "INSERT INTO tb_user_info (user_image) VALUES( '$path')";

PHP - Check for distinct filename on file upload

I'm pretty new to PHP. I hate to have to ask questions, because I'm sure this is documented somewhere, but after looking for a while, I just cannot seem to put two and two together.
I have a program that will allow multiple images to be uploaded to an item within the database. Basically, for each item in the database, there might be multiple image uploads.
Example:
Item: Xbox 360
Images:
Xbox360.jpg
side.jpg
front.jpg
The image and item information is all stored in the database (MySQL), but the images are stored within the filesystem, and the database points to the URL of the image(s) in the filesystem.
The problem I'm having is that everything works as expected, except it allows duplicate image names to be written to the database. It doesn't allow duplicate images to be written to the filesystem, which I'm happy with. I want to make sure that the name of an image is only added once to the database. If the image name is a duplicate to another, it needs to not write to the database.
add_db.php:
$uniqueDir = uniqid();
$directory = "img/$uniqueDir/";
db_addItem($id_category, $name, $cost, $description, $qty, $directory); //Adds to the `items` table
foreach ($_FILES['i_file']['name'] as $filename) {
if ($filename != '' && $filename != 'No file chosen') {
//I think above is where I check for unique image names
$url = "img/$uniqueDir/$filename";
db_addImg($url, $filename); //Adds to the `img` table
$item_picsID = get_item_PicsID($filename, $url);
$itemID = get_itemID($directory);
db_insertImg($itemID, $item_picsID);
}
}
addFilesystem($directory); //Writes image(s) to filesystem
function db_addImg($url, $filename) {
include 'mysql_login_pdo.php';
// Create the SQL query
$query = "INSERT INTO img (`name`, `url`) VALUES(:filename, :url)";
$stmt = $db->prepare($query);
$stmt->execute(array(
':filename' => $filename,
':url' => $url
));
}
function db_insertImg($itemID, $item_picsID) {
include 'mysql_login_pdo.php';
// Create the SQL query
$query = "INSERT INTO `item_pics` (`item_id`, `img_id`) VALUES(:itemID, :item_picsID)";
$stmt = $db->prepare($query);
$stmt->execute(array(
':itemID' => $itemID,
':item_picsID' => $item_picsID
));
$db = null;
return;
}
Everything works, except it will write duplicate image names to the database. I want the image names to be distinct. I also don't want to rename the images (if possible).
You can define an UNIQUE index on the name column in img table, and then use slightly modified INSERT statement in your db_addImg function:
function db_addImg($url, $filename) {
//...
$query = "INSERT INGORE INTO img (`name`, `url`) VALUES(:filename, :url)";
//...
}
It will quietly cancel any insert where the is a UNIQUE key collision, which will end up in distinct filenames across your img table.
I would use a filename based on the primary key from the img table as you're guaranteed it's unique.
Otherwise, you'll need to guess a unique filename with some type of hashing and then check the file system. All of which can be expensive operations.
Looks like you are using PDO, so the static method lastInsertId will get the last insert id (primary key).
For example:
// after your insert to img
$filename = 'img' . $db->lastInsertId() . $extension;
This will require changing the img table slightly. But you're better off storing meta data (file type, size, etc) in this table as opposed to the file location (as that can change).
I think better to use hash value of your url as the primary key. Be cause string searching is much slower as int.

issue when inserting variable value to MySQL table

Hey I am currently trying to insert a global variable to a table. The other values I pass are variables too but they get sent correctly.
Here is my query. my error handling does not capture anything
$result = mysql_query("INSERT INTO IPmanagement (userId, NameUsed, EmailUsed, IPStatus, Ip) VALUES ('" .$masterUserId . "', '" . $Entry['LeadName'] . "', '" . $Entry['LeadEmail'] . "', '0', '" . $ip . "')") or die(ErrorException("Function 6", "Error when processing the current lead. your data is unaffected and if the proccess continues please contact an Admin.", mysql_error(),$_SERVER['REMOTE_ADDR'], CurrentPath(), $masterUserId));
my variable that is global defined before the function is
$masterUserId = "1";
I tried echoing the variable before it sends and it echos out correctly YET my table holds a value of 0.
here is a screenshot of how I have my table setup.
Click for Larger Image
Any idea what is going on. I am rather stumped and tried writing this same code different ways and it still gives me same issue. Also $masterUserId will always be an int value
Edit: also would like to mention the variable is different .php that contains the varaiable and database login information. It is being included at the top. (don't know if that is relevant)
Because you are not inserting IP STATUS.Which is not null
\
You should either set this to null or enter some value to it.
If you are using query in a function than use like this
function (){
//than define
$globat $masterUserId;
// use the global defination
// than use this variable with global value
}
Do not use mysql_*. Replace them with mysqli_* or PDO::.
Did you try to echo the mysql_query()? Do this. Replace mysql_query("..."); with die("..."); and put it in the phpMyAdmin and try executing.
And in your table, I see that IP Status is a NOT NULL. So that might throw an exception. Use a default value in the table.
And yeah, what do you get the result as in mysql_error()?
Why ''' or "' in query?
I have cleaned up query with PHP function sprintf and using NULL for EntryID(Autoincrement)
$query = sprintf("INSERT INTO IPmanagement (EntryID,userId, NameUsed, EmailUsed, IPStatus, Ip) VALUES (NULL,%s,%s,%s,'0',%s)",
$masterUserId , $Entry['LeadName'] , $Entry['LeadEmail'] , $ip ));
$result = mysql_query($query);
You should also use MySQLi or PDO

Wrong mysql query in php file?

I'm trying to insert some data into my mysql database. The connection is working fine but im having a problem with sending the query correctly to the database. Below you can find the code in my php file. I also post what for type of fields they are in the Database.
Fields in the mysql database:
Reservaties_id = int
Materialen_id = int
aantal = int
effectief_gebruikt = tinyint
opmerking = Varchar2
datum_van = date
datum_tot = date
$resID = $_REQUEST['resID'];
$materialen_id = $_REQUEST['materialen_id'];
$aantal = $_REQUEST['aantal'];
$effectief_gebruikt = $_REQUEST['effectief_gebruikt'];
$opmerking = $_REQUEST['opmerking'];
$datum_van = date('YYYY-MM-DD',$_REQUEST['datum_van']);
$datum_tot = date('YYYY-MM-DD',$_REQUEST['datum_tot']);
$string = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`, `materialen_id`, `aantal`, `effectief_gebruikt`, `opmerking`, `datum_van`, `datum_tot`) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', $datum_van, $datum_tot)";
mysql_query($string);
you have to include single quotes for the date fields '$dataum_van'
$string = "INSERT INTO `materialen_per_reservatie`(reservaties_id, materialen_id, aantal, effectief_gebruikt, opmerking, datum_van, datum_tot) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')";
and this is only a example query, while implementing don't forget to sanitize your inputs
Your code has some serious problems that you should fix. For one, it is not doing any error checking, so it's no surprise the query breaks silently when it fails. Check for errors and it will tell you what goes wrong - how to do it is outlined in the manual on mysql_query() or in this reference question.. Example:
$result = mysql_query($string);
// Bail out on error
if (!$result)
{
trigger_error("Database error: ".mysql_error(), E_USER_ERROR);
die();
}
In this specific case, I'm fairly sure it's because you are not putting your values into quotes after the VALUES keyword.
Also, the code you show is vulnerable to SQL injection. You need to escape every value you use like so:
$resID = mysql_real_escape_string($_REQUEST['resID']);
for this to work, you need to put every value in your query into quotes.
try this
$string = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`) VALUES ('".$resID."')";

php code of adding a record to database

I am working on a control panel (admin pages) for a website. All the pages have the same code with little changes in the database table name and columns. All of them work fine, but one page doesn't work.
This is its code....
<?php
include('connect.php');
// read the input data
$KTitle = $_POST['Title'];
$Kcontent = $_POST['content'];
$ImgName = $_FILES["file"]["name"];
//get img extension
$ImgExtension = substr($ImgName, (strlen($ImgName) - 4), strlen($ImgName));
//check if it Gif, Bng, Jpg
if ($ImgExtension == ".gif" || $ImgExtension == ".jpg" || $ImgExtension == ".png")
{ //get img name to rename it then readd the extinsion
$ImgName = substr($ImgName, 0, (strlen($ImgName) - 4));
$storyImgName = $ImgName . "_" . $Title;
$target = "../CharacterImgs/" . $storyImgName . $ImgExtension;
$target = str_replace(" ", "_", $target);
move_uploaded_file($_FILES['file']['tmp_name'], $target);
mysql_query("INSERT INTO CharactersN (name,desc,img) VALUES ('$KTitle', '$Kcontent','$target')");
echo "<meta http-equiv=\"refresh\" content=\"3;URL=AddCharacterForm.php\">";
}
?>
If you use desc as a column name in MySQL, you must surround it in backticks because it is a reserved word.
"INSERT INTO CharactersN (name, `desc`, img) ..."
You have a problem here:
INSERT INTO CharactersN (name,desc,img)
desc is a reserved word, so you must use the ` notation there, which is like this:
INSERT INTO CharactersN (`name`,`desc`,`img`)
It is a good practice to use this notation for field names every time (or never use reserved words for field names in your database design).
Also, please read about SQL Injection, because your code shows you are not aware of it. You are inserting values into your query which are coming from outside (POST in this case).
VALUES ('$KTitle', '$Kcontent','$target')")
You should escape these values first with mysql_real_escape_string(), or even better, use PDO for your database interaction.
from xkcd

Categories