Append variable To string in php insert - php

I'm having an issue appending a file name variable to a string in a sql insert like so
$insert = $mysqlConn->query("INSERT into images (image_name, url) VALUES ('".$fileName."', 'images/".$fileName."'");
I can do it with just the $fileName and it works fine but my syntax is wrong. I'm simply trying to make sure that every file name inserted starts with 'images/'
So if I'm inserting 'red.jpg' it would be 'images/red.jpg'

You can store image value into one variable
$imgPath = 'images/'.$fileName;
Above variable you can pass into the query

try this,you are missing one bracket
$insert = ("INSERT into images (image_name, url) VALUES ('".$fileName."', 'images/".$fileName."')");

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.

multiple file upload sql/php

i am trying to upload multiple files and then insert the files names in mysql db
my problem is with inserting the names it only store the last file name
for($i=0;$i<count($_FILES['file']['size']);$i++){
if(strstr($_FILES['file']['type'][$i], 'image')!==false){
$file = 'uploads/'.time().' - '.$_FILES['file']['name'][$i];
move_uploaded_file($_FILES['file']['tmp_name'][$i],$file);
$na=$_FILES['file']['name'][$i];
$sql="INSERT INTO img (img_name) VALUES ('$na');";
}
}
notice that all the files are uploaded successfully
for($i=0;$i<count($_FILES['file']['size']);$i++){
if(strstr($_FILES['file']['type'][$i], 'image')!==false){
$file = 'uploads/'.time().' - '.$_FILES['file']['name'][$i];
move_uploaded_file($_FILES['file']['tmp_name'][$i],$file);
$na=$_FILES['file']['name'][$i];
$sql="INSERT INTO img (img_name) VALUES ('$na');";
}
}
you are just creating a string and storing some value. you have not executed it ..
Say $str = "apple"; Its just a declaration. I presume you have executed the query after the loop. Say you have 10 files. loop gets executed 10 times and $na has the last filename which gets inserted.
Soln: move your execute query inside the for loop.
for($i=0;$i<count($_FILES['file']['size']);$i++){
if(strstr($_FILES['file']['type'][$i], 'image')!==false){
$file = 'uploads/'.time().' - '.$_FILES['file']['name'][$i];
move_uploaded_file($_FILES['file']['tmp_name'][$i],$file);
$na=$_FILES['file']['name'][$i];
$sql="INSERT INTO img (img_name) VALUES ('$na');";
mysql_query($con,$sql); // note: $con is your connection string
}
}

Data is not being inserted into second table (MYSQLi)

I am using the code below that uploads a file and inserts data into the "Image" table using mysqli:
<?php
session_start();
$username="xxx";
$password="xxx";
$database="mobile_app";
$mysqli = new mysqli("localhost", $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
$result = 0;
//UPLOAD IMAGE FILE
move_uploaded_file($_FILES["fileImage"]["tmp_name"], "ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
//INSERT INTO IMAGE DATABASE TABLE
$imagesql = "INSERT INTO Image (ImageFile) VALUES (?)";
if (!$insert = $mysqli->prepare($imagesql)) {
// Handle errors with prepare operation here
}
//Dont pass data directly to bind_param store it in a variable
$insert->bind_param("s", $img);
//Assign the variable
$img = 'ImageFiles/' . $_FILES['fileImage']['name'];
$insert->execute();
//RETRIEVE IMAGEID FROM IMAGE TABLE
$lastID = $mysqli->insert_id;
//INSERT INTO IMAGE_QUESTION DATABASE TABLE
$imagequestionsql = "INSERT INTO Image_Question (ImageId, SessionId, QuestionId) VALUES (?, ?, ?)";
if (!$insertimagequestion = $mysqli->prepare($imagequestionsql)) {
// Handle errors with prepare operation here
}
$sessid = $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
$insertimagequestion->bind_param("sss", $lastID, $sessid, $_POST['numQuestion'][$i]);
$insertimagequestion->execute();
//IF ANY ERROR WHILE INSERTING DATA INTO EITHER OF THE TABLES
if ($insert->errno) {
// Handle query error here
}
$insert->close();
if ($insertimagequestion->errno) {
// Handle query error here
}
$insertimagequestion->close();
}
}
?>
So for example if I insert 2 images "cat.png" and "dog.png" into "Image" Database table, it will insert it like this:
ImageId ImageFile
220 cat.png
221 dog.png
(ImageId is an auto increment)
Anyway what I want to do is that when a file is uploaded, not only is the data inserted into the table above, but I want to also be able to retrieve the ImageId that was inserted above and place it in the "Image_Question" table below so it would be like this:
ImageId SessionId QuestionId
220 cat.png 1
221 dog.png 4
The problem is that it is not inserting any data into the second table "Image_Question", does anyone know why it is not inserting any data? There is no errors in the php file.
To upload a file, the user selects a file for the ajax uploader in the "QandATable.php" page, when the user clicks on upload, using AJAX it will go onto the imageupload.php page and does the uploading there. So the problem I have is that no errors will appear as they are on seperate pages.
First, save the insert ID gained from your record addition (after the $insert->execute):
$lastID = $mysqli->insert_id;
Then reference $lastID later.
To pull up my comment from below:
$lastID = $insert->insert_id;
I think it's to do with swapping the handle names around - $mysqli, $insert etc.
Hope I read the question correctly...
Check for 500 Error responses in Firebug -> Net tab/Chrome Developer tools -> Network tab . Even if nothing is returned as text, this will help you debug a syntax/semantic error as opposed to a logical error.
Firstly, what happens when you echo $lastID? Do you get a value output to the screen?
If not, we need to fix that first so that $lastID is returning the correct value.
Your insert code appears to be correct.
You should get the Last inserted ID from first table and insert into your 2nd table (Image_Question) .
I Don't know the PHP coding, but this task is simple as well.Because this operation will be executed inside DAO class.So, No matter whether it is PHP or JAVA.
If the second insertion fails, then
if ($insertimagequestion->error) {
// Handle query error here
echo $insertimagequestion->error;
}
This should tell you what the Error being thrown from the execution of the statement is.
Your PHP code seems fine, the error could be due to a Foreign key constraints or any other constraints on your DB Tables.
PS: I think you should validate the type of files you allow to be uploaded so people can't upload *.php or *.js files, this can lead to catastrophic XSS attacks.
Also try to avoid using the same filename as uploaded by the user, you may want to prefix with some random variable, so you can now have
//notice uniqid(time()) for randomness, also move the declaration of $img higher
//Assign the variable
$img = "ImageFiles/" . uniqid(time()) . $_FILES["fileImage"]["name"];
move_uploaded_file($_FILES["fileImage"]["tmp_name"], $img);
...
//Dont pass data directly to bind_param store it in a variable
$insert->bind_param("s", $img);
Bind with mysqli works with references to variables. I dont think your last argument in the second bind command references the way you expect it to.
Assign the the last argument $_POST['numQuestion'][$i] to a variable and use this variable in the bind method call. I am guessing this is either not defined, evaluating to null, and the bind is failing since you can't bind a null as a string or bind cannot use a multidimensional array since itexpects a variable passed as reference.
Try this:
//Below will set a default value of empty string if the POST variable is not set
$postVar = isset($_POST['numQuestion'][$i])?$_POST['numQuestion'][$i]:'';
$insertimagequestion->bind_param("sss", $lastID, $sessid, $postVar);
After doing this, if you see entries in the DB with a '' in the QuestionId column, $_POST['numQuestion'][$i] isn't being set and you have something wrong elsewhere in your code having nothing to do with DB access.
Tried to figure out where could be the failure.
There is no problem with second query and you get successfully last insert id. I used static values for the variables for second query it worked fine. Even you can hardcode values n check out.
Take care of the foll:
Does bind params get the all the values?
print_r() $lastID, $sessid, $_POST['numQuestion'][$i]
This Will not create problem unless database has contraints of not accepting empty or null values.
Make use of the check condition to find where its going wrong.
if (!$insertimagequestion = $mysqli->prepare("$imagequestionsql")) {
// Handle errors with prepare operation here
echo "Prepare statement err";
}
if ($insert->errno) {
// Handle query error here
echo "insert execution error";
}
Though its an ajax you can use Developer Tool of Chome to debug ajax requests.
Press F12 to open the Developer Tool in Chrome
Go to Network Tab >> Perform action for ajax requests to be sent on your form >> you can find the ajax requests sent >> click on it >> Click on the "Response" Tab you will find the error if you have
echoed or the response. So, echo error and print_r() to help debugging

uploadify and sql query

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().

Categories