How to insert these values correctly in the database - php

Below is part of the code where it uploads a file (fileImage) into a folder (ImageFiles). But what I want to also do is INSERT the file location (The location the file is uploaded into) into the database using INSERT VALUES code. I want the file location to be inserted into the "ImageFile" field and for the "ImageId" I want it to display the string "IMG" and then include a number after the string. For Example:
In my database table if it reads like this:
ImageId ImageFile
IMG1 ImageFiles/penguins.png
IMG2 ImageFiles/desert.png
IMG3 ImageFiles/jellyfish.jpg
Then if I upload the file from my computer 'tulips.png' into the ImageFiles folder, then in the database it should insert the values like this below:
ImageId ImageFile
IMG4 ImageFiles/tulips.png
But how can this be coded? Below is my code at the moment which uploads the file successfully and contains only partial coding of the INSERT VALUES:
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$imagesql = "INSERT INTO Image (ImageId, ImageFile)
VALUES ("");
mysql_query($imagesql);

If you use PHPs PDO object it would simplify your code and make it more safe at the same time (by using prepared statements).
Here's an example of how you would do that:
Firstly, store your ID as an AUTO_INCREMENT-ed INT rather than "IMG#" as this would make things easier (you wouldn't need to INSERT the ID value then)
DROP TABLE IF EXISTS tbl_img_store;
CREATE TABLE tbl_img_store(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
filename VARCHAR(25) --increase this if you think you need to
) ENGINE=InnoDB;
Also, create a table to store configuration settings to make your database more efficient:
DROP TABLE IF EXISTS tbl_img_config;
CREATE TABLE tbl_img_config(
img_path VARCHAR(50)
);
INSERT INTO tbl_img_config (img_path) VALUES ("http://img.mysite.com/?i=");
Now back to PHP, you can quickly insert a load of images like this:
# Create a DB connection
$db = new PDO("mysql:host=X.X.X.X;dbname=mydb", $user, $pass);
# Compile an array of image paths
$img1path = "img1.png";
$img2path = "img2.png";
$img3path = "img3.png";
$images = array($img1path, $img2path, $img3path);
# Create a query to insert the paths to the db
$sql = "INSERT INTO tbl_img_store (filename) VALUES (?),(?),(?);";
$query = $db->prepare($sql);
$query->execute($images);
# Check rows affected
$rows = $query->rowCount();
echo "$rows images were saved.";

You should use an auto incremented id for identifying images instead of using strings for this.
This would ease up the process for you as you would only have to insert a single fields and the autoi ncremented fields updates automatically.
$imagesql = "INSERT INTO Image (ImageFile) VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";
ImageId should then be of type INT as PRIMARY KEY with AUTO INCREMENT instead. That's also a good way to design your tables.

You need to add the values to the query like this
$imagesql = "INSERT INTO Image (ImageId, ImageFile)
VALUES ('$imageName','$imageFile');";
But first make sure you escape the values correctly to avoid any problems. Also note that it's not recommended to use the mysql_ functions any more. Instead use mysqli_ equivalents or better still PDO (with PDO it will automatically handle the DB escaping for you.

You can use MySql Auto increment .. you don't need to worry about IMG IMG2 ... etc
See : http://dev.mysql.com/doc/refman/5.5/en/example-auto-increment.html
Example:
Assumption : ImageId is an auto increment field
http://dev.mysql.com/doc/refman/5.5/en/example-auto-increment.html
$tmpName = $_FILES ["fileImage"] ["tmp_name"];
$fileName = $_FILES ["fileImage"] ["tmp_name"];
move_uploaded_file ( $tmpName, $fileName );
$sql = "INSERT INTO Image (ImageId, ImageFile) VALUES (NULL,'%s');";
mysql_query ( sprintf ( $sql, mysql_real_escape_string ( $fileName ) ) );
When you want to get your images
$sql = "SELECT ImageId, ImageFile FROM Image";
$result = mysql_query ( $sql );
while ( $row = mysql_fetch_assoc ( $result ) ) {
echo "IMG", $row ["ImageId"], " = ", 'ImageFiles/' , $row ["ImageFile"], PHP_EOL;
}
Reason Why you should use this
A. IMG and ImageFiles/ are constant saving them several times is not efficient
B. integer based id would also faster than varchar and performs better on `JOIN
C. To get IMGX where X is an increment value would involve multiple SQL calls .. and not efficient

This is what I do. For an answer to your question, look near the end of the second file, for the mysql_query for SELECT LAST_INSERT_ID(). Note that I don't INSERT an id but let the database auto_increment.
The image is uploaded through upload.php, part of which looks like this:
<form>
<?php
session_start();
if (isset($error["image"])) echo '<span class="error">'.$error["image"].'</span>'; else echo 'Select an image<span class="required"> *</span>';
if ($imgVars["is_image"] == "J") {
echo '
<input type="hidden" name="image_url" value="'.$imgVars["image_url"].'">
<input type="hidden" name="image_type" value="'.$imgVars["image_type"].'">
<input type="hidden" name="is_image" value="J">
<img src="'.$imgVars["image_url"].'" width="224" height="168" alt="Image">
<p>Change image?</p>';
?>
<input type="file" name="image">
<input type="submit" name="upload" value="Upload" title="Upload your image">
</form>
Then the uploaded file is processed through process.php, part of which looks like this:
<?php
session_start();
if (!session_is_registered("error"))
session_register("error");
$error = array();
if (!session_is_registered("imgVars"))
session_register("imgVars");
foreach($_POST as $varname => $value)
$imgVars[$varname] = trim(EscapeShellCmd(stripslashes($value)));
$imgVars = array();
if ($imgVars["is_image"] != 'J') {
$imgVars["is_image"] = 'N';
if ($_FILES["image"]["size"] > 0) {
$size = GetImageSize($_FILES["image"]["tmp_name"]);
$width = $size[0];
$height = $size[1];
if(($width != 224) || ($height != 168)) {
$error["image"] = 'Image dimensions must be exactly 224 x 168 pixel!';
$imgVars["is_image"] = "N";
}
preg_match("/(\.\w+)$/",
$_FILES["image"]["name"],$match);
$imagetype = $match[1];
if (!in_array(strtolower($imagetype), array(".jpg",".jpeg",".gif",".png"))) {
$error["image"] = 'You may upload only images of type JPEG, GIF and PNG!';
$imgVars["is_image"] = "N";
}
if ($imgVars["is_image"] == "J") {
$filename = time().$imagetype;
copy($_FILES["image"]["tmp_name"], "img/".$filename);
$imgVars["image_url"] = "img/".$filename;
$imgVars["image_type"] = $imagetype;
}
} else {
$error["image"] = 'Please upload an image!';
}
}
if (count($error))
{
header('Location: upload.php');
exit();
}
// connect to database
$query = "INSERT INTO images SET image_url = '" . $imgVars["image_url"] . "';
if (!($result = # mysql_query ($query, $connection)))
die("Your mysql error routine here.");
$rs = mysql_query("SELECT LAST_INSERT_ID()", $connection);
$lid = mysql_fetch_row($rs);
$image_id = $lid[0];
if ($imgVars["is_image"] == 'J') {
rename ($imgVars["image_url"], "img/".$image_id.$imgVars["image_type"]);
$query = "UPDATE images SET image_url = 'img/".$image_id.$imgVars["image_type"]."' WHERE image_id = '".$image_id."'";
if (!(# mysql_query ($query, $connection)))
die("Your mysql error routine here.");
}
session_unregister("formVars");
session_unregister("fehler");
header('Location: danke.php');
exit();
?>
There might be typos or omissions in this code, because I translated and trimmed it from my original file without testing.

First of all : ALWAYS use mysql_real_escape_string when inserting values in the db.
Then :
$query = "INSERT INTO `Image` (`ImageId`, `ImageFile`)
VALUES ('".mysql_real_escape_string($_FILES["fileImage"]["tmp_name"])."','".
mysql_real_escape_string($_FILES["fileImage"]["name"])."'
);";

Related

I have a problem with "ADD" and "INSERT" functions in database

I wanna ask you, how can I fix this code? I have a problem with "ADD" and "INSERT" functions in database. I can only delete from database, but "add and insert" functions do nothing.
this is my about.php file.
$mode = 'add';
$about = '';
if(isset($_GET['edit']) && is_numeric($_GET['edit'])){
$sql = "SELECT * FROM `about_me` WHERE `about_me`.`id` =".$_GET['edit'];
$result_about = mysqli_query($conn, $sql);
if(mysqli_num_rows($result_about) == 1) {
$mode = 'edit';
$about = mysqli_fetch_assoc($result_about);
}
}
$apie = '';
if(isset($_POST["submit"])){
if(isset($_POST["apie"])){
$apie = trim($_POST["apie"]);
}
}
elseif($mode=='edit') {
$apie = $about['about'];
}
if($mode=='add') {
if(($apie!='')){
$sql = 'INSERT INTO about_me(about)
VALUES ("'.$apie.'")';
mysqli_query($conn, $sql);
header('Location:about.php');
die();
}
}
elseif($mode=='edit') {
if(($apie!='')){
$sql = "UPDATE `about_me` SET `about` = '".$apie."' WHERE `about_me`.`id` = ".$_GET['edit'];
mysqli_query($conn, $sql) ;
}
}
<..>
<input type = "text" name = "apie" value = "<?php echo $apie; ?>">
<br><br>
<input type = "submit" name = "submit" value = "Gerai">
<br><br>
I checked mysql error, with https://www.w3schools.com/php/func_mysqli_error.asp, and then it insert in my DB. I think there is code foult, but I don't know where.
You have a slight error with your first query, you can't use parentheses next to the database selector, I'd recommend creating a separate file with a database connection that you can refer to as $conn, your first query should look like this:
$sql = "INSERT INTO about_me
VALUES (?)";
Also, you should look into prepared statements for your queries, instead of inserting them directly you use a question mark? to which you bind the parameter/parameters. This helps prevent SQL injections!
Hope this helps!:)

How to fetch images that stored in comma separated format in single row in MySQL?

I am uploading multiple images in the database in a single column with comma separated format. I am first creating a folder for each user and inside that folder, images are stored. car_images is my root directory inside that with the name of logged_in user new directory will create.
My images are stored in below format :
Here, emp_code is unique I am using this as SESSION and for the name of the folder of each user.
as you see car_images column where I am storing image name with ,.
I am using below code to stored images in folders and database. I don't know idea how to fetch all images of a single user.
$car_images_all="";
for($i=0; $i<count($_FILES['car_images']['name']); $i++)
{
$tmpFilePath = $_FILES['car_images']['tmp_name'][$i];
if ($tmpFilePath != "")
{
if (!file_exists('car_images/'.$emp_code))
{
mkdir('car_images/'.$emp_code, 0777, true);
}
$location = 'car_images/'.$emp_code.'/';
$name = $_FILES['car_images']['name'][$i];
$size = $_FILES['car_images']['size'][$i];
list($txt, $ext) = explode(".", $name);
$file= time().substr(str_replace(" ", "_", $txt), 0);
$info = pathinfo($file);
$filename = $file.".".$ext;
if(move_uploaded_file($_FILES['car_images']['tmp_name'][$i], $location.$filename))
{
$car_images_all.=$filename.",";
}
}
}
First of all,
Select all images from database by emp_code (as you want all images of a particular user/emp).
select car_images from TableName where emp_code = $emp_code;
Now, by this you will get one or more rows.
So, add one by one images to array with using explode() function per row (i.e. if row has multiple image name with comma separated).
Use the array as per your choice of manipulation.
Below code will fetch the data from table and save images in array. For more details check the explode function.
$query = "select car_images from table_name where emp_code = 'emp_code'";
$result = mysqli_query($connection,$query);
$row = mysqli_fetch_assoc($result);
$images = $row['car_images'];
$images = explode(',',$images);
foreach($images AS $image){
echo '<img src="car_images/'.$emp_code.'/'.$image.'">';
}
You can use GROUP_CONCAT() function
SELECT GROUP_CONCAT(car_images) FROM TableName
You can use group by also with emp_code or brand_id or any other column whatever your business logic is met.
SELECT GROUP_CONCAT(car_images) FROM TableName GROUP BY emp_code
OR
SELECT GROUP_CONCAT(car_images) FROM TableName GROUP BY brand_id
<?php
$x=0;
$car_img =explode(",",$car_images);
foreach($car_img as $car_images{
$x+=1;0
?>
<?php echo '<img src="'."images/".$car_images.'" width="70" height="70" />';?>

Inserting multiple images in mysql, also inserts multiple rows

I searched Google all over the place for an answer but I can't seem to find the right one so I'll try it here.
I want to store the users' firstname, lastname and the path of the images in the mysqli database and the image in the folder uploads. (the user can upload multiple images)
This works and is no problem.
The issue is:
When for example they type their firstname and lastname and select two images and press the upload button it uploads everything but it also creates two rows with the exact same values.
I want to store everyting in one row, see my code below:
<?php
$con = mysqli_connect('localhost','root','','img_db');
mysqli_select_db($con,'img_db');
$rn = mt_rand();
if(isset($_POST['submit'])&& isset($_FILES['image'])&& !empty($_POST['firstname'])&& !empty($_POST['lastname']))
{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
for($i=0; $i<count($_FILES['image']['name']); $i++)
{
$tmp_name = $_FILES['image']['tmp_name'][$i];
$max_size = 100000;
$path = "uploads/";
$name = $_FILES['image']['name'][$i];
$size = $_FILES['image']['size'][$i];
$type = $_FILES['image']['type'][$i];
$ext = strtolower(substr($name, strpos($name, '.') +1));
$name = str_replace('_','',trim($name));
$name = str_replace('-','',trim($name));
$name = str_replace(' ','',trim($name));
$name = str_replace('__','',trim($name));
if(($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')&&($type=='image/jpeg' || $type=='image/png' || $type=='image/gif')&&$size<=$max_size)
{
if(move_uploaded_file($_FILES['image']['tmp_name'][$i], $path.$rn.$name))
{
mysqli_query($con,"INSERT into `img` (firstname,lastname,url) VALUES('$firstname','$lastname','$rn$name')");
}
}// END EXT
}// END FOR LOOP
}// END IF ISSET POST SUBMIT
?>
Suggestion 1
One solution is to store uploaded file urls in an array (declared before the for loop) and utilize the array outside of the for loop, like so:
if (isset(/* ... */)) {
// Outside your for loop
$files = array();
for (/* .. */) {
// Doing things
if (/* $ext stuff */) {
if (move_uploaded_file(/* ... */))
{
$files[] = $rn.$name;
}
} // End EXT
} // End FOR
// Utilize $files array to determine how you want to store all of these URLs in one field.
// Let's say you created a variable called $store with the desired representation.
mysqli_query($con,"INSERT into `img` (firstname,lastname,url) VALUES('$firstname','$lastname','$store')");
} // End ISSET
Suggestion 2
You could use a two-table structure (one table is users, one table is images) and create a foreign key relation from each image table row to a user table row via the desired user's primary key.
See: http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html

PHP/HTML/mySQL URL Caching Problem

I have this function: http://pastebin.ca/2058418
It basically checks to see if a tables contains some URLs to pictures of a band. If it does, then it will order the table by random, choose the first result and then output the html code to insert the picture. If the table does not have the pictures of that specific band, then it downloads an XML file which contains the image URL's, parses the XML and inserts in into the table, and then gets the HTML code for the image like before.
In terms out html output, you can't tell if the image URL has been cached or not. HOWEVER, when the image URL is cached (for the first time), whatever web browser you use will not display the image. The HTML is fine - the image is linked correctly.
Do you have any ideas? A live version of the site which contains this function is here: http://redfern.me/similar/. I have just emptied the tables, so there shouldn't be many cached URL's. Try choosing a band, and then see if the image loads. You can tell if the URL's where cached or not by looking at the bottom of the page.
basically looks like you wasn't returning after you fetched the image first time.
<?php function getimage($artist){
$api_key = "XXXXXXXXX";
$iquery = mysql_query("SELECT url FROM `images` WHERE artist = '".$artist."' ORDER BY RAND() LIMIT 1");
if($artist != ""){
$artist = str_replace(" ", "+", $artist);
if(mysql_num_rows($iquery) == 0){
$url = "http://developer.echonest.com/api/v4/artist/images?format=xml&api_key=".$api_key."&name=".$artist."&results=20";
$data = file_get_contents($url);
if($data=false){return 'Error Getting Image';}
$images = new SimpleXMLElement($data);
foreach($images as $image){
foreach($image->image as $indimage){
$insiquery = "INSERT INTO images (id, artist, url) VALUES (NULL, '$artist','".$indimage->url."')";
mysql_query($insiquery);
}
}
return "<img src=\"".$indimage->url."\" alt=\"$artist image\" />";
}else{
$imgurl = mysql_fetch_array($iquery);
return"<img src=\"".$imgurl['url']."\" alt=\"$artist image\" />";
}
}
else{
return"Image Aquire Function Error: <i>No Band Specified</i>";
}
return null;
}?>
echo getimage('Britney Spears');
That's simply because when you enter to the "xml call" your var "$imgurl[0]"
is empty :
try something like this :
$images = new SimpleXMLElement($data);
$xmlImgUrl = array();
foreach($images as $image){
foreach($image->image as $indimage){
$xmlImgUrl[] = $indimage->url;
$insiquery = "INSERT INTO images (id, artist, url) VALUES (NULL, '$artist','".$indimage->url."')";
mysql_query($insiquery);
}
}
}
$imgurl = $nrows == 0 ? $xmlImgUrl : mysql_fetch_row($iquery);
if(!empty($imgurl)) echo "<img src=\"".$imgurl[0]."\" alt=\"$artist image\">";
which instantiate an array of image urls when no results in mysql.

php mysql insert (when something is repeart, insert an empty value)

I want insert some articles. I want make a judge first, if the image value has already in the database, insert a null value.
For more explain:
If there have these data:
title1,image1
title2,image2 //this is image2 first appear, so insert it
title3,image2 //image2 has already in the database, so insert an empty value for just image field
title4
title5,image3
the final data insert into the database should like this:
title | image
title1,image1
title2,image2
title3
title4
title5,image3
Here is my code, but it still insert the repeat value into the database. So is there any one can help me? thanks.
foreach{//first here has a foreach to make all the articles as a queue
...
if(!empty($image)){ //first judge if the insert article had a image value
$query1 = mysql_query("select * from articles where .image = '".$image."' ");
while ($row = mysql_fetch_array($query1)) {
$image1 = $row['image'];
}
}
if(!empty($image1)){ //make a query first if the image has already in the database
mysql_query("INSERT INTO articles (title,image) SELECT '".$title."','' ");
}else{
mysql_query("INSERT INTO articles (title,image) SELECT '".$title."','".$image."' ");;
}
}
Your first query contains an error. You have to remove the dot before "image":
where **.**image
As Francesco mentioned that dot could be a problem for that query.
Not really clear what you are trying to do here. But if you are trying to stop same image file being stored twice then you should use something like this below:
function is_same_file( $image1, $image2 ){
if( filesize($image1) != filesize($image2)
return false;
if( hash_file('md5', $image1) != hash_file('md5', $image2) )
return false;
return true;
}

Categories