inserting directory address in mysql php - 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]);

Related

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

Putting PHP array into MySQL with additional columns

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')

Text area values exploded and submitted to MySQL database

if(isset($_POST['usersadded'])){
$value = $_POST['usersadded'];
$lines = explode("\n", $value);
foreach ($lines as $line) {
mysql_query("INSERT INTO Users_$support (Users) VALUES ('$line')");
};
I have a valid connection to the database already, so it's not that that's wrong. But it never submits anything :(
$support is a number, e.g. 19.
I would always suggest using this SQL syntax when inserting something with PHP variables inside.
mysql_query("
INSERT INTO
`table_name`
SET
`field` = '" . $field_variable . "'
");
The error might appear when you don't phrase your PHP variables correctly inside the query string.
Try this
mysql_query("INSERT INTO Users_$support (Users) VALUES (\"'\".$line.\"'\")");

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

Php Multi-Dimensional Array / MySql problem

I am trying to write a php script that take a text file break down its contents and and insert it into a MySql database, the code is as follows:
$file = "my_file.txt";
$db = "db_name";
$link = mysql_connect("localhost","root");
if(!$link) die("Connection Failed");
mysql_select_db($db) or die("Could not open $db: ".mysql_error()."<br />");
$fp = fopen($file, 'r') or die("Could not open file");
$my_filesize = filesize($file);
while(!feof($fp)) {
$prod_doc.=fread($fp, $my_filesize); // store the file in a variable
}
$prod_array = explode("~",$prod_doc); // create a array with the explode function
for($i=0; $i<count($prod_array); $i++){
$prod_items[$i] = explode(',', $prod_array[$i]); // create a malti-dimensional array
}
$query = "INSERT INTO my_table(feild1, feild two, feild three)
VALUES ('$prod_items[$i][0]','$prod_items[$i][1]','$prod_items[$i][2]')
";
$result = mysql_query($query);
if(!$result) die(mysql_error());
$result = mysql_affected_rows($result);
echo $result;
mysql_close($link); `
My problem is this: Array[0], Array[1], Array[3] is what is entered into the database instead of my data. Thanks in advance, cheers.
To access array variable element values used inside a double-quote string need braces delimiters:
"'{$prod_items[$i][0]}','{$prod_items[$i][1]}','{$prod_items[$i][2]}') ";
Another way to code this is by concatenation (in which case you don't need the extra delimiters):
"'" . $prod_items[$i][0] . "','" . $prod_items[$i][1] . "','" . $prod_items[$i][2] . "') ";
Don't forget, if the input data is unpredictable, you need to filter out characters that can break your sequel or compromise security principles. SEE How can I prevent SQL injection in PHP?
Also, junmats's comment is correct, you are only running the query outside the for loop which doesn't make sense.
You have to iterate over your $prod_items array as well, then concate the values
$insert = array();
for($i=0; $i<count($prod_array); $i++){
$prod_items[$i] = explode(',', $prod_array[$i]); // create a malti-dimensional array
$insert[] = '( ' .$prod_items[$i][0]. ', '.$prod_items[$i][1]. ', '. $prod_items[$i][3] .')';
}
$insert_string = implode(', ', $insert);
$query = "INSERT INTO my_table(feild1, feild two, feild three)
VALUES" . $insert_string;
And you should use foreach insted of for.
Seems like you've skipped some code.
After explode you'll have array of strings, not 2d array.
Also it's better to update the code a bit.
$query = "INSERT INTO my_table(feild1, feild_two, feild_three) VALUES ('".$prod_items[$i][0]."','".$prod_items[$i][1]."','".$prod_items[$i][2]."') ";
You should use the standard concatenation(.) technique for this.
PHP can only evaluate simple variables inside a string:
"$var" --> var is evaluated
"$var->var" --> is not evaluated
"$var[0]" --> is not evaluated
$query = "INSERT INTO my_table(feild1, feild two, feild three)
VALUES ('".$prod_items[$i][0]."','".$prod_items[$i][1]."','".$prod_items[$i][2]".')
";

Categories