PHP - Unique Profile Views Counter (update Database With New Number)
Hi all,
I'm trying to create a PHP script for user's profile to display the amount of times they've been viewed. I'm looking to have this script increase on a unique view, and it should update the variable in the database. Profiles are accessed by the following link: userprofile.php?userid=X (where X is the ID, e.g. 1, 2, 1001, 345982, etc.). The database variable I'm looking to update is called ProfileViews. I began developing the script, which is as follows: Code: [Select] $_SESSION['Viewed'] = 0; if ($_SESSION['Viewed'] == 0) { $profileViewsQuery = mysql_query("SELECT ProfileViews FROM Users WHERE UserID='????'"); $getProfileViews = mysql_fetch_array($profileViewsQuery); $profileViews = $getProfileViews['ProfileViews']; $profileViews = $profileViews + 1; mysql_query("UPDATE Users SET ProfileViews='$profileViews' WHERE UserID='????'"); $_SESSION['Viewed'] = 1; } However, I'm stumped on a couple things. Could you possibly help me out? 1. How can I get the script to recognize the link accessed's ID? E.g. when a user goes to userprofile.php?userid=1001, how can I get the script to identify the ID to update should be 1001? This is where the "????" would be replaced in the code. 2. On page load, the variable is always going to be $_SESSION['Viewed'] = 0, which isn't going to produce unique hits. Do you have any recommendations how I could achieve unique hits using this method? Thanks very much for reading. Similar TutorialsMy current project requires me to save the number of views an image (banner ad) has appeared on users website. The problem here is that the image will be appearing on several users website and i want to be able to save the number of times it has appeared on my database. I know how to do this if the image was on the same server as the database, but not when the image and database are on completely different servers. This is somewhat like analytic where it tracks the visitors to a page. Does anyone how i can accomplish this? i figured i would need to create a JavaScript code to provide to the user so they can place it on the site but how do i get that code to connect to my database? hi!, is it possible to use rand() to generate unique number that will be saved in a database as a primary key? Since i dont want to have numbers like 00001 incrementing on the table. They dont look like real account numbers... i need something like 45642 or 95452 and the like. thanks in advance. Hey guys, I m not yet an experienced coder. SO faced alot of problems. Here, I'm trying to generate a UNIQUE RANDOM NUMBER set between two numbers. Repetative occurance must be avoided by all means as I want every number so generated bears a unique value. In other words, every values that made entry into the field of my database should be differant from each others. <?php $conN=mysql_connect("localhost","root",""); if(!$conN) { die('error'.mysql_error()); } mysql_select_db("freebie_allusers",$conN); $UIN=mt_rand(1,5); $locateUIN="SELECT UIN FROM user_info WHERE UIN='".$UIN."'"; $fetchUIN=mysql_query($locateUIN); $resultUIN=mysql_num_rows($fetchUIN); if($resultUIN>0) { WHAT CODE IS REQUIRED HERE SO AS TO GENERATE UNIQUE RANDOM NUMBER? } else echo $UIN; ?> Thanx in advance Currently on my website i record the statistics, for my pages they include unique views, and total page views. at the moment every time a visitor loads a page a script updates a MySql Db. This seems very resource intensive, is there a better way to record statistics?? hii i had created a site but i'm facing one problem. where users had to show there page to earn money... like 1000 imp/1$. but what happened is that when ever page reloads in same browser with same ip, it gaining impression. is there any way that i can limit 1 impression per ip in 24 hours... Any help will be appreciated... I made this for my site and decided to share with the community. Depending on how you do the code and where, this can keep count of the views in different ways. Please read the somewhat directions have in the code, make a folder called counters, and be sure to include this below function file. I named the function file index.php and belongs in the counters folder you make. <?php /* name this file index.php and place it into a folder called counters the function will create a unique text file for each unique item, good for posts or pages and store all the files in the counters folder For the total website views,add this to your header file or top of your page <?php include('counters/index.php'); $website_view_url = "http://".$_SERVER['HTTP_HOST']; } $website_views = getViews("$website_view_url"); echo "<br />".$website_views."<br />"; ?> For the total pages or scripts views,add this to your header file or top of your page <?php include('counters/index.php'); $total_page_view_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']; } $total_page_views = getViews("$total_page_view_url"); echo "<br />".$total_page_views."<br />"; ?> For entire urls including queries,add this to your header file or top of your page <?php include('counters/index.php'); $page_queries_view_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']; if (!empty($_SERVER["QUERY_STRING"])) { $page_queries_view_url .= "?".$_SERVER['QUERY_STRING']; } $page_queries_views = getViews("$page_queries_view_url"); echo "<br />".$page_views."<br />"; ?> for usage in posts like by id: if do not want the pages counted and did not do the above code,include the below somewhere near the beginning of your page <?php include('counters/index.php');?> Then in the posts loop, you can associate your $row['id']; or some other unique value <?php $post_views = $row['id']; $post_views = getViews("$post_views"); echo "<br />Post Views ".$post_views."<br />"; ?> if would like to combine any the above or use them all, just be sure to just include include('counters/index.php'); only one time */ function getViews($views_count_value) { $views_count_value = md5("$views_count_value"); $views_count_file_name = "counters/$views_count_value.txt"; if (!file_exists($views_count_file_name)) { $views_count =0; $file_handle = fopen($views_count_file_name, 'w') or die("can't open file"); fwrite($file_handle, "$views_count"); fclose($file_handle); } $file_handle = fopen($views_count_file_name, "r"); $views_count = fread($file_handle, filesize("$views_count_file_name")); fclose($file_handle); if ($views_count <= 0){ $views_count =1; } else { ++$views_count; } $file_handle = fopen($views_count_file_name, "w+"); fwrite($file_handle, "$views_count"); fclose($file_handle); return("$views_count"); } ?> Hey everyone! My upcoming site will host, potentiallly thousands of photographs, and i was wondering how to go about having a unique ip hit counter for EACH image. Obviously i dont want people refreshing the page to gain hits, therefore the hit counter will need to be dependent on the IP address. I have used google and found a few hit counters however i need to know how to make this practical as it seems like it will require a lot of databases! Thanks in advanced, Jimmy. Hi, I have a web site that sells both video and images. The full versions are located securely behind a paywall, however in a bid to get visitors to purchase them and to promote the members offering I have trailer videos of 30 seconds to one minute and four free images per imageset. I want to be able to restrict the number of images a visitor can view for free to 12 and the number of videos a visitor can play to 5. With a little graphic/overlay notifying the user when they have exceeded their free play/preview limit. I have been advised that a tracking cookie and php if statement would be the way to go to achieve this. I have got a cookie that is successfully logging views that is written to on a free preview link as an onclick function. I have tried writing some php if code that will have the normal thumbnail or video divs display as usual if the views recorded in the cookie are below 12 or five, respectively, and have a not allowed, please subscribe div that would show over the thumbnails or video divs should the number of views exceed the threshold. My PHP code does not seem to be working at all, I have ran it through an online syntax checker - corrected the mistakes and now it's supposed to be working but opts to display nothing instead of either if argument. Videos then become a whole other problem because at the moment I have no other way to track the view/visit other than to count the loading of the video summary page with the free player as the preview, whether or not the clip is played - ideally I would like the view to be counted when the video begins to play. But I have no idea how to write to the cookie from Flash (is that even possible?) Any help would be greatly appreciated. Hello, I am trying to create article directory for learning PHP MySql and i want to write a script for recording number of views for an article and store it in Database. Can anyone please direct me to a nice simple tutorial or help me with the steps or algorithm? Suppose the link for an article is http://www.domain.com/article.php?id=123 Do i need to put extra variables and create a tracking PHP file for it? How can i make this hit counter code, so that it doesnt update the views on ALL of my videos. i want it to be unique for each video id. any ideas? Code: [Select] <?php $querySelect = mysql_query("SELECT * FROM `mydatabase` WHERE `counter`"); $row = mysql_fetch_assoc($querySelect); $counter = $row['counter']; if (empty($counter)) { $counter = 1; $insert = mysql_query ("INSERT INTO counter VALUES ('counter')"); } $add = $counter+1; $insertNew = mysql_query("UPDATE mydatabase SET counter=('$add')"); echo "Video Views"; echo ":"; echo" "; echo"<br />"; echo "$counter"; ?> www.game4vids.com if you pick a video you can see that it changes the views on ALL the videos i have. ok, so I have found this code to edit profiles online, only problem is that the data is not being posted to the database, there are no errors, just basically refreshes the page. could you take a look and see if you can help me? Code: [Select] <?php } //action: edit user ----------------------------------------------------------------------------- if (isset($_GET['edit']) && isset($_GET['id'])) { $userid = (int) $_GET['id']; if ($userid == 0) { die("Invalid ID provided."); } //execution when completed the edit user form and pressed submit button --------------------- if (isset($_POST['editUser'])) { //validate data ------------------------------------------------------------------------ //check empty fields //passwords won't be checked, as they are not required foreach ($_POST as $k=>$v) { if ($v == "" && !in_array($k,$notRequired)) { $error[$k] = "<strong>This field is empty</strong>"; } } //escape string $name = mysql_real_escape_string($_POST['name']); $phone = mysql_real_escape_string($_POST['phone']); $address = mysql_real_escape_string($_POST['address']); $city = mysql_real_escape_string($_POST['city']); $state = mysql_real_escape_string($_POST['state']); $zip = mysql_real_escape_string($_POST['zip']); $cell = mysql_real_escape_string($_POST['cell']); $email = mysql_real_escape_string($_POST['email']); $username = mysql_real_escape_string($_POST['username']); $badges = mysql_real_escape_string($_POST['badges']); $rank = mysql_real_escape_string($_POST['rank']); $accounttype = mysql_real_escape_string($_POST['accounttype']); //check email validation, the function is available at config.php if (!check_email($_POST['email'])) { $error['email'] .= " <strong>Email is not valid!</strong>"; } //check email exists in database $res = mysql_query("SELECT email FROM members WHERE email='".$email."' AND userid != '".$userid."'"); if (mysql_num_rows($res) == 1) { $error['email'] .= " <strong>Email already existst in database!</strong>"; } //check username exists in database $res = mysql_query("SELECT username FROM members WHERE username='".$username."' AND username != '".$username."'"); if (mysql_num_rows($res) == 1) { $error['username'] .= " <strong>Username already existst in database!</strong>"; } //check both passwords are the same when password fields are not empty //end validate data --------------------------------------------------------------------- //save to database when no errors are detected ------------------------------------------ if (count($error) == 0) { $query = "UPDATE members SET username='".$username."', email='".$email."',name='".$name."', phone='".$phone."',address='".$address."', city='".$city."',state='".$state."', zip='".$zip."',cell='".$cell."', accounttype='".$accounttype."',badges='".$badges."', rank='".$rank."' "; $query .= "username='".$username."', email='".$email."',name='".$name."', phone='".$phone."',address='".$address."', city='".$city."',state='".$state."', zip='".$zip."',cell='".$cell."', accounttype='".$accounttype."',badges='".$badges."', rank='".$rank."' WHERE userid='".$userid."'"; //update username session if you edit yourself if ($userid == $_SESSION['auth_admin_userid']) { $_SESSION['auth_admin_username'] = $username; } if (mysql_query($query)) { echo "<p><strong>User has been edited and saved to the database.</strong></p>"; } else { echo "<strong>User has NOT been edited and saved into the database. ".mysql_error()."</strong>"; } } } //get user from the database and put data into $_POST variables. $rs = mysql_query("SELECT name, username, phone, address, city, state, zip, cell, email, badges, rank, accounttype FROM members WHERE userid = ".$userid.""); if (mysql_num_rows($rs) == 0) { die("User does not exists!"); } $row = mysql_fetch_assoc($rs); $_POST['name'] = $row['name']; $_POST['username'] = $row['username']; $_POST['phone'] = $row['phone']; $_POST['address'] = $row['address']; $_POST['city'] = $row['city']; $_POST['state'] = $row['state']; $_POST['zip'] = $row['zip']; $_POST['cell'] = $row['cell']; $_POST['email'] = $row['email']; $_POST['badges'] = $row['badges']; $_POST['rank'] = $row['rank']; $_POST['accounttype'] = $row['accounttype']; //if is admin, then $_POST['admin'] exists ?> <div id="TabbedPanels1" class="TabbedPanels"> <ul class="TabbedPanelsTabGroup"> <li class="TabbedPanelsTab" tabindex="0">My Info</li> <li class="TabbedPanelsTab" tabindex="0">Merit Badges</li> <li class="TabbedPanelsTab" tabindex="0">Scout Rank</li> </ul> <div class="TabbedPanelsContentGroup"> <div class="TabbedPanelsContent"> <form action="admin.php?edit&id=<?php echo $userid;?>" method="post"> <table align="center" cellpadding="8" cellspacing="8"> <tr> <td><div align="right">Name:</div></td> <td> <p><input type="text" name="name" value='<?php echo $_POST['name'];?>' /> <?php echo(isset($error['name']))?$error['name']:"";?></p></td> </tr> <tr> <td>Phone Number:</td> <td><input type="text" name="phone" value='<?php echo $_POST['phone'];?>' /> <?php echo(isset($error['phone']))?$error['phone']:"";?></td> </tr> <tr> <td><div align="right">Address:</div></td> <td><input type="text" name="address" value='<?php echo $_POST['address'];?>' /> <?php echo(isset($error['address']))?$error['address']:"";?></td> </tr> <tr> <td><div align="right">City:</div></td> <td><input type="text" name="city" value='<?php echo $_POST['city'];?>' /> <?php echo(isset($error['city']))?$error['city']:"";?></td> </tr> <tr> <td><div align="right">State:</div></td> <td><input type="text" name="state" value='<?php echo $_POST['state'];?>' /> <?php echo(isset($error['state']))?$error['state']:"";?></td> </tr> <tr> <td><div align="right">Zip Code:</div></td> <td><input type="text" name="zip" value='<?php echo $_POST['zip'];?>' /> <?php echo(isset($error['zip']))?$error['zip']:"";?></td> </tr> <tr> <td><div align="right">Email:</div></td> <td> <p> <input type="text" name="email" value='<?php echo $_POST['email'];?>' /> <?php echo(isset($error['email']))?$error['email']:"";?></p></td> </tr> <tr> <td><div align="right">Cell Phone:</div></td> <td><input type="text" name="cell" value='<?php echo $_POST['cell'];?>' /> <?php echo(isset($error['cell']))?$error['cell']:"";?></td> </tr> <tr> <td class="aaaaaaa" align="right">Username:</td> <td><label for="username"></label> <input type="text" name="username" value='<?php echo $_POST['username'];?>' /> <?php echo(isset($error['username']))?$error['username']:"";?></p> </td> </tr> </table> <p> </p> <input name="submit" type="submit" value="Save" /> </form> </div> <div class="TabbedPanelsContent"> <label for="badges"></label> <input name="badges" type="text" id="badges" value="<?php echo "$badges"; ?>" /> </div> <div class="TabbedPanelsContent"> <input name="badges2" type="text" id="badges2" value="<?php echo $rank; ?>" /> </div> </div> </div> <script type="text/javascript"> var TabbedPanels1 = new Spry.Widget.TabbedPanels("TabbedPanels1"); </script> <?php } ?> i get a message saying i cannot be authorised - i have keys, tokens, passwords, users etc but do not know how to implement them or update this script. any help for a super novice would be great! Code: [Select] <html><head><title>Title</title> <?php if (!isset($_POST['submit'])) { // if page is not submitted to itself //echo the form } else { $username = $_POST["username"]; $password = $_POST["password"]; $image = $_POST["image"]; ////// ////// ////// If you are using file uploads from your form, use the following block ////// NOTE: this particular example code uses file uploads from the input form ////// ////// $filename = $_FILES["image"]['name']; $tmpfilename = $_FILES["image"]['tmp_name']; $fileparts = explode(".", $filename); /* get file extension */ $ext = $fileparts[count($fileparts) - 1]; $newfilename = substr($tmpfilename, 0, strlen($tmpfilename) - strlen($ext)) . "." .$ext; //echo $newfilename; /* * this next line creates a "corrected" file ending in .gif/.png/.jpg so * the post headers are correct when CURL makes the request */ copy($tmpfilename, $newfilename); ////// ////// ////// Else If you are using canned files local to your server, use the following block ////// NOTE: you MUST use full path to image! ////// // // /* windows, notice FORWARD SLASHES */ // $newfilename = "c:/www/path/to/image.jpg"; // // // /* *nix */ // $newfilename = "/www/path/to/image.jpg"; // // The twitter API address $url = 'http://twitter.com/account/update_profile_image.xml'; $curl_handle = curl_init(); curl_setopt($curl_handle, CURLOPT_URL, "$url"); curl_setopt($curl_handle, CURLOPT_POST, 1); curl_setopt($curl_handle, CURLOPT_HTTPHEADER, array('Expect:')); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl_handle, CURLOPT_POSTFIELDS, array("image" => "@$newfilename")); curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password"); $buffer = curl_exec($curl_handle); curl_close($curl_handle); echo $buffer; // if you want to delete the local temp image from uploading, uncomment this next line: // unlink($newfilename); } ?> </head> <body> <form enctype="multipart/form-data" method="post" action="<?php echo $PHP_SELF;?>"> Username:<input type="text" size="12" maxlength="12" name="username"><br /> Password:<input type="password" size="12" maxlength="36" name="password"><br /> <input type="file" name="image"> <input type="submit" value="submit" name="submit"><br /> </form><br /> </body> </html> This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=342583.0 How to generate a unique random number in php??? Any one who can help me? Hi, Newbie! I need to generate a unique number and put it in a field called "intInstD" value ="123456" to send to Paypoint to initiate an order. They insist each order from my website has a unique number. Can anyone help with a bit of code that does this please? Much appreciated zzdave Good morning! I have a two dimensional array, basically a table (see code below). I want to get a value from the array using two methods: 1) Using the row's key: $NewValue = $MyArray[$UniqueKey]; 2) Using the row's index (row number, so to speak): $NewValue = $MyArray[$RowNumber]; The second print statement in the code below does not work. Both print statements should output the same value. Is there an easy way to do this? The table has hundreds of rows and I will not know the key value of row 879 nor can I generate it. So I cannot use array_keys(). And I DO NOT want to start at the first row and count up to the 879th row. Any clever ideas to share and enlighten? Thanks! <?php // Initialize the array keys and values $MyArray = array(); $MyArray['first']['col1'] = 'abc'; $MyArray['first']['col2'] = 'def'; $MyArray['first']['col3'] = 'ghi'; $MyArray['second']['col1'] = 'jkl'; $MyArray['second']['col2'] = 'mno'; $MyArray['second']['col3'] = 'pqr'; $MyArray['third']['col1'] = 'stu'; $MyArray['third']['col2'] = 'vwx'; $MyArray['third']['col3'] = 'yz'; $MyArray['fourth']['col1'] = 'a1a'; $MyArray['fourth']['col2'] = 'b2b'; $MyArray['fourth']['col3'] = 'c3c'; $MyArray['fifth']['col1'] = 'ddd'; $MyArray['fifth']['col2'] = 'eee'; $MyArray['fifth']['col3'] = 'fff'; // Two methods to get a value. Second one does nothing. print"{$MyArray['third']['col2']}</br>"; print"{$MyArray[2]['col2']}</br>"; ?> I am looking to generate a random number for every user contribution as a title of the contribution. I could simply check the database each time with a query and generate a number which does not equal to any of the entries of the database. But I imagine this as inefficient and it could become slow if the database is big in my opinion. Also I'd have to contain all the numbers of the database somewhere to manage the "not equals to", in an array or something similar but that can end up as a giant one. Excuse the layman's speech I am new to this. Any suggestions how this can be solved efficiently without straining the resources too much? You can explain it linguistically and do not have to provide me any scripts, I will figure it out. Hi guys. I am working on an update function which edits users of the admin area of my website. The functions works well to certain extend. I need to make sure that when a user is updated that a repeat username is not used, and display a message that a particular user already exist. I have that functionality in my function, however, this part of the code is not executed and I keep getting the error message: Duplicate entry 'b' for key 'username'. I also need to keep intact any part of the content that's not updated, i.e., password not changed, etc. Here's the code: Code: [Select] function editUser($userUsername, $userPassword, $userEmail, $userRealname, $id){ //select users to see if they exist $query = mysql_query("SELECT * FROM authorized_users WHERE username='$userUsername' ") or die(mysql_error()) ; if (mysql_num_rows($query) >= 1 ) { /* Username already exists */ echo "<p><p><span class='current_admin'>Username already exists</span>"; echo '<p>Please <a href="javascript:history.go(-1)">Go Back</a> and complete the form<br>'; echo '<META HTTP-EQUIV="Refresh" CONTENT="8; URL=users_authorized.php">'; } else { /* Username doesn't exist */ $query = mysql_query("UPDATE authorized_users SET username ='$userUsername', password = '$userPassword', email='$userEmail', realname='$userRealname' ") or die (mysql_error()); echo '<p><p><b> 1 User Added</b>'; echo '<META HTTP-EQUIV="Refresh" CONTENT="4; URL=users_authorized.php">'; } } Thanks in advance for your help. hi all, i have a profile page which is a form that asks users to enter there personal details such as name, location, mobile number etc and saves this info with a mysql database, however when you return to the edit profile page the fields are blank and i want them to pull the details the user has entered (if any) and display it, so if a user entered there name as Lee, then returned to the edit profile page there name field would show lee instead of being empty. heres my profiles page code, any help would be great Code: [Select] <?PHP session_start(); if (!(isset($_SESSION['username']) && $_SESSION['username'] != '')) { header ("Location: login.php"); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Author: Reality Software Website: http://www.realitysoftware.ca Note: This is a free template released under the Creative Commons Attribution 3.0 license, which means you can use it in any way you want provided you keep the link to the author intact. --> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <link href="style.css" rel="stylesheet" type="text/css" /> <style type="text/css"> .auto-style2 { font-size: 25px; } </style> </head> <body> <div id="container"> <!-- header --> <div id="header"> <div id="logo"><a href="#"><span class="orange">SouthWest</span> LAN's</a></div> <div id="menu"> <ul> <li><a href="index.php">home</a></li> <li><a href="register.php">Register</a></li> <li><a href="account.php">My Account</a></li> <li><a href="forum.php">Forums</a></li> <li><a href="faq.php">FAQ</a></li> </ul> </div> </div> <!--end header --> <!-- main --> <div id="main"> <div id="content"> <div id="head_image"> <div id="slogan"><strong><span class="auto-style2">Organising LAN Parties in the SouthWest</span></strong><br /></div> <div id="under_slogan_text"></div> </div> <div id="text"> <h1>Edit Profile</h1> <br /> <form name="register" method="post" action="process_p.php"> <table border="0" width="225" align="center"> <tr> <td width="219" bgcolor="#999999"> <p align="center"><font color="white"><span style="font-size:12pt;">Please fill out as much as possible</span></font></p> </td> </tr> <tr> <td width="219"> <table border="0" width="282" align="center"> <tr> <td width="116"><span style="font-size:10pt;">Username: </span></td> <td width="156"><?php echo $_SESSION['username']; ?></td> </tr> <tr> <td width="116"><span style="font-size:10pt;">Email: </span></td> <td width="156"><input type="text" name="email" maxlength="30"></td> </tr> <tr> <td width="116"><span style="font-size:10pt;">Real Name: </span></td> <td width="156"><input type="text" name="real_name"></td> </tr> <tr> <td width="116"><span style="font-size:10pt;">Location: </span></td> <td width="156"><input type="text" name="location"></td> </tr> <tr> <td width="116"><span style="font-size:10pt;">Mobile Number: </span></td> <td width="156"><input type="text" name="mobile_number"></td> </tr> <tr> <td width="116"><span style="font-size:10pt;">Instant Messager: </span></td> <td width="156"><input type="text" name="instant_messaging"></td> </tr> <tr> <td width="116"> </td> <td width="156"> <p align="right"><input type="submit" name="update" value="Update Profile"></p> </td> </tr> </table> I have a form that passes multiple images and I wanted them to have a substring of a md5 encrypted time for generating unique codes so I don't delete or overwrite an older file. I keep the actual images in a folder and the path in mysql. The folder is working perfectly and there are no problems generating unique codes but I have been trying all night and I can't figure out why mysql won't update. I can actually get it to update but then I loose the functionallity of the code and if I don't upload a 4 images and leave one blank, the blank one deletes the previously uploaded field in the table row. Here is the md5 encrypted time for generating unique codes: Code: [Select] $unique = strtolower(substr(md5(time()), 0, 4)); This is how it works with the folder: Code: [Select] $filePath = $uploadDir . $unique . $fileName; This is how I get it to update mysql but then loose functionality: Code: [Select] $values[$i] = $unique . mysql_real_escape_string(basename(trim($_FILES[$fields[$i]]['name']))); Here is the entire code: Code: [Select] <?php require_once('storescripts/connect.php'); mysql_select_db($database_phpimage,$phpimage); $unique = strtolower(substr(md5(time()), 0, 4)); $uploadDir = 'upload/'; if(isset($_POST['upload' . $config])) { foreach ($_FILES as $file) { $fileName = $file['name']; $tmpName = $file['tmp_name']; $fileSize = $file['size']; $fileType = $file['type']; if($fileName==""){ $filePath = 'upload/'; } else{ $filePath = $uploadDir . $unique . $fileName; } $filePath = str_replace(" ", "_", $filePath); $result = move_uploaded_file($tmpName, $filePath); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); $filePath = addslashes($filePath); } $fileinsert[]=$filePath; } } $mid = mysql_real_escape_string(trim($_POST['mid'])); $cat = mysql_real_escape_string(trim($_POST['cat'])); $item = mysql_real_escape_string(trim($_POST['item'])); $price = mysql_real_escape_string(trim($_POST['price'])); $about = mysql_real_escape_string(trim($_POST['about'])); $fields = array(); $values = array(); $updateVals = array(); for($i=1; $i<=4; $i++) { $fields[$i] = 'name'.$i; $values[$i] = mysql_real_escape_string(basename(trim($_FILES[$fields[$i]]['name']))); if($values[$i] != '') { $updateVals[] = "{$fields[$i]} = '{$values[$i]}'"; } } $updateNames = ''; if(count($updateVals)) { $updateNames = ", " . implode(', ', $updateVals); } $update = "INSERT INTO image (mid, cid, item, price, about, name1, name2, name3, name4) VALUES ('$mid', '$cat', '$item', '$price', '$about', '$values[1]', '$values[2]', '$values[3]', '$values[4]') ON DUPLICATE KEY UPDATE cid = '$cat', item = '$item', price = '$price', about = '$about' $updateNames"; $result = mysql_query($update) or die (mysql_error()); $id = mysql_insert_id(); ?> <p style="font-size:35px; font-family:Arial, Helvetica, sans-serif; color:#255E67; margin-left:25px;">Your Item Has Been Uploaded!</p> <script type="text/javascript"> setTimeout('ourRedirect()', 2000) function ourRedirect() { location.href='protator_php.php?mid=<?php echo $id ?>' } </script> |