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
Related
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')";
I'm trying something with file upload and sql lately, and I have this small problem. When I'm trying to insert this string to sql, the sql insert different value. Here is the text I'm trying to insert.
C:\xampp\tmp\phpCD2.tmp
and here is the text inserted in mysql
C:xampp mpphpCD2.tmp
so from what I see the php/mysql remove all the '\' and convert the '\t' to a tab or spaces. I know it will be fix if I change the directory but what if I have some file starting with 't' so it will be remove, so How can I fix this. Thanks.
Here is the code:
foreach ($files['name'] as $position => $file_name)
{
$name = $files['name'][$position];
$tempName = $files['tmp_name'][$position];
$type = $files['type'][$position];
$size = $files['size'][$position];
echo $tempName, '<br>';
$insert = "INSERT INTO " . $table . " (id, name, tempName, type, size)
VALUES ('', '$name', '$tempName', '$type', '$size') ";
mysql_query($insert);
}
You have to escape the string.
$tempName = mysql_escape_string($files['tmp_name'][$position]);
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.
getting :
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 's Creed III', description='The plot is set in a fictional
history of real ' at line 2
when trying to edit posts on a database.
heres my display and edit php:
$result = mysql_query("SELECT * FROM gallery");
while ($row = mysql_fetch_array( $result )){
// while looping thru each record…
// output each field anyway you like
$title = $row['title'] ;
$description = $row['description'];
$year = $row['year'];
$rating = $row['rating'];
$genre = $row['genre'];
$filename = $row['filename'];
$imageid = $row['imageid'];
include '../modules/edit_display.html';
}
// STEP 2: IF Update button is pressed , THEN UPDATE DB with the changes posted
if(isset($_POST['submit'])){
$thisTitle = $_POST['title'];
$thisDescription = $_POST['description'];
$thisYear = $POST['year'];
$thisRating = $POST['rating'];
$thisGenre = $POST['genre'];
$thisNewFilename = basename($_FILES['file']['name']);
$thisOneToEdit = $_POST['imageid'];
$thisfilename = $_POST['filename'];
if ($thisNewFilename == ""){
$thisNewFilename = $thisfilename ;
} else {
uploadImage();
createThumb($thisNewFilename , 120, "../uploads/thumbs120/");
}
$sql = "UPDATE gallery SET
title='$thisTitle',
description='$thisDescription',
year='$thisYear',
rating='$thisRating',
genre='$thisGenre',
filename='$thisNewFilename'
WHERE
imageid= $thisOneToEdit";
$result = mysql_query($sql) or die (mysql_error());
}
You're suffering from an imminent dose of SQL Injection due to using a dangerous user input model.
When you type "Assassin's Creed III" in the title field, that gets placed in single quotes in the UPDATE statement in your code (via the $_POST['title'] variable):
'Assassin's Creed III'
The problem there is that MySQL sees it as 'Assassin', followed by s Creed III'. It doesn't know what to do with the latter.
Of course, this becomes a HUGE problem if someone types in valid SQL at that point, but not what you expected. Have a look at How can I prevent SQL injection in PHP? or any of several other advices on avoiding SQL Injection.
i have seen you are adding ' into database so you need to escape it using addslashes()
addslashes($thisTitle)
You have syntax error here. Use $_POST instead of $POST.
Replace
$thisYear = $POST['year'];
$thisRating = $POST['rating'];
$thisGenre = $POST['genre'];
With
$thisYear = $_POST['year'];
$thisRating = $_POST['rating'];
$thisGenre = $_POST['genre'];
you need to escape your input like
$thisDescription = mysql_real_escape_string($_POST['description']);
do this for all input that contains quotation marks etc..
NOTE: mysql will soon be gone so its advised to write new code using mysqli instead
You have alot of issues in your script.
You're trying to add ' character to database, you need to escape it properly with addslashes.
You're vulnerable to SQL Injection. Escape it properly with mysql_real_escape_string, or even better, use PDO.
Third, it is $_POST, not $POST. You're using it wrong in some areas.
Add quotes to $thisOneToEdit in query.
The error is causing because you're trying to add Assasin's Creed III string to database. The single quote breaks your query and creates a syntax error.
Do a addslashes() on the values that might contain single or double quotes like below before using them in query
$thisTitle = addslashes($_POST['title']);
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().