PHP - Upload Several Images And Save In Mysql Table
I receive files/images and loop through an array as follows:
$files=rearrfiles( $_FILES['image']); foreach($files as $key=>$item) { if(is_array($item) && !empty($item['name']) && !empty($item['tmp_name'])){ //$_POST['imageFile']=$item['name']; //echo $item['name']; if($error!=true && !uploadImageB(array('image'=>'image'), DB_EXTENTION."mod_projects_images", $naming, $search = $editId, $dir, 'photo')) { $error=true; $action='Edit'; $message.='<br>Images were unable to be uploaded.'; } } }The function uploadImageB() is as follows: function uploadImageB($info, $table, $naming, $search, $path, $add='uploaded', $maxw=1280, $maxh=1280, $dynamic=true, $id='Id', $thumbMaxWidth = 120) { global $connection; if(!$_POST){ global $HTTP_POST_VARS; @$_POST=$HTTP_POST_VARS;} if(!$_FILES){ global $HTTP_POST_FILES; @$_FILES=$HTTP_POST_FILES;} if(is_array($info) && !empty($info) && $table!='' && !empty($path)) { $error=false; $d=$naming; foreach($info as $key=>$val) { $names[$val]=$dynamic==true?$add.'_'.$result[$id].'_'.$d.'_.'.strtolower(mygetext($_FILES[$val]['name'])):$add.strtolower(mygetext($_FILES[$val]['name'])); if(is_array(@$_FILES[$val]) && !empty($_FILES[$val]['name']) && !empty($names[$val])) { if(!singMove($path, $names[$val], $_FILES[$val], array(), array('gif', 'jpeg', 'jpg', 'png', 'bmp', 'svg'))) { $error=true; break; } else{ $valid[$val]=$names[$val]; resizeImage($path.$names[$val], $maxw, $maxh); make_thumb($path.$names[$val],$names[$val], $path, $thumbMaxWidth); } } } if($error==true) return false; elseif(!empty($valid)) { $connection->info=$info; $connection->input=$valid; $connection->id=array('field'=>$id, 'val'=>addslashes($result[$id])); $connection->makenew($table); $connection->return_db($connection->query); } } return true; }I get the error: Images were unable to be uploaded. Any help? Similar TutorialsOne image is displaying but when i choose image 2 it overlaps image 1..
gallery.php 8.77KB
7 downloads
I am having trouble trying to save my image file names to mysql after reading a dir. I am trying to use the file below.
Any help would be appreciated. I was originallly getting the files to list but they we not showing up in the database.
Now the page shows up blank.
<?php require("config_0.php"); // Connect to server and select database. mysql_connect($dbhost, $dbuser, $dbpass)or die("cannot connect"); mysql_select_db("test")or die("cannot select DB"); $files = glob("images/*.jpg"); for ($i=1; $i<count($files); $i++) { $num = $files[$i]; $sql="INSERT INTO images (url) VALUES ('$num')"; if (!mysql_query($sql)) { die('Error: ' . mysql_error()); } echo '<img src="'.$num.'" alt="random image">'." "; } ?> I've looked around at a bunch of sample code and cannot seem to get this to work. I'm trying to create a table with the values provided in a form along with an uploaded image. Here is what I have. Code: [Select] <?php //Set variables from form $title = $_POST["title_textfield"]; $description = $_POST["description_textbox"]; $price = $_POST["price_textfield"]; $time = date("ymdHis"); $me = $myuserID /Create Table $con = mysql_connect("mydatabase.mysql.com","databaseAdmin","Adminpass"); if (!$con) { die('Could not connect: ' . mysql_error()); } //check if table exists // Create table $time = date("ymdHis"); $tablename = "1_$me$time"; mysql_select_db("db_01", $con); $sql = "CREATE TABLE $tablename ( ID int NOT NULL AUTO_INCREMENT, imageData LONGBLOB NOT NULL , PRIMARY KEY(comicID), Owner varchar(15), Status varchar(15), AgeRestriction varchar(25), Title varchar(25), Description varchar(100), Price varchar(15) )"; // Execute query mysql_query($sql,$con); //input info into table mysql_query("INSERT INTO $tablename (Owner, Status, Title, Description, Price) VALUES ('$myid', 'Pending', '$title', '$description', '$price')"); //Image control!!!! $maxFileSize = "2000000"; // 2 MB file size //Initializing the image types. $image_array = array("image/jpeg","image/jpg","image/gif","image/bmp","image/pjpeg","image/png"); // valid image type //store the file type of the uploading file. $fileType = $_FILES['userfile']['type']; $nname= $_FILES['userfile']['name']; echo "$nname"; //Initializing the msg variable. Although , not necessary. $msg = ""; // if Submit button is clicked if(@$_POST['Submit']) { // check for the image type , before uploading if (in_array($fileType, $image_array)) { // check whether the file is uploaded if(is_uploaded_file($_FILES['userfile']['tmp_name'])) { // check whether the file size is below 2 mb if($_FILES['userfile']['size'] < $maxFileSize) { // reading the image data $imageData =addslashes (file_get_contents($_FILES['userfile']['tmp_name'])); // inserting into the database $sql = "INSERT INTO $tablename (imageData) VALUES ('$imageData')"; mysql_query($sql) or die(mysql_error()); $msg = " Data successfully uploaded"; } else { $msg = " Error : File size exceeds the maximum limit "; } } } else { $msg = "Error: Not a valid image "; } } mysql_close($con); ?> All the fields populate just fine except the imageData field which shows "[BLOB - 0 Bytes]" Any help would be GREATLY appreciated. Thank you for even taking the time to look. Cordially, TcS what's wrong with this ? i can't upload I think this is the right section to post this is in..... Anyway.....I'm building a web site that requires i have functionality to upload a tab delimited file (or some file format that is easiest) via php and insert the data into MYSQL. I've searched for many third party scripts but none seem to work. So I've decided to move to the community to see if someone can give me insight on how i might accomplish this script. I have some third party scripts but I'm not sure if they'd be of any use. Thank you kindly Hello Guys, I need help on this problem. output: display images for the values that exist in the table: input: the values in a table's column where they're in the format of "0,0" and the image corresponding to it is named 0,0.png this is my attempt $q is retrieving "0,0" however in order for me to retrieve its image i need to add ".png" to it in order to find it in the directory that the image is located. It tried without ".png" and it also doesn't work. $q = 'SELECT ID FROM table'; $dirname = "directory/"; $images = glob($dirname.$q.".png"); foreach($images as $image) { echo '<img src="'.$image.'" /><br />';
Hi, here's my problem: I am trying to make a simple online buying website and I want to display a table with all the fields for each item. So I got that part down which is to just use mysql_fetch_assoc("SELECT * FROM myTable") and use the html table tags stuff, but now I want to display my images in the table, so here's my code to display my mysql database table in html's table tag along w/ php: <html> <head> <title>My Online buying website project</title> </head> <body> <?php mysql_connect("localhost","root"); mysql_select_db("myTable"); $imagesArray=array("Apple_iPhone3GS.jpg","Apple_iPhone4.jpg","product3.jpg","product4.jpg","product5.jpg"); $result=mysql_query("SELECT Name, Manufacturer, Price, Description, SimSupport FROM myTable"); if(mysql_num_rows($result))//if there is at least one entry in bellProducts, make a table { print "<table border='border'>"; print "<tr> <th>Name</th> <th>Manufacturer</th> <th>Price</th> <th>Description</th> <th>SimSupport</th> </tr>"; //NB: now output each row of records while($row=mysql_fetch_assoc($result)) { extract($row); print "<tr> <td>$Name</td> <td>$Manufacturer</td> <td>$Price</td> <td>$Description</td><td>$SimSupport</td> </tr>"; }//END WHILE }//END IF ?> </table> </body> </html> *So how do I go about adding my images in this table? I have code written for image uploading, but it doesn't allow multiple images on a single upload, and doesn't re-size. Anyone willing to share a good upload script that will do the following?: -Allow multiple image uploads (10+ per submission), -Re-size images on upload, and -Rename images. Thanks Brett Hi, Very new to PHP and am enjoying learning the ins and outs etc, but while creating my mam a website, ive ran into a problem while uploading, resizing and saving the file to my web host. Initially i used imagecreatefromjpeg, but this was taking too much memory up, so opted to use imagemagick. All of the features work apart from the file getting saved to the uploads directory on my web space. They always get saved to the root. If someone could help i would be very grateful. The code ive got currently is: <?php // If the form has been submitted do this if(isset($_POST['submit'])) { // Temporary upload image name $original_image = $_FILES['photo']['tmp_name']; // Get the image dimensions $size=GetImageSize( $original_image ); // Name to save the image as - in this case the same as the original $new_image = $_FILES['photo']['name']; // Maximum image width $max_width = "600"; // Maximum image height $max_height = "300"; // Resize the image and save exec("convert -size {$size[0]}x{$size[1]} $original_image -thumbnail $max_widthx$max_height $new_image"); echo "File uploaded<br>"; echo "<img src=\"".$new_image."\">"; } ?> Hopefully someone could help Many thanks, Matk. this script saves the image from a url to the folder were this script is saved, how can i make this code save images into specific folder such as "/image/poster_image/" <?php $img[]='http://images.rottentomatoescdn.com/images/redesign/poster_default.gif'; foreach($img as $i){ echo $i; save_image($i); // if(getimagesize(basename($i))){ // echo '<h3 style="color: green;">Image ' . basename($i) . ' Downloaded OK</h3>'; // }else{ // echo '<h3 style="color: red;">Image ' . basename($i) . ' Download Failed</h3>'; // } } //Alternative Image Saving Using cURL seeing as allow_url_fopen is disabled - bummer function save_image($img,$fullpath='basename'){ if($fullpath=='basename'){ $fullpath = basename($img); } $ch = curl_init ($img); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); $rawdata=curl_exec($ch); curl_close ($ch); if(file_exists($fullpath)){ unlink($fullpath); } $fp = fopen($fullpath,'x'); fwrite($fp, $rawdata); fclose($fp); } ?> I am looking for the code|script to put on my update.php that allows uploaded images to be saved in my database (chmod) 777? PLEASE HELP! Hi, I found a very nice script for saving my TwitPic images in full size. I have tested this script for a couple of times yesterday and it seems that this way of saving images is now blocked by amazon or TwitPic. Using the API it's not possible to download the images as fas I can see, does anyone has an idea ? http://forrst.com/posts/TwitPic_Hack_Get_Full_TwitPic_Image_using_PHP-mFQ Code: [Select] <?php function imgResize($width, $height, $target) { if ($width > $height) { $percentage = ($target / $width); } else { $percentage = ($target / $height); } $width = round($width * $percentage); $height = round($height * $percentage); return "width=\"$width\" height=\"$height\""; } // full url of the TwitPic photo $url = "http://twitpic.com/1pfhfd"; // make the cURL request to TwitPic URL $curl2 = curl_init(); curl_setopt($curl2, CURLOPT_URL, $url); curl_setopt($curl2, CURLOPT_AUTOREFERER, true); curl_setopt($curl2, CURLOPT_RETURNTRANSFER,true); curl_setopt($curl2, CURLOPT_TIMEOUT, 10); $html = curl_exec($curl2); $HttpCode = curl_getinfo($curl2, CURLINFO_HTTP_CODE); $totalTime = curl_getinfo($curl2, CURLINFO_TOTAL_TIME); // if the HTTPCode is not 200 - you got issues if ($HttpCode != 200) { ?><p>Unable to connect to TwitPic. Please try again later.</p><? } else { // if you are not getting any HTML returned, you got another issue. if ($html == "") { ?><p>Yikes! TwitPic is experiencing heavy load. Please close this window and try again.</p><? } else { $dom = new DOMDocument(); @$dom->loadHTML($html); // grab all the on the page $xpath = new DOMXPath($dom); $hrefs = $xpath->evaluate("/html/body//img"); foreach( $hrefs as $href ) { $url = $href->getAttribute('id'); // for all the images on the page find the one with the ID of photo-display if ($url == "photo-display") { // get the SRC attribute of the element with the ID of photo-display $image = $href->getAttribute('src'); // get the image size $imagesize = getimagesize($image); ?> <a href="<? echo $url; ?>" target="_blank"><img class="twitpic" src="<? echo $image; ?>" "<? echo imgResize($imagesize[0], $imagesize[1], 450); ?>"></a> <? break; } } } } ?> HI All, I have a form submission that uploads a photo as well as submitting other data. I would like to change the name of the photo to the id of the person record (created automatically on by the database) then a hyphen, then their first name and lastname. (i am flexible on this). This file name will also need to be submitted into the person record so the photo and the person can be linked. I am struggling with this one - but here is the code i have so far.
<?php include 'includes/dbconn.php'; $target_dir = "img/people/"; $target_file = $target_dir . basename($_FILES["personHeadshot"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); if ($_SERVER['REQUEST_METHOD']=='POST'){ $fn = $_POST['fname']; $ln = $_POST['lname']; $ad1 = $_POST['ad1']; $ad2 = $_POST['ad2']; $city = $_POST['city']; $post = $_POST['postcode']; $tel = $_POST['phone']; $email = $_POST['email']; $crole = $_POST['comRole']; $OFA = $_POST['OFA']; $playerType = $_POST['playerType']; $team = $_POST['primaryTeam']; $stmt = $conn->prepare(" INSERT IGNORE INTO person (fname, lname, committee_role_id, player_type_id, team_id, ad1, ad2, city, postcode, mobile, email, on_field_auth_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?) "); $stmt -> bind_param(ssiiissssssi, $fn, $ln, $crole, $playerType, $team, $ad1, $ad2, $city, $post, $tel, $email, $OFA); $stmt -> execute(); // Check if image file is a actual image or fake image //photo upload $check = getimagesize($_FILES["personHeadshot"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } //photo upload header("location: ../admin-people-list.php"); } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["personHeadshot"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["personHeadshot"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["personHeadshot"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } }
Hi Guys, I have stuck with my problem and i am nothing to php, i already posted this to another php script forum, but haven't solve, so i wondering if anyone here help me and many thanks. this is all about game scores from .xml file inside the xml file itself as: Code: [Select] <gesmes:Envelope> <gesmes:subject>Reference Scores</gesmes:subject> - <gesmes:Sender> <gesmes:name>Game Information Scores</gesmes:name> </gesmes:Sender> - <Cube> - <Cube time="2010-10-13"> <Cube scores="GameA1" value="1.5803"/> <Cube scores="GameA2" value="21.35"/> ............etc <Cube scores="GameA15" value="135"/> </Cube> </Cube> </gesmes:Envelope> then i got php script that can save all data of .xml above to mysql, look like <?php class Scores_Converter { var $xml_file = "http://192.168.1.112/gamescores/scores-daily.xml"; var $mysql_host, $mysql_user, $mysql_pass, $mysql_db, $mysql_table; var $scores_values = array(); //Load convertion scores function Scores_Converter($host,$user,$pass,$db,$tb) { $this->mysql_host = $host; $this->mysql_user = $user; $this->mysql_pass = $pass; $this->mysql_db = $db; $this->mysql_table = $tb; $this->checkLastUpdated(); $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass); $rs = mysql_select_db($this->mysql_db,$conn); $sql = "SELECT * FROM ".$this->mysql_table; $rs = mysql_query($sql,$conn); while($row = mysql_fetch_array($rs)) { $this->scores_values[$row['scores']] = $row['value']; } } /* Perform the actual conversion, defaults to 1.00 GameA1 to GameA3 */ function convert($amount=1,$from="GameA1",$to="GameA3",$decimals=2) { return(number_format(($amount/$this->scores_values[$from])*$this->scores_values[$to],$decimals)); } /* Check to see how long since the data was last updated */ function checkLastUpdated() { $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass); $rs = mysql_select_db($this->mysql_db,$conn); $sql = "SHOW TABLE STATUS FROM ".$this->mysql_db." LIKE '".$this->mysql_table."'"; $rs = mysql_query($sql,$conn); if(mysql_num_rows($rs) == 0 ) { $this->createTable(); } else { $row = mysql_fetch_array($rs); if(time() > (strtotime($row["Update_time"])+(12*60*60)) ) { $this->downloadValueScores(); } } } /* Download xml file, extract exchange values and store values in database */ function downloadValueScores() { $scores_domain = substr($this->xml_file,0,strpos($this->xml_file,"/")); $scores_file = substr($this->xml_file,strpos($this->xml_file,"/")); $fp = @fsockopen($scores_domain, 80, $errno, $errstr, 10); if($fp) { $out = "GET ".$scores_file." HTTP/1.1\r\n"; $out .= "Host: ".$scores_domain."\r\n"; $out .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5\r\n"; $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); while (!feof($fp)) { $buffer .= fgets($fp, 128); } fclose($fp); $pattern = "{<Cube\s*scores='(\w*)'\s*value='([\d\.]*)'/>}is"; preg_match_all($pattern,$buffer,$xml_values); array_shift($xml_values); for($i=0;$i<count($xml_values[0]);$i++) { $exchange_value[$xml_values[0][$i]] = $xml_values[1][$i]; } $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass); $rs = mysql_select_db($this->mysql_db,$conn); foreach($exchange_value as $scores=>$value) { if((is_numeric($value)) && ($value != 0)) { $sql = "SELECT * FROM ".$this->mysql_table." WHERE scores='".$scores."'"; $rs = mysql_query($sql,$conn) or die(mysql_error()); if(mysql_num_rows($rs) > 0) { $sql = "UPDATE ".$this->mysql_table." SET value=".$value." WHERE scores='".$scores."'"; } else { $sql = "INSERT INTO ".$this->mysql_table." VALUES('".$scores."',".$value.")"; } $rs = mysql_query($sql,$conn) or die(mysql_error()); } } } } /* Create the scores table */ function createTable() { $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass); $rs = mysql_select_db($this->mysql_db,$conn); $sql = "CREATE TABLE ".$this->mysql_table." ( scores char(3) NOT NULL default '', value float NOT NULL default '0', PRIMARY KEY(scores) ) ENGINE=MyISAM"; $rs = mysql_query($sql,$conn) or die(mysql_error()); $sql = "INSERT INTO ".$this->mysql_table." VALUES('GameA0',1)"; $rs = mysql_query($sql,$conn) or die(mysql_error()); $this->downloadValueScores(); } } ?> but that php script above just create table of mysql below CREATE TABLE IF NOT EXISTS `scrore_table` ( `scores` char(3) NOT NULL default '', `value` float NOT NULL default '0', PRIMARY KEY (`scores`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; INSERT INTO `scrore_table` (`scores`, `value`) VALUES ('GameA0', 1), ('GameA1', 1.5651), ......etc ('GameA15', 95.572); while of my existing database table look like: CREATE TABLE IF NOT EXISTS `scrore_table` ( `scrore_id` int(11) NOT NULL auto_increment, `scrore_title` varchar(32) collate utf8_bin NOT NULL default '', `scores` varchar(3) collate utf8_bin NOT NULL default '', `decimal_place` char(1) collate utf8_bin NOT NULL, `value` float(15,8) NOT NULL, `date_updated` datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (`currency_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; ; INSERT INTO `scrore_table` (`scrore_id`, `scrore_title`, `scores`, `decimal_place`, `value`, `date_updated`) VALUES (1, 'Game Class A0', 'GameA0', '2', 1.00000000, '2010-04-06 22:00:54'), (2, 'Game Class A1', 'GameA1', '2', 1.52600002, '2010-04-06 22:00:54'), ..............................etc (14, 'Game Class A15', 'GameA15', '2', 1.13999999, '2010-04-06 22:00:54'); as i said i newbie to php then i dont know how to modify the php code above able to automatically create the table and insert/update new fields e.g. scrore_id, scrore_title,decimal_place, date_updated also all values to my existing database i looking for some helps and thanks in advance.. In MVC type architecture, is it safe to do this ini_set("mysql.default_host"$mysql_host); ini_set("mysql.default_user",$mysql_user); ini_set("mysql.default_password",$mysql_pass); in my index.php file. Then, every time time I do a query in a model, mysql_connect(); // MySQL connects using the default values from the ini_sets we did. mysql_query($query); mysql_close(); The reason behind this, would be to avoid passing database variables to objects/models etc or defining constants. Maybe there's a better way? I'm looking into database abstraction.
Hello, I am a newbie regarding PHP and have done mostly only front-end web design for a couple of years and recently started querying DB's and displaying the data, but now this is a new project.
I've tested code snippets as the ones below, but fail to incorporate them in the bigger picture of what I'm trying to achieve. <?php // https://gist.github.com/magnetikonline/650e30e485c0f91f2f40 class DumpHTTPRequestToFile { public function execute($targetFile) { $data = sprintf( "%s %s %s\n\nHTTP headers:\n", $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL'] ); foreach ($this->getHeaderList() as $name => $value) { $data .= $name . ': ' . $value . "\n"; } $data .= "\nRequest body:\n"; file_put_contents( $targetFile, $data . file_get_contents('php://input') . "\n" ); echo("Done!\n\n"); } private function getHeaderList() { $headerList = []; foreach ($_SERVER as $name => $value) { if (preg_match('/^HTTP_/',$name)) { // convert HTTP_HEADER_NAME to Header-Name $name = strtr(substr($name,5),'_',' '); $name = ucwords(strtolower($name)); $name = strtr($name,' ','-'); // add to list $headerList[$name] = $value; } } return $headerList; } } (new DumpHTTPRequestToFile)->execute('./dumprequest.csv'); This snippet also seems to return the headers and their values but I don't know how to efficiently write and append it to a TXT or CSV, or preferably, directly into a MySQL database. <?php foreach (getallheaders() as $name => $value) { echo "$name: $value"; echo "<br>"; } ?>
Any help towards storing the header values of HTTP POST requests into a database would be greatly appreciated! Hi I am using php5 and Mysql I want to generate user id like phone format (Ex: xxx-xxx-xxxx). and check that user id exists in database or not. if yes, i have to generate new user id etc. If that user id not in database, i have to insert user id for new user. Means i have generate unique user id for login purpose. Generating user id is working fine. availability of user id also ok for me by using mysql_num_rows() function. But if user id i exists in database, how can i generate new user id. All this will be done in single instance (When user click on submit button from registration form). Here is my script. Code: [Select] <?php function UserID() { $starting_digit=5; $first_part1=rand(0,99); if(strlen($first_part1)==1) { $first_part="0".$first_part1; } else { $first_part=$first_part1; } $second_part1=rand(1,999); if(strlen($second_part1)==1) { $second_part="00".$second_part1; } elseif(strlen($second_part1)==2) { $second_part="0".$second_part1; } else { $second_part=$second_part1; } $third_part1=rand(1,9999); if(strlen($third_part1)==1) { $third_part="000".$third_part1; } elseif(strlen($third_part1)==2) { $third_part="00".$third_part1; } elseif(strlen($third_part1)==3) { $third_part="0".$third_part1; } else { $third_part=$third_part1; } $userid=$starting_digit.$first_part."-".$second_part."-".$third_part; return $userid; } $random_userid=UserID(); $sql=mysql_query("select * from users where user_id='".$random_userid."'"); if(mysql_num_rows($sql)==0) { $insert=mysql_query("insert into users (user_id) values ('".$random_userid."')"); } ?> If user id not exists in database, that user id inserting in database successfully. If not, empty value is inserting, not generating new user id. Can any one help me out please. I would like to store PDF file into mysql (this part works) and then send it as email attachment and it should be retrieved from mysql table. Here's the code I have for now, but what it gives me is 0bytes large PDF file Saving PDF to mysql (it works), because size of blob in mysql table is OK. $fp = fopen('generated.pdf', 'r'); $content = fread($fp,filesize('generated.pdf')); $content = addslashes($content); fclose($fp); $DB->Query('insert into pdf_files (pdf_file, name) values ("'.$content.'", "'.$name.'")'); And here's the mailing part <?php $query = "SELECT name, pdf_file FROM pdf_files $result = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_array ( $result)) { $fileContent =$row['pdf_file']; $fileName=$row['name']; } $fileatt = $fileContent; // getting file $fileatt_type ="application/pdf"; //type of file $fileatt_name = "attachment.pdf"; // name $fileatt_size = $fileSize; $email_from = "dont@have.it"; // mail from $email_subject = "Testtt"; // subject $email_message = "Testtt.<br>"; $email_message .= "Testtt.<br>"; // Message $email_to = $mail_user; // users mail $headers = "From: ".$email_from; $file = fopen($fileatt,'rb'); $data = fread($file,filesize($fileatt)); fclose($file); $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; $email_message .= "Testtt.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $email_message .= "\n\n"; $data = chunk_split(base64_encode($data)); $email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" . " name=\"{$fileatt_name}\"\n" . //"Content-Disposition: attachment;\n" . //" filename=\"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data .= "\n\n" . "--{$mime_boundary}--\n"; $ok = @mail($email_to, $email_subject, $email_message, $headers); if($ok) { echo "<font face=verdana size=2><center>Mail was sent</center>"; } else { die("Error!"); } ?> <?php $GLOBALS['title']="Admission-HMS"; $base_url="http://localhost/hms/"; require('./../../inc/sessionManager.php'); require('./../../inc/dbPlayer.php'); require('./../../inc/fileUploader.php'); require('./../../inc/handyCam.php'); $ses = new \sessionManager\sessionManager(); $ses->start(); if($ses->isExpired()) { header( 'Location:'.$base_url.'login.php'); } else { $name=$ses->Get("loginId"); } $msg=""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (isset($_POST["btnSave"])) { $db = new \dbPlayer\dbPlayer(); $msg = $db->open(); echo '<script type="text/javascript"> alert("'.$msg.'");</script>'; if ($msg = "true") { $userIds = $db->getAutoId("U"); $flup = new fileUploader\fileUploader(); $perPhoto = $flup->upload("/hms/files/photos/",$_FILES['perPhoto'], $userIds[1]); // var_dump($perPhoto); $handyCam=new \handyCam\handyCam(); if (strpos($perPhoto, 'Error:') === false) { $dateNow=date("Y-m-d"); $data = array( 'userId' => $userIds[1], 'userGroupId' => "UG004", 'name' => $_POST['name'], 'studentId' => $_POST['stdId'], 'cellNo' => $_POST['cellNo'], 'gender' => $_POST['gender'], 'dob' => $handyCam->parseAppDate($_POST['dob']), 'passportNo' => $_POST['passportNo'], 'fatherName' => $_POST['fatherName'], 'fatherCellNo' => $_POST['fatherCellNo'], 'perPhoto' => $perPhoto, 'admitDate' => $dateNow, 'isActive' => 'Y' ); $result = $db->insertData("studentinfo",$data); if($result>=0) { $data = array( 'userId' => $userIds[1], 'userGroupId' => "UG004", 'name' => $_POST['name'], 'loginId' => $_POST['stdId'], 'verifyCode' => "vhms2115", 'expireDate' => "2115-01-4", 'isVerifed' => 'Y' ); $result=$db->insertData("users",$data); if($result>0) { $id =intval($userIds[0])+1; $query="UPDATE auto_id set number=".$id." where prefix='U';"; $result=$db->update($query); // $db->close(); echo '<script type="text/javascript"> alert("Admitted Successfully.");</script>'; } else { echo '<script type="text/javascript"> alert("' . $result . '");</script>'; } } elseif(strpos($result,'Duplicate') !== false) { echo '<script type="text/javascript"> alert("Student Already Exits!");</script>'; } else { echo '<script type="text/javascript"> alert("' . $result . '");</script>'; } } else { echo '<script type="text/javascript"> alert("' . $perPhoto . '");</script>'; } } else { echo '<script type="text/javascript"> alert("' . $msg . '");</script>'; } } Hello... I have some simple code but no ideas for upload another image?? PHP stores image name in database but there is no second picture uploaded in the images/ folder. Pls help. Thanks if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 2000000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "<strong>Slika:</strong> " . $_FILES["file"]["name"] . "<br />"; echo "<strong>Format slike:</strong> " . $_FILES["file"]["type"] . "<br />"; echo "<strong>Velicina:</strong> " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "<strong>Temp file:</strong> " . $_FILES["file"]["tmp_name"] . "<br />"; // here is mistake??? move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . $_FILES["file"]["name"]); // $sql="INSERT INTO test (name, something, slika, slika2) VALUES ('".$_POST['name']."', '".$_POST['something']."', '".$_FILES['file']['name']."', '".$_FILES['slika1']['name']."')"; if (mysql_query($sql)) { echo "Sucess"; } else { echo "Error" . mysql_error(); } } } else { echo "Invalid file"; } ?> |