Putting PHP array into MySQL with additional columns - php

I have a question about PHP arrays and inserting them as single records into a MySQL database. I have the array sorted and that is working as it should.
This is what I have for the array:
$files = array();
foreach($_FILES['file']['tmp_name'] as $key => $tmp_name )
{
$files[$key] = array
(
$file_name = $_FILES['file']['name'][$key],
$file_type=$_FILES['file']['type'][$key],
$file_size =$_FILES['file']['size'][$key],
$file_tmp =$_FILES['file']['tmp_name'][$key]
);
}
This is what I have for the array to insert them as separate rows in to the database:
$new = array();
foreach($files as $key => $value)
{
$new[] = "'".implode("','", $value)."'";
}
$query = "(".implode("), (",$new).")";
$sqlone = "INSERT INTO files (filename, filetype, filesize, filetempname) VALUES ".$query."";
if (!mysql_query($sqlone, $conn))
{
die("Error: " . mysql_error().".");
}
The issue I am running into is this: I want to add extra information to the query but I am not entirely sure how to do this.
I want to be able to add a reference to the email that the files were attached to. I basically want the query to be as follows:
$sqlone = "INSERT INTO files (filename, filetype, filesize, filetempname, mailid //this is the extra column in the database) VALUES ".$query.", '1'// this is the corresponding value";
The issue I am running in to is that I get an error when trying to add extra information to it.
Are there any pointers you guys could give me?
Thanks in advance

Just change where your parenthesis is added (and quote your inputs):
$query = "('".implode("'), ('",$new);
$sqlone = "INSERT INTO files (filename, filetype, filesize, filetempname, mailid) VALUES ".$query."', '1')";
Should result in the SQL:
INSERT INTO files (filename, filetype, filesize, filetempname, mailid) VALUES
('<file_name>', '<file_type>', '<file_size>', '<file_tmp_name>', '1')

Related

how to prevent duplicate entry in mysql while data are entered from array?

I am new in android development I am sending a json array through android application and insert that data into MySQL database. The problem is that whenever I insert userJSON it entered every time with duplicate entries. So, I want to prevent duplicate entry in mysql how can this possible with php. Please help me to solve this problem.
json string from android side
'[{"type":"Outgoing","duration":"0","number":"XXXXXXXX","date":"Tue Dec 13 15:26:29 GMT+05:30 2016"},
{"type":"Outgoing","duration":"0","number":"XXXXXXXX","date":"Tue Dec 13 13:49:50 GMT+05:30 2016"}]';
Here is my php file for post json:
<?php
require_once('conn.php');
if($_SERVER['REQUEST_METHOD']=='POST')
{
$json = $_POST["usersJSON"];
echo $json;
if (get_magic_quotes_gpc())
{
$json = stripslashes($json);
}
$data = json_decode($json,true);
$query=mysqli_query($con,"SELECT *
FROM users
where number = '$number'
and type = '$type'
and date = '$date'
and duration= '$duration'");
if(mysqli_num_rows($query)>0) {
echo "already exist";
}
elseif(is_array($data))
{
$sql = "INSERT IGNORE INTO users (type, duration, number,date) values ";
$valuesArr = array();
foreach($data as $row)
{
$type = mysqli_real_escape_string( $con,$row['type'] );
$duration = mysqli_real_escape_string($con, $row['duration'] );
$number = mysqli_real_escape_string( $con,$row['number'] );
$date = mysqli_real_escape_string( $con,$row['date'] );
$valuesArr[] = "('$type', '$duration', '$number', '$date')";
}
$sql .= implode(',', $valuesArr);
if(mysqli_query($con,$sql))
{
echo 'Entry Added Successfully';
}
else
{
echo 'Could Not Add Entry';
}
}
//Closing the database
mysqli_close($con);
}
?>
Create a UNIQUE INDEX
Regardless of whatever programming language that you use, all the constraints on the data have to be enforced with in the database and not in your application layer. And the easiest way to do that is to add a UNIQUE KEY on the columns in question.
ALTER TABLE users ADD UNIQUE KEY all_columns(number,type,date,duration)
I am adding all the four columns to the unique index because you seem to want any column to have duplicate values taken in isolation. Please confirm if this is correct or choose the columns appropriately when creating the index.
Simply your code
With a unique key in place, your don't need that SELECT
$data = json_decode($json,true);
if(is_array($data))
{
$sql = "INSERT IGNORE INTO users (type, duration, number,date) values ";
....
}
Use Prepared Statements
Instead of a huge string concatenation as is being currently done and multple calls to mysqli_real_escape, you would be better of using prepared statements. You might even get a tiny increase in performance. However more importantly there is a maximum size of a string that can be passed through to the server, if you get a large array you might go beyond that.

Inserting multiple files path in a single column of DB?

I am new to php. I am uploading multiple files from a form along with other inputs to database. Files complete path and name should be inserted in DB in a single column with commas. How do I do that?
$filename = $_FILES['file']['name'];
$folder = "/var/www/html/PhpProject1/";
for($i=0; $i<count($_FILES['file']['name']);$i++)
{
move_uploaded_file($_FILES['file']['tmp_name'][$i], $folder.$_FILES['file']['name'][$i]);
}
$stmt = $conn->prepare("INSERT INTO studentrecords(name, email, mobileno,address,gender,filename) values (?,?,?,?,?,?)");
$stmt->bind_param("ssssss",$name,$email,$mobno,$address,$gender,$filename);
$stmt->execute();
echo "Successfull";
$stmt->close();
$conn->close();
You need to keep the paths in an array, because you are uploading multiple files. So here i am using $paths array to store the paths.
And in the insert query i am using implode function to convert array to string (with comma). This way you can store all paths as a comma separated value in a single column.
This is your solution
$filename = $_FILES['file']['name'];
$folder = "/var/www/html/PhpProject1/";
$paths = array();
for($i=0; $i<count($_FILES['file']['name']);$i++)
{
$paths[] = $folder.$_FILES['file']['name'][$i];
move_uploaded_file($_FILES['file']['tmp_name'][$i], $folder.$_FILES['file']['name'][$i]);
}
$stmt = $conn->prepare("INSERT INTO studentrecords(name, email, mobileno,address,gender,filename) values (?,?,?,?,?,?)");
$stmt->bind_param("ssssss",$name,$email,$mobno,$address,$gender,implode(",",$paths));
$stmt->execute();
echo "Successfull";
$stmt->close();
$conn->close();

how to add multiple records in mysql using php?

for example i have an array of images of a specific location lets say of new york...which i want to store in mysql... these images are coming directly from wikipedia...how can i insert these images in a loop with each image entry would get the same location name?..like this
1|Newyork|img1.jpg
2|Newyork|img2.jpg
3|Newyork|img3.jpg...so on...
what i have done so far is..
foreach($images as $record)//'$images' is the array of images..
{
$sql="INSERT INTO `search`(`id`, `name`, `image`) VALUES ('','".$data"','".$record."',} //$data is the name of location
if I understood well, even if I don't see your array, sth like that would be the query loop:
//if id is a primary key autoincrement
foreach ($images as $data => $record){
$dbh->query("INSERT INTO search (name, image) VALUES ('".$data."','".$record."') ");
}
but most possibly the array is of that form
for($i=0; $i<count($images); $i++){
$dbh->query("INSERT INTO search (name, image) VALUES ('".$images[$i]['data']."','".$images[$i]['record']."') ");
}
It depends of the array form.

inserting directory address in mysql php

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]);

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.

Categories