PHP - Change Insert Script To Modify/update Script
Hi i have this upload script which works fine it uploads image to a specified folder and sends the the details to the database.
but now i am trying to instead make a modify script which is Update set so i tried to change insert to update but didnt work can someone help me out please this my insert image script which works fine but want to change to modify instead Code: [Select] <?php mysql_connect("localhost", "root", "") or die(mysql_error()) ; mysql_select_db("upload") or die(mysql_error()) ; // my file the name of the input area on the form type is the extension of the file //echo $_FILES["myfile"]["type"]; //myfile is the name of the input area on the form $name = $_FILES["image"] ["name"]; // name of the file $type = $_FILES["image"]["type"]; //type of the file $size = $_FILES["image"]["size"]; //the size of the file $temp = $_FILES["image"]["tmp_name"];//temporary file location when click upload it temporary stores on the computer and gives it a temporary name $error =array(); // this an empty array where you can then call on all of the error messages $allowed_exts = array('jpg', 'jpeg', 'png', 'gif'); // array with the following extension name values $image_type = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif'); // array with the following image type values $location = 'images/'; //location of the file or directory where the file will be stored $appendic_name = "news".$name;//this append the word [news] before the name so the image would be news[nameofimage].gif // substr counts the number of carachters and then you the specify how how many you letters you want to cut off from the beginning of the word example drivers.jpg it would cut off dri, and would display vers.jpg //echo $extension = substr($name, 3); //using both substr and strpos, strpos it will delete anything before the dot in this case it finds the dot on the $name file deletes and + 1 says read after the last letter you delete because you want to display the letters after the dot. if remove the +1 it will display .gif which what we want is just gif $extension = strtolower(substr($name, strpos ($name, '.') +1));//strlower turn the extension non capital in case extension is capital example JPG will strtolower will make jpg // another way of doing is with explode // $image_ext strtolower(end(explode('.',$name))); will explode from where you want in this case from the dot adn end will display from the end after the explode $myfile = $_POST["myfile"]; if (isset($image)) // if you choose a file name do the if bellow { // if extension is not equal to any of the variables in the array $allowed_exts error appears if(in_array($extension, $allowed_exts) === false ) { $error[] = 'Extension not allowed! gif, jpg, jpeg, png only<br />'; // if no errror read next if line } // if file type is not equal to any of the variables in array $image_type error appears if(in_array($type, $image_type) === false) { $error[] = 'Type of file not allowed! only images allowed<br />'; } // if file bigger than the number bellow error message if($size > 2097152) { $error[] = 'File size must be under 2MB!'; } // check if folder exist in the server if(!file_exists ($location)) { $error[] = 'No directory ' . $location. ' on the server Please create a folder ' .$location; } } // if no error found do the move upload function if (empty($error)){ if (move_uploaded_file($temp, $location .$appendic_name)) { // insert data into database first are the field name teh values are the variables you want to insert into those fields appendic is the new name of the image mysql_query("INSERT INTO image (myfile ,image) VALUES ('$myfile', '$appendic_name')") ; exit(); } } else { foreach ($error as $error) { echo $error; } } //echo $type; ?> Similar TutorialsI have a php script that I've been running that seems to have been working but now I'm wondering if some of my logic is potentially off. I select records from a db table within a date range which I put into an array called ```$validCount``` If that array is not empty, that means I have valid records to update with my values, and if it's empty I just insert. The trick with the insert is that if the ```STORES``` is less than the ```Quantity``` then it only inserts as many as the ```STORES``` otherwise it inserts as many as ```Quantity```. So if a record being inserted with had Stores: 14 Quantity:12
Then it would only insert 12 records but if it had It would only insert 1 record. In short, for each customer I should only ever have as many valid records (within a valid date range) as they have stores. If they have 20 stores, I can have 1 or 2 records but should never have 30. It seems like updating works fine but I'm not sure if it's updating the proper records, though it seems like in some instances it's just inserting too many and not accounting for past updated records. This is the logic I have been working with:
if(!empty($validCount)){ for($i=0; $i<$row2['QUANTITY']; $i++){ try{ $updateRslt = $update->execute($updateParams); }catch(PDOException $ex){ $out[] = $failedUpdate; } } }else{ if($row2["QUANTITY"] >= $row2["STORES"]){ for($i=0; $i<$row2["STORES"]; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $out[] = $failedInsertStore; } } }elseif($row2["QUANTITY"] < $row2["STORES"]){ for($i=0; $i<$row2["QUANTITY"]; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $out[] = $failedInsertQuantity; } } } }
Let's say customer 123 bought 4 of product A and they have 10 locations
customerNumber | product | category | startDate | expireDate | stores Because they purchased less than their store count, I insert 4 records. Now if my ```$validCheck``` query selects all 4 of those records (since they fall in a valid date range) and my loop sees that the array isn't empty, it knows it needs to update those or insert. Let's say they bought 15 this time. Then I would need to insert 6 records, and then update the expiration date of the other 9 records.
customerNumber | product | category | startDate | expireDate | stores There can only ever be a maximum of 10 (store count) records for that customer and product within the valid date range. As soon as the row count for that customer/product reaches the equivalent of stores, it needs to now go through and update equal to the quantity so now I'm running this but it's not running and no errors, but it just returns back to the command line $total = $row2['QUANTITY'] + $validCheck; if ($total < $row2['STORES']) { $insert_count = $row2['QUANTITY']; $update_count = 0; } else { $insert_count = $row2['STORES'] - $validCheck; // insert enough to fill all stores $update_count = ($total - $insert_count); // update remainder } for($i=0; $i<$row2['QUANTITY']; $i++){ try{ $updateRslt = $update->execute($updateParams); }catch(PDOException $ex){ $failedUpdate = "UPDATE_FAILED"; print_r($failedUpdate); $out[] = $failedUpdate; } } for($i=0; $i<$insert_count; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $failedInsertStore = "INSERT_STORE_FAILED!!!: " . $ex->getMessage(); print_r($failedInsertStore); $out[] = $failedInsertStore; } }```
Hello: Can someone give me some insight on how to be able to not just add (INSERT) a photo and photo description with the following code, but also how to add the ability to UPDATE (if the user wants to replace a photo or adjust the photo description): Code: [Select] <?php include("config.inc.php"); // initialization $result_final = ""; $counter = 0; // List of our known photo types $known_photo_types = array( 'image/pjpeg' => 'jpg', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/bmp' => 'bmp', 'image/x-png' => 'png' ); // GD Function List $gd_function_suffix = array( 'image/pjpeg' => 'JPEG', 'image/jpeg' => 'JPEG', 'image/gif' => 'GIF', 'image/bmp' => 'WBMP', 'image/x-png' => 'PNG' ); // Fetch the photo array sent by preupload.php $photos_uploaded = $_FILES['photo_filename']; // Fetch the photo caption array $photo_caption = $_POST['photo_caption']; while( $counter <= count($photos_uploaded) ) { if($photos_uploaded['size'][$counter] > 0) { if(!array_key_exists($photos_uploaded['type'][$counter], $known_photo_types)) { $result_final .= "File ".($counter+1)." is not a photo<br />"; } else { mysql_query( "INSERT INTO gallery_photos(`photo_filename`, `photo_caption`, `photo_category`) VALUES('0', '".addslashes($photo_caption[$counter])."', '".addslashes($_POST['category'])."')" ); $new_id = mysql_insert_id(); $filetype = $photos_uploaded['type'][$counter]; $extention = $known_photo_types[$filetype]; $filename = $new_id.".".$extention; mysql_query( "UPDATE gallery_photos SET photo_filename='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" ); // Store the orignal file copy($photos_uploaded['tmp_name'][$counter], $images_dir."/".$filename); // Let's get the Thumbnail size $size = GetImageSize( $images_dir."/".$filename ); if($size[0] > $size[1]) { $thumbnail_width = 100; $thumbnail_height = (int)(100 * $size[1] / $size[0]); } else { $thumbnail_width = (int)(100 * $size[0] / $size[1]); $thumbnail_height = 100; } // Build Thumbnail with GD 1.x.x, you can use the other described methods too $function_suffix = $gd_function_suffix[$filetype]; $function_to_read = "ImageCreateFrom".$function_suffix; $function_to_write = "Image".$function_suffix; // Read the source file $source_handle = $function_to_read ( $images_dir."/".$filename ); if($source_handle) { // Let's create an blank image for the thumbnail $destination_handle = ImageCreate ( $thumbnail_width, $thumbnail_height ); // Now we resize it ImageCopyResized( $destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $size[0], $size[1] ); } // Let's save the thumbnail $function_to_write( $destination_handle, $images_dir."/tb_".$filename ); ImageDestroy($destination_handle ); // $result_final .= "<img src='".$images_dir. "/tb_".$filename."' /> File ".($counter+1)." Added<br />"; } } $counter++; } // Print Result echo <<<__HTML_END <html> <head> <title>Photos uploaded</title> </head> <body> $result_final </body> </html> __HTML_END; ?> The tutorial says to edit a photo, simply add: Code: [Select] function edit_photo( $photo_id, $new_caption, $new_category ) <br> { <br> mysql_query( "UPDATE gallery_photo SET photo_caption='".addslashes( $new_caption )."', photo_category='".addslashes( $new_category )."' WHERE photo_id='".addslashes( $photo_id )."'" ); <br> } But I can not figure out how to call that function. Anyone help me out? Thanks. For right or wrong, I've been using XML to define my Doctrine entities. When the XML changes, my entities need to change. I've automated the process with a simple PHP script which allows me to swap some text to modify one of the auto-generated methods, add methods, etc. Kind of clunky but it works well enough. Now, I recently had the need to remove a given method in its entirety from a given class. I "could" just add the entire string which represents the method name, earlier comments, and script for the method to my parsing script to my parsing script and remove it, but would like to be a little more concise. For instance, say I have $script as follows: $script = <<<'EOT' class SomeEntityClass { //... more stuff above public function getSomething() { return $this->something; } /** * Get foos. * * @return \Doctrine\Common\Collections\Collection */ public function getFoos() { return $this->foos; } /** * Get somethingElse. * */ //... more stuff below } EOT; How would you recommend creating the function: removeFunction($script, 'getFoos') which would remove the given function along with its comments from the $script string and result with? $script = <<<'EOT' class SomeEntityClass { //... more stuff above public function getSomething() { return $this->something; } /** * Get somethingElse. * */ //... more stuff below } EOT; Assuming regex is the way to go, I was thinking of something like the following, but could use some help with the regex expression. function removeFunction($script, $method) { $method="public function $method("; //regex to remove script with which starts after pattern "{\n" OR "**/", contains $method, and is located before pattern "\n{" OR "\n /**" return $script; } Thanks This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=310049.0 This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=334372.0 i have this awesome script i've used on multiple websites and only now is it giving me trouble. it's always aligned/cropped to the middle of the image but for some reason the smaller thumbnails are cropping to the bottom. Code: [Select] <?php header ("Content-type: image/jpeg"); $file_name=$_GET['f']; $crop_height=$_GET['h']; $crop_width=$_GET['w']; $file_type= explode('.', $file_name); $file_type = $file_type[count($file_type) -1]; $file_type=strtolower($file_type); $original_image_size = getimagesize($file_name); $original_width = $original_image_size[0]; $original_height = $original_image_size[0]; if($file_type=='jpg') { $original_image_gd = imagecreatefromjpeg($file_name); } if($file_type=='gif') { $original_image_gd = imagecreatefromgif($file_name); } if($file_type=='png') { $original_image_gd = imagecreatefrompng($file_name); } $cropped_image_gd = imagecreatetruecolor($crop_width, $crop_height); $wm = $original_width /$crop_width; $hm = $original_height /$crop_height; $h_height = $crop_height/2; $w_height = $crop_width/2; if($original_width > $original_height ) { $adjusted_width =$original_width / $hm; $half_width = $adjusted_width / 2; $int_width = $half_width - $w_height; imagecopyresampled($cropped_image_gd ,$original_image_gd ,-$int_width,0,0,0, $adjusted_width, $crop_height, $original_width , $original_height ); } elseif(($original_width < $original_height ) || ($original_width == $original_height )) { $adjusted_height = $original_height / $wm; $half_height = $adjusted_height / 2; $int_height = $half_height - $h_height; imagecopyresampled($cropped_image_gd , $original_image_gd ,0,-$int_height,0,0, $crop_width, $adjusted_height, $original_width , $original_height ); } else { imagecopyresampled($cropped_image_gd , $original_image_gd ,0,0,0,0, $crop_width, $crop_height, $original_width , $original_height ); } imagejpeg($cropped_image_gd); ?> if i modify the value of original_image_size, it crops to the middle, but if the height is greater than the width it will add black on either side of the image to fill out the designated value. Code: [Select] $original_image_size = getimagesize($file_name); $original_width = $original_image_size[0]; $original_height = $original_image_size[1]; i can't figure out how to get it do both. 0, 0 outputs this: http://www.loudtechinc.com/images/scriptissue/00.png http://www.loudtechinc.com/images/scriptissue/00n2.png 0, 1 outputs this: http://www.loudtechinc.com/images/scriptissue/01.png http://www.loudtechinc.com/images/scriptissue/01n2.png The end goal is to have it fill the desired height and width while cropping to the middle. Well the subject line is pretty explicit. I found this script that uploads a picture onto a folder on the server called images, then inserts the the path of the image on the images folder onto a VACHAR field in a database table. Code: [Select] <?php //This file inserts the main image into the images table. //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user //Start session session_start(); //Connect to database require ('config.php'); //Check whether the session variable id is present or not. If not, deny access. if(!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) { header("location: access_denied.php"); exit(); } else{ // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif"); if (in_array($file['type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that's easy to read // I used this function during debugging but it serves no purpose at run time for this example function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } // Set some constants // This variable is the path to the image folder where all the images are going to be stored // Note that there is a trailing forward slash $TARGET_PATH = "images/"; // Get our POSTed variable $image = $_FILES['image']; // Sanitize our input $image['name'] = mysql_real_escape_string($image['name']); // Build our target path full string. This is where the file will be moved to // i.e. images/picture.jpg $TARGET_PATH .= $image['name']; // Make sure all the fields from the form have inputs if ( $image['name'] == "" ) { $_SESSION['error'] = "All fields are required"; header("Location: member.php"); exit; } // Check to make sure that our file is actually an image // You check the file type instead of the extension because the extension can easily be faked if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, or bmp"; header("Location: member.php"); exit; } // Here we check to see if a file with that name already exists // You could get past filename problems by appending a timestamp to the filename and then continuing if (file_exists($TARGET_PATH)) { $_SESSION['error'] = "A file with that name already exists"; header("Location: member.php"); exit; } // Lets attempt to move the file from its temporary directory to its new home if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "insert into images (member_id, image_cartegory, image_date, image) values ('{$_SESSION['id']}', 'main', NOW(), '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: images.php"); echo "File uploaded"; exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod the directory to be writeable $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; header("Location: member.php"); exit; } } //End of if session variable id is not present. ?> The script seems to work fine because I managed to upload a picture which was successfully inserted into my images folder and into the database. Now the problem is, I can't figure out exactly how to write the script that displays the image on an html page. I used the following script which didn't work. Code: [Select] //authenticate user //Start session session_start(); //Connect to database require ('config.php'); $sql = mysql_query("SELECT* FROM images WHERE member_id = '".$_SESSION['id']."' AND image_cartegory = 'main' "); $row = mysql_fetch_assoc($sql); $imagebytes = $row['image']; header("Content-type: image/jpeg"); print $imagebytes; Seems to me like I need to alter some variables to match the variables used in the insert script, just can't figure out which. Can anyone help?? Good morning. I am looking fo some help with an update script to update all rows in a table. This is what I have for a form and all looks well. form.php <?php // run the query and put the results in an array variable called $result $result = mysql_query("SELECT * FROM table ORDER BY 'id', 'title', 'text', 'number'"); print "<form method='post' action='update.php'> <table width='100%' border='0' cellspacing='1' cellpadding='1'><tr> <td align='center'><strong>ID</strong></td> <td align='center'><strong>Title</strong></td> <td align='center'><strong>text</strong></td> <td align='center'><strong>Number</strong></td> </tr>\n"; // start a loop to print all of the courses with their book information // the mysql_fetch_array function puts each record into an array. each time it is called, it moves the array counter up until there are no more records left while ($Update = mysql_fetch_array($result)) { // start displaying the info; the most important part is to make the name an array (notice bookinfo[$i]) print "<td align='center'><p>{$Update['id']}</p></td>\n"; print "<td align='center'><input type='text' name='title' value='{$Update['title']}' /></td>"; print "<td align='center'><input type='text' size='40' name='text' value='{$Update['text']}' /></td>\n"; print "<td align='center'><input type='text' size='40' name='number' value='{$Update['number']}' /></td>\n"; print "</tr>\n"; // add 1 to the count, close the loop, close the form, and the mysql connection } print "<tr> <td colspan='4' align='center'><input type='submit' value='submit' />"; print "</td> </tr> </table> </td> </tr> </form> </table>"; print "</tr>\n"; ?><br /><br /> My question is. How do I update this info into the database with the proper info. ie. Update.php? I'm new to PHP/MySQL and have been searching high and low for a solution to this... When using my PHP script to insert a row into the database it errors out but does not give me a specific error. When I use the MySQL command line client I can insert the first, second, third, or any number of rows without a problem. What I don't understand is, once I have inserted a row using the command line client, my PHP script will insert rows without issue. So my question is, what is it about the first row being inserted that makes it so special? One of the columns in the table is an AUTO_INCREMENT field, so i'm guessing that has something to do with it? I've used this on like three other scripts I don't know why it won't insert now <?php date_default_timezone_set('America/Los_Angeles'); $timestamp = date('H:m:s m.d'); $admin = '24.68.214.97'; $visitor_ip = $_SERVER['REMOTE_ADDR']; $host="mysql"; // Host name $username="15557_test"; // Mysql username $password="**********"; // Mysql password $db_name="15557_test"; // Database name $tbl="announce"; // Table name mysql_connect("$host", "$username", "$password")or die("cannot connect to server"); mysql_select_db("$db_name")or die("cannot select DB"); $body = $_POST["body"]; if ($visitor_ip == $admin) { mysql_query("INSERT INTO $tbl (body, date) VALUES ('$body', '$timestamp')"); //right here, i can echo $body and see what I wrote, but I can't insert into $tbl } else { die("no"); } ?> <meta http-equiv="REFRESH" content="0;url=http://testchan.dcfilms.org/board-b.php"> Hi
i've got a script to migrate some tables.
This is most of it.. just missing the db connection (not needed here)
$link = mysql_connect($host,$user,$pass) or die(mysql_error()); mysql_selectdb($db,$link) or die(mysql_error()); $ag_forums_to_kunena_categories = array(); mysql_query("TRUNCATE bzhv8_kunena_messages"); mysql_query("TRUNCATE bzhv8_kunena_messages_text"); $sql = " SELECT p.id AS messages_id, u.name AS messages_name, a.jos_id AS messages_userid, p.message AS messages_text_message, p.posted AS messages_time, p.edited AS messages_modified_time, p.edited_by AS messages_modified_by, p.topic_id AS messages_thread, t.forum_id AS messages_catid FROM jos_agora_posts AS p LEFT JOIN jos_agora_users AS a ON a.username = p.poster LEFT JOIN jos_agora_topics AS t ON t.id = p.topic_id LEFT JOIN bzhv8_users AS u ON u.id = a.jos_id ORDER BY p.id ASC "; $res = mysql_query($sql) or die(mysql_error()); while ($row = mysql_fetch_object($res)) { echo $row->messages_id; //echo "<br />"; //echo $row->messages_name; //echo "<br />"; //echo $row->messages_userid; //echo "<br />"; //echo $row->messages_text_message; //echo "<br />"; //echo $row->messages_time; //echo "<br />"; //echo $row->messages_modified_time; //echo "<br />"; //echo $row->messages_modified_by; //echo "<br />"; //echo $row->messages_thread; //echo "<br />"; //echo $row->messages_catid; //echo "<br />"; //if($row->messages_userid == '') //echo "userid er nul"; //{ // $row->messages_userid = 0; //} $cat_id = $ag_forums_to_kunena_categories[$row->messages_catid]; if ($cat_id != 0) { echo $cat_id; echo "kategori id"; echo "<br />"; echo "lige før den skal indsætte"; $sql = "INSERT INTO `bzhv8_kunena_messages` VALUES (".$row->messages_id.", 0, ".$row->messages_thread.", ".$cat_id.", '".$row->messages_name."', ".$row->messages_userid.", '', '', ".$row->messages_time.", NULL, 0, 0, 0, 0, 0, 0, 0, 0, '')"; echo "her bør den køre sql(1)"; $sql2 = "INSERT INTO `bzhv8_kunena_messages_text` VALUES (".$row->messages_id.", '".mysql_escape_string($row->messages_text_message)."')"; echo $sql; echo "lige efter anden insert echo sql"; echo "<br />"; echo $sql2; echo "<br />"; echo "her skulle den vise anden insert"; mysql_query($sql) or die(mysql_error()); mysql_query($sql2) or die(mysql_error()); } else { } } mysql_close();But something is not working.. first.. ignore the echo's of course.. just me trying to debug.. same with the else statement... from what I can tell.. and my php knowledge is non-existant.. this part: $cat_id = $ag_forums_to_kunena_categories[$row->messages_catid]; it what's causing the problem.. it appears that the $cat_id is not getting any data.. if copy the sql line and run it against my database via phpmyadmin then it works as it should.. but well.. something isn't right.. there are some other stuff in the script that does the same as the above.. but with different tables and they work just fine.. example: mysql_query("TRUNCATE bzhv8_kunena_topics"); $sql = " SELECT t.id AS topic_id, t.poster AS topic_poster, t.subject AS topic_subject, t.posted AS topic_first_post_time, t.last_post AS topic_last_post_time, t.last_post_id AS topic_last_post_id, t.last_poster AS topic_last_poster, t.num_views AS topic_hits, t.num_replies AS topic_posts, t.closed AS topic_locked, t.sticky AS topic_hold, t.moved_to AS topic_moved_id, t.forum_id AS topic_category_id, t.question AS topic_poll_id, p.id AS topic_first_post_id, p.posted AS topic_first_post_time, a.jos_id AS topic_first_post_userid, p.message AS topic_first_post_message FROM jos_agora_topics AS t LEFT JOIN jos_agora_users AS a ON a.username = t.poster LEFT JOIN jos_agora_posts AS p ON t.posted = p.posted ORDER BY t.id ASC "; $res = mysql_query($sql) or die(mysql_error()); while ($row = mysql_fetch_object($res)) { echo $row->topic_id; echo "<br />"; if($row->topic_first_post_userid == '') { $row->topic_first_post_userid = 0; } $cat_id = $ag_forums_to_kunena_categories[$row->topic_category_id]; echo $cat_id; echo "<br />"; $sql = "INSERT INTO `bzhv8_kunena_topics` VALUES (".$row->topic_id.", ".$cat_id.", '".mysql_escape_string($row->topic_subject)."', 0, ".$row->topic_locked.", ".$row->topic_hold.", 0, ".$row->topic_posts.", ".$row->topic_hits.", 0, 0, 0, ".$row->topic_first_post_id.", ".$row->topic_first_post_time.", ".$row->topic_first_post_userid.", '".mysql_escape_string($row->topic_first_post_message)."', NULL, ".$row->topic_last_post_id.", ".$row->topic_last_post_time.", 0, NULL, NULL, '')"; echo $sql; echo "<br />"; mysql_query($sql) or die(mysql_error()); }the above works fine.. Can someone take a look and give a hint or 2.. or just point at whatever the solution is :-) I plan to be releasing some scripts and will update the version of the script on my website. Users will be able to download the script and run it on there website. The latest version will be checked by checking my website and compared with the version of the user's script to see if its out of date. I can't get it to work correctly. On http://www.phpfusionmods.com/updates/check.php I have the latest version set to 1.4. In the script the version is set at 1.3 so its obviously out of date. However, its showing that its up to date. Please offer your support. My script is below. <?php $version = "1.3"; function new_version() { $url = "http://www.phpfusionmods.com/updates/check.php"; $url_p = @parse_url($url); $host = $url_p['host']; $port = isset($url_p['port']) ? $url_p['port'] : 80; $fp = @fsockopen($url_p['host'], $port, $errno, $errstr, 5); if (!$fp) return false; @fputs($fp, 'GET ' . $url_p['path'] . ' HTTP/1.1' . chr(10)); @fputs($fp, 'HOST: ' . $url_p['host'] . chr(10)); @fputs($fp, 'Connection: close' . chr(10) . chr(10)); $response = @fgets($fp, 1024); $content = @fread($fp, 1024); $content = preg_replace("#(.*?)text/plain(.*?)$#is", "$2", $content); @fclose($fp); if (preg_match("#404#", $response)) return "Timeout"; else return trim(str_replace("X-Pad: avoid browser bug", "", $content)); } $newversion = str_replace("X-Pad: avoid browser bug", "", new_version()); $new_version = $newversion != "Timeout" && intval(str_replace(".", "", $newversion)) > intval(str_replace(".", "", $version)) ? true : false; if ($new_version) { echo "Download the latest version <a href='http://www.phpfusionmods.com/' target='_blank'>here</a>. <b>v" . str_replace("X-Pad: avoid browser bug", "", $newversion) . "</b>"; } elseif ($newversion == "Timeout") { echo "PHPFusionMods.com has timed out. Check for updates <a href='http://www.phpfusionmods.com/' target='_blank'>here</a>."; } else { echo ("You have the latest version"); } ?> Please could some1 just point out why this php code is not updating the my-sql db? It displays the content of the db but does not update accordingly.. Code: [Select] <?php include("cn.php"); //$username=$_GET['username']; if (!@$_SESSION['username']){ header("location:Not_Logged.php"); } if (isset($_POST['update'])) { $update=$_GET['update'];} else {$update=0;} if ($update = "1") { $username=$_GET['username']; $id=$_GET['id']; $username=$_POST['username']; $password=$_POST['password']; $select="select * from users where username='$_SESSION[username]'"; $rs_cat=mysqli_query($con,$select); $row=mysqli_fetch_array($rs_cat); $username=$row['username']; $password=$row['password']; $update="UPDATE users SET username='$username', password='$password' where id='$id'"; $ur=mysqli_query($con,$update) or die (mysql_error()); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>UPDATE</title> </head> <body> <?php //echo $_SESSION['username'];?> <table align="center" > <form name="login" action="" method="post"/> <tr> <td> <th scope="col"><strong>UPDATE</strong></th> </td> </tr> <tr> <td> USERNAME <th scope="col"><input name="username" type="text" value="<?php echo ("$row[username]");?>"/></th> </td> </tr> <tr> <td> PASSWORD <th scope="col"><input name="password" type="password" value="<?php echo ("$row[password]");?>" /></th> </td> </tr> <tr> <td> <th scope="col"><input name="update" type="submit" value="UPDATE" /></th> </td> </tr> <tr> <td> <th scope="col"><input name="id" type="hidden" value="<?php echo $row[id];?>" /></th> </td> </form> </table> </body> </html> Any sharp locator would be appreciated... Having trouble with this upload script, it grabs and displays the content from the database fine. It won't however update the database although the code is throwing up no errors; this is the script that displays the content Code: [Select] ############### Code <?php include("includes/connection.php"); $sql="SELECT * FROM mot"; $result=mysql_query($sql); ?> <table width="400" border="0" cellspacing="1" cellpadding="0"> <tr> <td> <table width="400" border="1" cellspacing="0" cellpadding="3"> <tr> <td colspan="4"><strong>List data from mysql </strong> </td> </tr> <tr> <td align="center"><strong>Name</strong></td> <td align="center"><strong>Lastname</strong></td> <td align="center"><strong>Update</strong></td> </tr> <?php while($rows=mysql_fetch_array($result)){ ?> <tr> <td><? echo $rows['header']; ?></td> <td><? echo $rows['content']; ?></td> // link to update.php and send value of id <td align="center"><a href="update_content.php?id=<? echo $rows['id']; ?>">update</a></td> </tr> <?php } ?> </table> </td> </tr> </table> this next bit of code is the code that user updates the content; Code: [Select] <?php include("includes/connection.php"); $id=$_GET['id']; $sql="SELECT * FROM mot WHERE id='$id'"; $result=mysql_query($sql); $rows=mysql_fetch_array($result); ?> <table width="400" border="0" cellspacing="1" cellpadding="0"> <tr> <form name="form1" method="post" action="update_ac.php"> <td> <table width="100%" border="0" cellspacing="1" cellpadding="0"> <tr> <td> </td> <td colspan="3"><strong>Update data in mysql</strong> </td> </tr> <tr> <td align="center"> </td> <td align="center"> </td> <td align="center"> </td> <td align="center"> </td> </tr> <tr> <td align="center"> </td> <td align="center"><strong>Name</strong></td> <td align="center"><strong>Lastname</strong></td> </tr> <tr> <td> </td> <td align="center"><input name="name" type="text" id="name" value="<? echo $rows['header']; ?>"></td> <td align="center"><input name="lastname" type="text" id="lastname" value="<? echo $rows['content']; ?>" size="15"></td> </tr> <tr> <td> </td> <td><input name="id" type="hidden" id="id" value="<? echo $rows['id']; ?>"></td> <td align="center"><input type="submit" name="Submit" value="Submit"></td> <td> </td> </tr> </table> </td> </form> </tr> </table> this final bit is the update code for the database which isnt working but not throwing up any errors Code: [Select] <?php include("includes/connection.php"); if(isset($_POST['update'])){ $id = $_GET['id']; $header = $_POST['header']; $content = $_POST['content']; $sql="UPDATE mot SET header = '$header', content = '$content' WHERE id='$id'"; $result=mysql_query($sql); if($result){ echo "Successful"; echo "<BR>"; echo "<a href='mot_edit.php'> View result</a>"; } else { echo "ERROR"; } } ?> Any help would be much appreciated i have got this script which displays all folders within a folder but what i want to do now is get it to display a random picture for each of the folders that it is showing in the grid. i know how to display a random image using array_rand() but i don't know how i would implement it. Code: [Select] <form name="Gallery" method="post"> <?php $path = "gallery_files/gallery/"; $dir_handle = @opendir($path) or die("Unable to open folder"); echo "<table cellspacing='15'>"; echo "<tr>"; while (false !== ($folder = readdir($dir_handle))) { if($folder == "pictures.php") continue; if($folder == ".") continue; if($folder == "..") continue; echo ($x % 6 == 0) ? "</tr><tr>" : ""; echo "<td><a href='pictures/?folder=$folder'><img src='path/to/random/image' style='height:auto;width:110px;' alt='$folder'></a><br /><a href='pictures/?folder=$folder'>$folder</a></td>"; $x++; } echo "</tr>"; echo "</table>"; closedir($dir_handle); ?> </form> Hello, I'm trying to write my first database using SQL and PHP, without much luck, I'm afraid. After inserting a new record (for which I didn't have a problem), I wanted to automatically generate a username which is the person's first name (they'll then be able to change it later). Trying to use Dreamweaver as a model, I've come up with this: $updateSQL = sprintf("UPDATE users SET username=%s", GetSQLValueString($_POST['first_name'], "text")) Well...it does update the username, but it does so on ALL of the records as opposed to the one that was just inserted. Any help would be appreciated... Thank you. I have a script to let the user update their password, when I submit it i get a 500 error and I'm not sure. Here is the code: If (isset($_POST['update-password'])) { //This makes sure they did not leave any fields blank if (!$_POST['oldpw'] || !$_POST['pass'] || !$_POST['pass2'] ) { $error="<span style="; $error .="color:red"; $error .=">"; $error .= "You did not complete all of the required fields"; $error .="</span>"; setcookie('Errors', $error, time()+20); header('Location /useredit.php'); exit; } // checks if the password is correct $pass = md5($_POST['pass']); if (!get_magic_quotes_gpc()) { $pass = addslashes($pass); } $check = mysql_real_escape_string("SELECT * FROM YBK_Login WHERE pass = '{$pass}'"); mysql_query($check) or die( 'Query string: ' . $check . '<br />Produced an error: ' . mysql_error() . '<br />' ); // this makes sure both passwords entered match if ($_POST['pass'] != $_POST['pass2']) { $error="<span style="; $error .="color:red"; $error .=">"; $error .= 'Your passwords did not match.'; $error .="</span>"; setcookie('Errors', $error, time()+20); header('Location: /useredit.php'); exit; } // here we encrypt the password and add slashes if needed $_POST['pass'] = md5($_POST['pass']); if (!get_magic_quotes_gpc()) { $_POST['pass'] = addslashes($_POST['pass']); $_POST['pass2'] = addslashes($_POST['pass2']); } // now we insert it into the database mysql_real_escape_string($insert = "UPDATE `YBK_Login` SET `pass` = '{$_POST['pass']}', `HR` = '{$_POST['pass2']}', `comment` = '{$_POST['oldpw']}' WHERE `ID` = {$_COOKIE['UID_WatsonN']}"); mysql_query($insert) or die( 'Query string: ' . $insert . '<br />Produced an error: ' . mysql_error() . '<br />' ); $error="<span style="; $error .="color:green"; $error .=">"; $error .= "<p>Thank you, your password has been updated.</p>"; $error .="</span>"; setcookie('Errors', $error, time()+20); header('Location: /useredit.php'); exit; } I am attempting to update selected records using '$row[' elements in where clauses. I recieve message 'Record Updated but when I check data base it hasn't changed. CODE: $query = "SELECT cr_num, cr_ci_num, cr_dte, cr_flag, ci_desc, ci_authority, ce_name, ce_email, ce_phone_ext FROM c_record, c_info, c_employee WHERE cr_num = ce_num AND cr_ci_num = ci_num AND cr_dte > '{$dte60}' and cr_dte <= '{$dte90}' AND cr_flag = '00'"; $result = mysqli_query($dbc, $query) or die('ERROR querying database'); while($row = mysqli_fetch_array($result)) { $query = "UPDATE c_record SET cr_flag = '90' WHERE cr_num = '{$row[cr_num]}' AND cr_ci_num = '{$row[cr_ci_num]}'" or die('ERROR UPDATE'); echo 'Update succesfull'; echo "<br />\n" OK I have no idea why this will not update the table but here is the code I wrote. I just can't see it Code: [Select] <?php //CONNECT TO DATABASE include("sharons_dbinfo.inc.php"); mysql_connect(localhost,$user,$password); mysql_select_db($database) or die( "Unable to select database"); //OPEN THE ZIP FILE $handle = gzopen('Newegg_com-Daily_Deals_Feed.txt.gz', 'r'); //READ THE WHOLE FILE LINE BY LINE while (!gzeof($handle)) { $buffer = gzgets($handle, 4096); $buffer = str_replace("'" , "" , $buffer); $buffer = str_replace("\"" , "" , $buffer); $data = explode(",", $buffer); //SKIP THE FIRST LINE OF COLUMN NAMES if ($data[4] == "NAME"){} else{ //PUT THIS IN TO MAKE SURE IT WAS LOOKING FOR THE RIGHT RECORD print "Looking for: ". $data['4'] . " to update with new date " . $data['3']."<br>"; $item_name = $data['4']; //QUERY THE TABLE FOR PRODUCT NAME FROM ZIP FILE $query = ("SELECT * FROM `computer_memory` WHERE `NAME` = '$item_name'"); $results = mysql_query($query) or die(mysql_error()."<br /><br />".$query); $result = mysql_fetch_array($results); $num=mysql_numrows($results); //IF THE NAME EXISTS PROCEED TO UPDATE THE RECORD WITH THE NEW INFORMATION if ($num >0) { //UPDATE TABLE WITH THE NEW INFORMATION $update = ("UPDATE `computer_memory` SET `PROGRAMNAME`= '$data[0]', `PROGRAMURL`= '$data[1]', `CATALOGNAME`= '$data[2]', `LASTUPDATED`= '$data[3]', `NAME`= '$data[4]', `KEYWORDS`= '$data[5]', `DESCRIPTION`= '$data[6]', `SKU`= '$data[7]', `MANUFACTURER`= '$data[8]', `MANUFACTURERID`= '$data[9]', `UPC`= '$data[10]', `ISBN`= '$data[11]', `CURRENCY`= '$data[12]', `SALEPRICE`= '$data[13]', `PRICE`= '$data[14]', `RETAILPRICE`= '$data[15]', `FROMPRICE`= '$data[16]', `BUYURL`= '$data[17]', `IMPRESSIONURL`= '$data[18]', `IMAGEURL`= '$data[19]', `ADVERTISERCATEGORY`= '$data[20]', `THIRDPARTYID`= '$data[21]', `THIRDPARTYCATEGORY`= '$data[22]', `AUTHOR`= '$data[23]', `ARTIST`= '$data[24]', `TITLE`= '$data[25]', `PUBLISHER`= '$data[26]', `LABEL`= '$data[27]', `FORMAT`= '$data[28]', `SPECIAL`= '$data[29]', `GIFT`= '$data[30]', `PROMOTIONALTEXT`= '$data[31]', `STARTDATE`= '$data[32]', `ENDDATE`= '$data[33]', `OFFLINE`= '$data[34]', `ONLINE`= '$data[35]', `INSTOCK`= '$data[36]', `CONDITION`= '$data[37]', `WARRANTY`= '$data[38]', `STANDARDSHIPPINGCOST`= '$data[39]' WHERE `ID`= '$id'"); mysql_query($update) or die(mysql_error()."<br /><br />".$update); //if ($update){print "UPDATED ".$result['ID'];} }else{ //IF THE NAME DID NOT EXIST INSERT A NEW RECORD INTO THE TABLE $import="INSERT into computer_memory (`ID`,`PROGRAMNAME`,`PROGRAMURL`,`CATALOGNAME`,`LASTUPDATED`,`NAME`,`KEYWORDS`,`DESCRIPTION`,`SKU`,`MANUFACTURER`,`MANUFACTURERID`,`UPC`,`ISBN`,`CURRENCY`,`SALEPRICE`,`PRICE`,`RETAILPRICE`,`FROMPRICE`,`BUYURL`,`IMPRESSIONURL`,`IMAGEURL`,`ADVERTISERCATEGORY`,`THIRDPARTYID`,`THIRDPARTYCATEGORY`,`AUTHOR`,`ARTIST`,`TITLE`,`PUBLISHER`,`LABEL`,`FORMAT`,`SPECIAL`,`GIFT`,`PROMOTIONALTEXT`,`STARTDATE`,`ENDDATE`,`OFFLINE`,`ONLINE`,`INSTOCK`,`CONDITION`,`WARRANTY`,`STANDARDSHIPPINGCOST`) values('','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]','$data[11]','$data[12]','$data[13]','$data[14]','$data[15]','$data[16]','$data[17]','$data[18]','$data[19]','$data[20]','$data[21]','$data[22]','$data[23]','$data[24]','$data[25]','$data[26]','$data[27]','$data[28]','$data[29]','$data[30]','$data[31]','$data[32]','$data[33]','$data[34]','$data[35]','$data[36]','$data[37]','$data[38]','$data[39]')"; mysql_query($import) or die(mysql_error()); } } } gzclose($handle); ?> I hope someone can see what I can't Thanks everyone Hello, I am very new to both PHP and MYSQL but I am eager to learn. What I want to do is write a PHP script that will parse an XML file and insert the results into a MYSQL database. I've read a bunch of guides online and I think I have the parser structure down. I created a parser using xml_parser_create(). As I understand it, I need to create functions to handle each of the three events, startTag, endTag, and contents. This is where I am not sure what to do. What do I need to tell these functions to do when these events are triggered? I know I need to connect to the MYSQL database at some point but I do not know when. If anyone could point me in the right direction, I'd appreciate it. |