DavidAM
Staff Alumni-
Posts
1,984 -
Joined
-
Days Won
10
Everything posted by DavidAM
-
Loop through a section of one array to create a 2D associative array...
DavidAM replied to ltd17's topic in PHP Coding Help
$multi[] = array(...); will add the array() on the right-hand side as a new element of the $mult array. It will start at zero if the array is not already defined, or will add the element with a numeric key greater than the last (adding 1 each time). so you end up with: $multi[0] => array( ... ) $multi[1] => array( ... ) and so forth. Just add the square brackets to the assignment you currently have and drop the outer array. Also, I usually define the variable as an empty array just to make the code clearer on what I am doing. It is not actually necessary: $multiproducts = array(); for ($counter = 0; $counter < $loopcount; $counter += 1) { $proditerate = 18 + ($counter * 12); $multiproducts[] = array( ProductTitle => substr($data[$proditerate], 0 , -1), ProductLink => substr($data[$proditerate+1], 0 , -1), ProductImage => substr($data[$proditerate+2], 0 , -1), ShopkeeperImage => substr($data[$proditerate+3], 0 , -1), ShopkeeperID => substr($data[$proditerate+4], 0 , -1), ShopName => substr($data[$proditerate+5], 0 , -1), ShopLink => substr($data[$proditerate+6], 0 , -1), ShopkeeperName => substr($data[$proditerate+7], 0 , -1), DollarPrice => substr($data[$proditerate+8], 0 , -1), CentsPrice => substr($data[$proditerate+9], 0 , -1), CommentExpression => substr($data[$proditerate+10], 0 , -1), CommentQuote => substr($data[$proditerate+11], 0 , -1), ); }; -
SELECT DISTINCT looks for distinct rows. You need to select only the fields that you need AND are distinct: SELECT DISTINCT userid, blogid FROM ... or if you need other data, say how many comments the user has made on the blog, you can use GROUP BY: SELECT userid, blogid, COUNT(commentid) FROM ... GROUP BY userid, blogid which is distinct by virtue of the GROUP BY phrase
-
try using %n instead of %i? Look at the examples in the manual (http://us3.php.net/manual/en/function.money-format.php)
-
at this point, I would add a print_r($_FILES) just before the IF statement and see what the array contains. Is the 'error' element something other than zero? Is the 'size' element what you expect? If the upload failed, then 'size' is probably zero (or empty) so your script is going to try to run. I really think you need to check the 'error' element before (or instead of) testing the 'size' element.
-
I left the categories out of the example query because I was thinking your thumbs_id might not be in sync with uploads_id. When you run the query that I provided, do you get the right filenames? Does the file for thumb_id = 1 match up to the file for upload_id = 1, and for = 2 and = 3, and so forth throughout your tables? If they are correct, I do not see why your original query would not work. The last query you sent looks fine too, but why do you have the parenthesis in there? FROM (categories INNER JOIN thumbs ON categories.category_id = thumbs.category_id) INNER JOIN why not just FROM categories INNER JOIN thumbs ON categories.category_id = thumbs.category_id INNER JOIN
-
So when you say: Do you mean the file is larger than the limit you have set or that it is larger than is allowed by PHP? If it is larger than PHP allows, the file is not uploaded so it DOES NOT EXIST. Setting the MAX_FILE_SIZE larger than the PHP maximum allowed, does not allow a larger file to be uploaded (I think). In fact, I believe that field on the form is more informational to the browser than anything else. I have not worked with file uploads much, but I believe this is what I have read. If you want to allow a file size larger than the PHP maximum, you have to change the ini setting IF THAT IS ALLOWED BY YOUR SERVER CONFIGURATION. You can try ini_set() in you php script to change it, but the main php.ini may disallow this change.
-
I don't see anything wrong with the query however, thumb_id and upload_id are both AUTO_INCREMENT, yet you JOIN them as if they are expected to be the same value. If every insert into thumbs has a related insert into uploads AND IN THE SAME SEQUENCE, and neither has ever failed, these IDs might be equal, but I would not depend on it. If you SELECT thumbs.thumb_id, thumbs.file_name, uploads.upload_id, uploads.file_name FROM thumbs JOIN uploads on thumb_id = upload_id DO you get the correct filenames? If not you need to re-think your database design and/or your INSERT process.
-
That should get you all the users that HAVE received awards. To get the ones that have NOT, you have to do an outer join and look for a NULL award. Something like this: SELECT * FROM Users LEFT JOIN Awards ON Users.UserID = Awards.UserID WHERE Awards.AwardID IS NULL
-
If I understand your question; you are trying to use AT commands to talk to a modem on a COM port. You don't need to use hyperterminal for this. It's just another layer of complication. Look at PHP's Direct IO extensions (http://us3.php.net/manual/en/book.dio.php). You should be able to open, read, and write a COM port directly. I've never done this in PHP either. But I would think it could be done.
-
I don't see where you have set $maxsize, if it is in config.php, then that's ok. If it is not defined, then the IF statement is a problem. You should probably check the error code for the upload ($_FILES['file']['error']) before checking the size. If the file is bigger than allowed, then it is not uploaded and the error code will be something other than zero (see http://us3.php.net/manual/en/features.file-upload.post-method.php). In that case the file you are running md5_file against does not exist and you will get that error.
-
I took a closer look at your code: <input name="img" type="file" id="img" size="15" /> This INPUT element is for a file upload. You do not get a value in $_POST['img'] from it. The uploaded file information is stored in the $_FILES array (see the documentation http://us2.php.net/manual/en/reserved.variables.files.php)
-
long slow sql needs a better approach - newbie here :)
DavidAM replied to cdinca's topic in MySQL Help
Actually, I thought about that long after I posted my message. Yeah, I think that outer SELECT should come out and just do it as a series of UNIONS. I really think that is the best you will get with the database you have. You might consider adding some indexes on columns that are used in the WHERE clause (not the one with the OR's but the other ones). Either a single column index where the column value vastly defines the set of records you want, or a multi-column index, like aca_type and atennis2. Of course if you use atennis2, you'll also have to do an separate index for each of the other sports. The index might get pretty big (depending on the amount of data, and the number of differnet values) but it could reduce the execution time. Look at the query plan to see how it helps. Note that creating two separate indexes say one on aca_type and another on atennis2, will probably not help. I don't know the internals of mySql, but in my experience, a query will not generally use two separate indexes on one table, it will pick the one that helps the most and use it. Someone who has more experience with mySql can correct me if I'm wrong (I wouldn't mind learning something new today). I don't know which storage engine you are using or which ones are available to you. And I really don't know the performance difference between them, but I suspect that there are differences in performance. So if changing the storage engine is an option (and I'm sure it will be a lot of work to do), you might do some research on the performance of the different engines. Good luck! -
Yeah, It looks like it does not like the COUNT(C.*). I have had problems with mySql not liking to count the *. Pick a column in the pic_comments table (if you have a unique ID, use it), and change it to count that column; like COUNT(C.id) or COUNT(C.cmt_id) or whatever the column name is. If that does not work, then try copying the SQL and paste it in your Query Browser, or mySqlAdmin. See if you can track down the problem from there.
-
if($_POST["submit"] == "Insert"){ The button's name is Insert, not submit. And it's value is submit, not Insert. The if should read : if($_POST["Insert"] == "submit"){ Also, there is no INSERT statement, you are using an UPDATE statement, which is not the same as an INSERT. There is no connection to a database, so the mysql_query() call cannot work.
-
No offense intended, but did you actually use 'edited-out.com' or did you use 'yourdomain.com'? If your main url is www.MyDomain.com and your sub-domain is www.test.MyDomain.com, then I think the setting would be: session_set_cookie_params(0, '/', '.MyDomain.com'); I've never used this, but I want to make sure you set the right value.
-
Using PHP for site navigation to pages in subfolders
DavidAM replied to djkirstyjay's topic in PHP Coding Help
I don't think you want to include from a URL. That forces a network call instead of just a read from the file system. It is more likely that the value of $_GET['main'] is escaped or url encoded in some way. You need to look at what the value is when you use the subdirectory. If gpc_magic_quotes is on, you will have to stripslashes() on that value before trying to use it. -
That error indicates that $result is not a mysql resource. That means the call to mysql_query() failed. There is probably an error in the SQL statement. You can add a line after the call to display the error: if ($result === false) { echo mysql_error(); } to have the error message printed. Or you can echo the sql before calling it to see what it is: echo $query; The you can copy and paste into the query browser (or mysqlAdmin) to see if the query works and returns what you expect. It seems like I sometimes have trouble with COUNT(*), and have to specifically name a column -- COUNT(C.id) -- or something. I don't see how the test page you did could work, you never execute the query. Maybe you just left the line out when you posted it? Do you have error reporting on? add a line at the top of the page that says error_reporting(E_ALL); so you can see them (at least during development). $thumb = $row[thumb]; // that line should be $thumb = $row['thumb']; you should get a warning that "thumb" is not a defined constant, and assuming you meant the literal string 'thumb' which is what you meant and so it works. But it is bad practice, you should quote those literals instead of letting the PHP engine make assumptions.
-
preg_match with variables. how escape forward slash in variable
DavidAM replied to becu's topic in PHP Coding Help
I know you got it working, but for future reference, you might look at the preg_quote() function. Also, your regular expression does not have to be delimited by '/' you can actually use any character. it is best to use one that is not going to be in the expression. So preg_match('/php/i', $string); is equivalent to preg_match('-php-i', $string); -
Yes, this is a scope problem. Variables you define outside of a function are not available inside the function. In this case: $hostname_conn, $username_conn, $password_conn, $database_conn, $pageID, $pageType, $ip, $email are NOT available to the function. There are two ways to solve this problem. The easiest way, which is the sloppiest and least recommended, is to make these available inside the function using the global keyword (I'm not even going to show you how). The cleanest way is to pass into the function what you need. But before we do that, you should reduce the function to a single task. So take the database connection stuff out and leave it at the global level. $db_conn = mysql_pconnect($hostname_conn, $username_conn, $password_conn) or trigger_error(mysql_error(),E_USER_ERROR); //select the database to use mysql_select_db($database_conn,$db_conn); then create the function with parameters (use a reference for the db connection NOT a copy) function insertStats($pageID, $pageType, $ip, $email, &$db_conn){ //create the SQL statement $stmnt = "INSERT INTO stats values('','$pageID','$pageType','$ip','$email',now())"; //execute the sql statement $execute = mysql_query($stmnt,$db_conn) or die ("Error,please email [email protected] to report this error, try again later!"); echo " Page Access logged"; } then call the function passing the required parameters insertStats($pageID, $pageType, $ip, $email, $db_conn); Other points to consider: or die() is not a nice way to handle an error. Consider having the function return a value of TRUE or FALSE depending on success and let the calling routine decide what to do when the function fails. or trigger_error() is just going to output an error message, it will continue to execute the following statements. You should check the result of the function call and decide how to handle a case when the database is not accessible.
-
Glad to help. One thing I did not think about before. The IF that I removed, may need to be brought back into play. If the file the user uploads is NOT an image, or is corrupted, you may want to use that IF to substitute the generic file in its place. Just something to consider. Happy Coding
-
long slow sql needs a better approach - newbie here :)
DavidAM replied to cdinca's topic in MySQL Help
While the best solution to this problem would be to normalize the database; since that cannot be done, we can try to improve the query. You have multiple levels of sub-queries. The inner-most level (3 sub-queries) are all scanning the same table with the same BASE criteria. We can pull this out to the middle level and remove three table scans for each of the UNION sections. The first set would look like this: SELECT grandtotal,maincategory,oof,underp,novice FROM ( SELECT COUNT(this_database.atennis2) as grandtotal, 'tennis' as maincategory, SUM(IF(graduated='0',1,0)) as underp, SUM(IF(NONLIC_tennis='1' AND graduated='1',1,0)) as oof, SUM(IF(NONLIC_tennis='0' AND graduated='1' AND newbie='0',1,0)) as 'novice' FROM this_database WHERE this_database.atennis2=1 AND (HAIR='R' OR HAIR='B' OR HAIR='CC' ) AND aca_type='Sport Academy' UNION Using SUM() and IF() we can get a count for each of those conditions (it is a count because we are SUMming the value of 1 (one)). And do it in a single sub-query. Each of the UNION sections can be revised to a similar arrangement by substituting the appropriate columns (atennis, asoccer, afootball, etc). Give this a shot and see if the performance improves significantly. I am looking at the UNIONS to see if there is a similar solution so we can eliminate them, but the query itself may be more complex, and we may have to change the structure of the returned data, which may or may not be a problem for you. -
If form.php is the original contact form, then you can put all of the code in this one file and do away with the second file contact.php. You will note in the example code I posted that the action attribute of the form is blank, this causes the form to post to the same file that it is in (in this case form.php). You can explicitly put form.php there but if you later change the name of the file you will have to change it in the action as well (of course you will be changing it on other pages that link to it, so that is no big deal). So, basically, the code I posted becomes form.php and you delete contact.php (well, save it off somewhere incase you want to refer to it later). Note, that I did not include any of your processing that builds up the mail parameters in the example, you will have to cut and paste that as needed. I did not test that code, so it may have some issues. If you run into any problems, continue to post the problems, code and error messages.
-
I think there are two things you need to do here. 1) since the variable inside the literal string is an array, mark it with cury braces; mysql_query("UPDATE $table SET mainPic = '{$file_name[$i]}' WHERE email = '$email'"); 2) you definitely need to escape the value - to do this we have to pull it out of the literal (so #1 no longer applies) - unless you escaped it when you put it in the array. $file = mysql_real_escape_string($file_name[$i]); mysql_query("UPDATE $table SET mainPic = '$file' WHERE email = '$email'"); you need to escape the $email address as well if haven't already.
-
You are getting the error because the file does not exist. A little change to the sequence and the if statement should solve the problem: if (file_exists ($originalFile['tmp_name'])) { $dimensions = getimagesize($originalFile['tmp_name']); $desiredW= 300; // if($dimensions[0]>0){ REMOVED IN FAVOR OF IF ABOVE $desiredH= number_format($dimensions[1] /$dimensions[0] *$desiredW); $dest= imagecreatetruecolor($desiredW, $desiredH); imageantialias($dest, TRUE); switch($dimensions[2]) { case 1: $src = imagecreatefromgif($originalFile['tmp_name']); break; case 2: $src = imagecreatefromjpeg($originalFile['tmp_name']); break; case 3: $src = imagecreatefrompng($originalFile['tmp_name']); break; default: return false; break; } imagecopyresampled($dest, $src, 0, 0, 0, 0, $desiredW, $desiredH, $dimensions[0], $dimensions[1]); $imageNewName = strtolower($imageNewName); $imageNewName =str_replace(" ", "_",$imageNewName); $imageNewName=$imageNewName.".jpg"; $destURL="../../images/products/".$imageNewName;//PATH imagejpeg($dest,$destURL, 80); }else{ // OF COURSE $dimensions is not defined now, so if you need it later, deal with that $imageNewName="generic.jpg"; } PS: Use [ code ] tags when posting code, it makes it easier to read
-
That would be one way to do it. However, it leaves the user on an error page, and they will have to navigate back to the form page and re-type everything to try again. If the form is in a separate file from the processing, then that is pretty much what you are stuck with (unless you want to do a lot of work to get the fields back to the original page). However, to make it more user friendly, you can put everything in one file and have it all. Let's call that file prayerReq.php (or whatever you want). It would look something like this (THIS IS NOT A WORKING CONTACT FORM, IT IS BASICALLY A TEMPLATE): <?php $errMsg = array(); // An empty array for error messages // Empty variables so we can redisplay user's entry if there is an error $name = ''; $email = ''; $message = ''; if (isset($_POST['submit'])) { // Did the user submit the form? if (isset($_POST['name'])) { $name = $_POST['name']; // BE SURE TO SANITIZE THIS FIELD } else { $errMsg[] = 'Your Name is Required.'; } if (isset($_POST['email'])) { $email = $_POST['email']; // BE SURE TO SANITIZE THIS FIELD } else { $errMsg[] = 'Your Email Address is Required.'; } if (isset($_POST['message'])) { $message = $_POST['message']; // BE SURE TO SANITIZE THIS FIELD } else { $errMsg[] = 'Some type of message is Required.'; } if (empty($errMsg)) { // If there are no error messages we can send the email // compose the mail parameters here if (mail(...)) { $errMsg[] = "Your prayer request has been submitted."; } else { $errMsg[] = 'Error sending email. Try again later '; } } } ?> <form method="POST" action=""> <p>Name: <input type="text" name="name" size="19" value="<?php echo $name; /* Show what the user typed the first time */ ?>"> <br> <br> E-Mail: <input type="text" name="email" size="19" value="<?php echo $email; /* Show what the user typed the first time */ ?>"> <br> <br> <input type="checkbox" name="check[]" value="Please list this in the bulletin"> I would like to have my prayer<br> request listed in the weekly bulletin. <br> <br> Message:<br> <textarea rows="9" name="message" cols="30"><?php echo $message; /* Show what the user typed the first time */ ?></textarea> <br> <br> <input type="submit" value="Submit" name="submit"> <?php if (! empty($errMsg)) { foreach ($errMsg as $msg) { echo $msg . '<BR>'; } } ?> </p> </form> You will note that within the form, we echo the user's original entries. If the page was NOT POSTed (user's first time to the page) these fields are empty (we set them at the top). If the page was POSTed, these fields contain whatever we got from the user and fill the field in so they do not have to re-type it. You will have to look at magic_quotes_runtime(), stripslashes(), and some other stuff to make sure you show what they typed. At the bottom of the form, we display the error messages (if any) so the user can fix the problems and try again. The page name has to have the .php extension (or some other extension that your server will process as php). So you may have to change links on other pages that send the user here. EDIT: I know that may require significant changes. If you are close with what you have, then post your files (be sure to use code tags) and we can help finish what you've got.