-
Posts
16,734 -
Joined
-
Last visited
-
Days Won
9
Everything posted by PFMaBiSmAd
-
Or - <?php $n = 100; $total = $n * ($n + 1)/2; echo $total; ?>
-
Referencing user-defined variables in a sub select, possible?
PFMaBiSmAd replied to s0c0's topic in MySQL Help
User defined variables can only be used where a value/variable would be used in expressions. They cannot be used as a table/column name. -
While loop -> Array -> Sort -> Remove duplicates
PFMaBiSmAd replied to Mundo's topic in PHP Coding Help
You would want to do this directly in your query, using one of the following two methods - 1) SELECT country FROM your_table GROUP BY country 2) SELECT DISTINCT country FROM your_table ORDER BY country -
It would help if you defined what columns $row[1] and $row[2] are, or better yet, use the associative index NAME so they have meaning (they don't seem to match your table definition, because your word column would be $row[0] or $row['word'] and your tye column would be $row[1] or $row['tye'].) Also, an example of what you are entering in the textfield and what the expected results after executing the code should be would be worth a 1000 words.
-
Trouble with initial installation
PFMaBiSmAd replied to cloksin's topic in PHP Installation and Configuration
What exactly is in your phpinfo.php page, including what the php tags are? -
If you are using the version of the code with str_word_count(), it removes \r \n and you don't need to do anything else.
-
Actually, the error message indicates that you do have a mail server present, but you are not satisfying the requirements to get it to handle an email. The most likely cause of that error is because you are putting the arbitrarily entered email address from the form into the From: address. You must set the From: address to be a valid mail box at the sending mail server and you need to put the arbitrarily entered email address from the form into the Reply-to: address. The second most likely cause is that your web host requires you to use SMTP Authentication unconditionally in order to send an email through the mail server. You would trust a letter that had a From address of your bank but the postmark (where it was sent from) was a completely different country then where your bank is located?
-
Assuming that the maximum size of any of your files is small enough so that it can be read into memory all at once, that the maximum number of unique words in any file is small enough so that a multi-value insert query does not exceed the max_allowed_packet setting (default 1Mbyte), and that your tye column has a default value set to zero in your table definition, see the following sample code - <?php require_once("connection.php"); if ($handle = opendir('pos')){ while (false !== ($file = readdir($handle))){ if(strcmp($file,".")==0 || strcmp($file,"..")==0) continue; // skip the . and .. entries echo "$file<br />"; $words = file_get_contents("pos/$file"); // read the whole file $words = str_word_count($words, 1); // get array of words $words = array_map('strtolower',$words); // convert all to lower case (so that duplicates can be found ignoring letter case) $words = array_unique($words); // remove any duplicates $words = array_map('mysql_real_escape_string',$words); // escape the data // form a multi-value query - INSERT INTO words (word) values (''),(''),('') $query = "INSERT IGNORE INTO words (word) values ('" . implode("'),('",$words) . "')"; set_time_limit(20); // probably not needed echo $query; // show the finished query mysql_query($query); // execuite the query echo mysql_error() . mysql_affected_rows(); // show any errors and the number of words that were inserted echo "<br />"; } closedir($handle); } ?>
-
That query never worked, you must have changed it as well. You have single-quotes around the table name and the column names, making them strings instead of table and column names.
-
The code you posted can be made at least 3x more efficient (you can do this using a single (one) query) and the strcmp() on the $word variable is probably not doing what you expect. To make your existing queries more efficient - 1) I recommend putting your stop words into your main words table and adding a column that 'flags' the stop words so that you can skip selecting them under normal processing. This will eliminate the first query. 2) You don't need to select a word to test if it exists, because you can simply attempt to insert the word and the database will prevent duplicates because your word column is a primary key. This will eliminate the second query. Using items #1 and #2 above will reduce your foreach() loop to the following. The echo/var_dump statements are to show what you are inserting (pertains to what your strcmp() is doing or is not doing) and what the result of executing the query is. - foreach ($words as $word) { if(strcmp($word,".")==0||strcmp($word,",")==0||strcmp($word,"(")==0||strcmp($word,")")==0 || strcmp($word,"\n")==0 || strcmp($word,"\r")==0 || strcmp($word,"\r\n")==0) continue; echo "Insert: [",var_dump($word),"]"; $word=mysql_real_escape_string($word); $query="insert into words values('$word','0')"; var_dump(mysql_query($query)); echo "<br />"; } Next, your strcmp() logic will only remove those characters you are testing for when those characters are separated by a space from any other characters or any word. If your intent is to filter out and remove those characters when they are immediately before/after a word, that logic won't do it. The dot, comma, (), and any \r or \n will be inserted with the word into the table when they are immediately before or after the word. Your existing logic also allows empty strings to be treated as a word because two or more spaces when exploded by the space character results in empty strings in the resulting array. See what the echo/var_dump in the code I posted shows for a bunch of test cases. To fix the strcmp(), I recommend either using trim() with the second parameter set to a list of characters you want to remove before/after each word and make sure you skip inserting empty strings or more simply use str_word_count instead of explode() to extract just the words from each line. If you are looping over thousands of files, your overall speed problem is more likely due to the disk access needed to read that number of files and the time it takes to read each line from each file. What is the maximum expected size of one of these files, because it would be more efficient to read one whole file at a time, get the unique words out of it, and then insert them all at once into your database table.
-
Don't need a direct answer - just where to look for the error
PFMaBiSmAd replied to boblan66's topic in PHP Coding Help
The error means that the php parser reached the end of your file while it was expecting a closing php element of some kind. This is usually due to a missing closing } but it can also be due to a missing closing quote or really any php statement that you have the opening syntax for but are missing the closing element. -
PHP is displayed to page because Doctype = Strict
PFMaBiSmAd replied to Smudly's topic in PHP Coding Help
Php is a server side scripting language. The doc type has nothing to do with php. Only the browser cares about the doc type. If your php code is not being parsed and executed on the server it means that something is preventing the server from seeing the php code as php code. You are either NOT using a .php extension on the file or you didn't browse to the file using a URL in your browser's address bar or you put the file into a location where the php language is disabled on your server... -
<?php $string = "45,3455,66,8900,2,49,88,8,909"; $arr = explode(',',$string); // individual numbers $arr = array_chunk($arr,4); // groups of 4 numbers // change each group of 4 to a comma separated string foreach($arr as $key=>$subarr){ $arr[$key] = implode(',',$subarr); } $string = implode(',<br />',$arr); // make string echo $string; ?>
-
There's nothing technically wrong with the query, provided that all the data values you put into it are numbers and not strings and all the columns exist... The code Pikachu2000 has posted here and probably in the other thread as well contains some debugging logic (the or die() statement) that would help you if you were actually reading what he has been posting.
-
How do I incorporate this Pre-Written PHP code into my website?
PFMaBiSmAd replied to CastItUp's topic in PHP Coding Help
You have got to be a little more specific. There's at least a couple dozen different reasons why a script might not work on any particular server and without the symptoms you saw in front of you to narrow down the possibilities, there's no way to even begin to help you. -
Is this some kind of employment test you are doing or a classroom assignment? Your's is about the 6th thread recently where someone is attempting to use or think they should be using variable variables. If you are somehow required to use variable variables, be advised you are not going to like the answers you get on a programming help forum from experienced programmers. You should not be using variable variables for what you are doing. If you need to buffer/store the results from your query (instead of using the results directly inside of the loop, which is what is normally done as it consumes less memory and takes less processor time) you should be using an array.
-
There is almost never a good reason to execute a query inside of a loop, where all you are doing is getting different values from each query that is executed. In general, you should execute 1 (one) query that gets all the data you want, in the order that you want it, and then simply iterate over that data in your presentation logic. What exactly are you trying to accomplish? What is your data and what is the expected output?
-
mysql_query() returns a result resource, not the data value. I recommend reading a basic php/mysql tutorial to learn how to execute a query and fetch the data from the result resource. Also, session_register(), session_is_registered(), and session_unregister() were depreciated more than 8 years ago in favor of using the $_SESSION array. There are examples of how to use the $_SESSION array in the php.net documentation under Sessions.
-
From the php.net documentation for what you are trying to do - Also from that php.net documentation page, in php versions prior to 5.2.9, the mysqli->connect_error property did not work and you would need to use the mysqli_connect_error() function.
-
The following sample code demonstrates how you might accomplish this (tested) - <?php // various configuration values used in the code $required = array('customername'=>'Customer Name', 'town'=>'Town/City', 'testimonial'=>'Testimonial', 'sort_order'=>'Sort Order'); // required form field names and labels (used in validation logic) $upload_name = 'images'; // the name of the upload field(s) $_FILES['images'] $imgdir = "uploaded_images/"; // destination folder $image_types = array(IMG_GIF,IMG_JPG,IMG_PNG); // acceptable types returned by getimagesize() // form processing starts here - check if a form submitted to this code if($_SERVER['REQUEST_METHOD'] == 'POST'){ $errors = array(); // store any errors // check if the $_FILES array contains anything // the following two if() tests assume that the form will always set at least one $_POST field ($_POST['submit']) if(empty($_FILES) && !empty($_POST)){ // no $_FILES information but there is $_POST information $errors[] = 'No uploaded file information, either the form is invalid (no enctype or no file fields) or uploads are not enabled on this server!'; } if(empty($_FILES) && empty($_POST)){ // both are empty, the maximum post size was exceeded $errors[] = 'No uploaded file information, the total size of all post data and uploaded files exceeds the post_max_size setting!'; } // at this point, if there are no errors, the $_FILES and $_POST arrays contain something and can be processed if(empty($errors)){ include('dbinfo.php'); // get your database connection information // connect to db server and select db (assumes only this code requires a connection...) if($con = mysql_connect($db_host,$db_user,$db_pwd)){ // connect worked if(!mysql_select_db($db_name, $con)){ // select failed $errors[] = "A database error occurred that prevents this page from working at this time!"; trigger_error('Could not select database: ' . mysql_error($con)); } } else { // connect failed $errors[] = "A database error occurred that prevents this page from working at this time!"; trigger_error('Could not connect: ' . mysql_error($con)); } // database connect/select worked, proceed with validating the form data if(empty($errors)){ // validate the form data (customername, town, testimonial, sort_order, and at least one image are required) foreach($required as $key=>$value){ // isset($_POST[$key]) && $_POST[$key] != '' complemented gives -> !isset($_POST[$key]) || $_POST[$key] == '' if(!isset($_POST[$key]) || $_POST[$key] == ''){ $errors[] = "Form field: $value, is empty!"; } } // add other validation tests here ... // validate the uploaded file(s), must be at least one that is of type gif, jpg, or png $upload_errors = array(UPLOAD_ERR_OK => 'There is no error, the file uploaded with success.', UPLOAD_ERR_INI_SIZE => 'The file exceeds the upload_max_filesize directive!', UPLOAD_ERR_FORM_SIZE => 'The file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form!', UPLOAD_ERR_PARTIAL => 'The file was only partially uploaded!', UPLOAD_ERR_NO_FILE => 'No file was uploaded!', UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder!', UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk!', UPLOAD_ERR_EXTENSION => 'A PHP extension stopped the file upload!'); $num_images = 0; // count the number of valid images foreach ($_FILES[$upload_name]["error"] as $key => $error){ if ($error == UPLOAD_ERR_OK){ // a file was successfully uploaded, check if an image and get the image data from it if(list($width,$height,$type,$attr)= getimagesize($_FILES[$upload_name]["tmp_name"][$key])){ // is an image, count it if it is allowed type if(in_array($type,$image_types)){ $num_images++; } else { // wrong image type $errors[] = "The uploaded file: {$_FILES[$upload_name]["name"][$key]}, is not a gif, jpg, or png type!"; } } else { // not an image $errors[] = "The uploaded file: {$_FILES[$upload_name]["name"][$key]}, is not an image file!"; } } else { // upload error occurred. If error = 4, file form field was left empty and ignore the error if($error != 4){ $ul_error_message = isset($upload_errors[$error]) ? $upload_errors[$error] : "An unknown error"; $errors[] = "The uploaded file: {$_FILES[$upload_name]["name"][$key]}, failed because: $ul_error_message!"; } } } // end foreach if(!$num_images){ $errors[] = "No valid images were uploaded, you must upload one or more images!"; } // Expected $_POST and $_FILES data exists, process the actual data if(empty($errors)){ // verify the destination directory if(!is_dir($imgdir)){ $errors[] = "The upload destination directory: $imgdir, does not exist"; } else { // directory does exist, check permissions if(!is_writable($imgdir)){ $errors[] = "The upload destination directory: $imgdir, is not writable!"; } } // destination directory exists and is writable if(empty($errors)){ $query=sprintf("INSERT INTO testimonials (CustomerName, Town, Testimonial, SortOrder) VALUES ('%s','%s','%s','%s')", mysql_real_escape_string($_POST['customername']), mysql_real_escape_string($_POST['town']), mysql_real_escape_string($_POST['testimonial']), mysql_real_escape_string($_POST['sort_order']) ); // execute query if (!mysql_query($query,$con)){ // query failed $errors[] = "The submitted data could not be inserted into the database due to a fatal error!"; trigger_error("Query: $query, failed: " . mysql_error($con)); } else { // query executed without error if(mysql_affected_rows($con)){ // row was inserted, get the id $last_id = sprintf("%05d",mysql_insert_id($con)); // get the id just used, pad to 6 places // move the uploaded files to the final destination // prepend the $last_id onto each file name to create unique names and to associate the files with the record in the database table // loop over files (again) processing valid images foreach ($_FILES[$upload_name]["error"] as $key => $error){ if ($error == UPLOAD_ERR_OK){ // a file was successfully uploaded, check if an image and get the image data from it if(list($width,$height,$type,$attr)= getimagesize($_FILES[$upload_name]["tmp_name"][$key])){ // is an image, process it if it is allowed type if(in_array($type,$image_types)){ // is an allowed image type $tmp_name = $_FILES[$upload_name]["tmp_name"][$key]; $name = $_FILES[$upload_name]["name"][$key]; $whole_name = $last_id . '_' . $name; if(!move_uploaded_file($tmp_name, "$imgdir$whole_name")){ $errors[] = "The uploaded file: $name, could not be saved to: $imgdir$whole_name!"; } else { echo "The uploaded file: $name, was saved to: $imgdir$whole_name<br />"; } } } } } // end foreach echo "<p align=center><b>1 testimonial added</b></p>"; } else { // query failed to insert row // the only way this branch can be reached is if the query executed without error but the row was not inserted $errors[] = "The submitted data could not be inserted into the database due to a fatal error!"; trigger_error("Query: $sql, failed: " . mysql_error($con)); } } } // end of verify destination directory } // end of process the actual data mysql_close($con); } // end of validating form data } // end of $_FILES/$_POST arrays contain data // display any errors that occurred during the processing of the form if(!empty($errors)){ echo "The following errors occurred:<br />"; foreach($errors as $error){ echo "$error<br />"; } } } // end of request_method check // display the form (always) // if post values don't exist, give them default values here (doing this before the upload test would give incorrect results) to be used in the value="" attributes $_POST['customername'] = isset($_POST['customername']) ? $_POST['customername'] : ''; $_POST['town'] = isset($_POST['town']) ? $_POST['town'] : ''; $_POST['testimonial'] = isset($_POST['testimonial']) ? $_POST['testimonial'] : ''; $_POST['sort_order'] = isset($_POST['sort_order']) ? $_POST['sort_order'] : ''; ?> <form action="" method="post" enctype="multipart/form-data" name="add_test" id="add_test"> <p> </p> <p align="center"> <label for="customername">Customer Name:</label> <input name="customername" type="text" id="customername" maxlength="150" value="<?php echo $_POST['customername']; ?>" /> </p> <p align="center"> <label for="town">Town/City: </label> <input name="town" type="text" id="town" maxlength="150" value="<?php echo $_POST['town']; ?>" /> </p> <p align="center"> <label for="testimonial"><u>Testimonial </u></label> </p> <p align="center"> <textarea name="testimonial" id="testimonial" cols="60" rows="10"><?php echo $_POST['testimonial']; ?></textarea> </p> <p align="center"> <label for="sort_order">Sort Order: </label> <input name="sort_order" type="text" id="sort_order" size="10" maxlength="3" value="<?php echo $_POST['sort_order']; ?>" /> </p> <p align="center"> <label for="images"><u>Upload Images</u></label> </p> <p align="center"> <input type="file" name="images[]" /><br /> <input type="file" name="images[]" /><br /> <input type="file" name="images[]" /><br /> <input type="file" name="images[]" /><br /> <input type="file" name="images[]" /> </p> <p align="center"> <input type="submit" name="submit" id="submit" value="Submit" /> </p> <p> </p> <p> </p> </form>
-
And I just noticed that the check_input() function is not ideal because it is adding part of the sql syntax onto the outside of the data, which means it will only work for the simplest queries, creates special conditions in your query syntax so that you must now use multiple different syntaxes for string data in your queries, and it does not work if any of your $_POST fields are arrays.
-
What must be a simple answer.....just not for me
PFMaBiSmAd replied to Stevis2002's topic in PHP Coding Help
Oh wow. Sorry to be blunt, but the check_input() function should not be responsible for putting the single-quotes (part of the sql syntax) around strings. Doing so creates a bunch of special case conditions (such as the $imgname variable) and prevents you from directly doing simple things like using the LIKE comparison with wild-card characters in a query. The only place sql syntax belongs is in the query string. See this recent thread where using the DreamWeaver function that does the same with single-quotes prevented a coder from writing the query he wanted - http://www.phpfreaks.com/forums/php-coding-help/help-adjusting-a-like-statement/ -
Quick fix - form entering blank records - same old problem
PFMaBiSmAd replied to phatmambo's topic in PHP Coding Help
Your code should be validating the form data and only performing the query when all the expected data have values. Doing this would filter out empty submissions.