DavidAM
Staff Alumni-
Posts
1,984 -
Joined
-
Days Won
10
Everything posted by DavidAM
-
I really don't see how this code could dependably work. Line 4 is saying if the date we are currently checking (in the while loop of dates) is the day of week at the current position of the days array, shift the position in the days array to the next position and if we are at the end, reset the position to the beginning. Lines 7,8 and 9 are executed regardless of whether the date is in the days array or not. I hate to say "my code is better", but give it a try: $days = array('tuesday', 'thursday'); while($current_date <= $end_date) { if(in_array(strtolower($current_date->format('l')), $days)) { $date_string = $current_date->format('Y-m-d'); $values[] = "('$date_string', $ti, '$tch', '$drt', '$grp')"; } $current_date->modify("next $day"); } $values = implode(', ', $values); $query = "INSERT INTO clases (fecha, hora, teacher, duracion, grupo) VALUES $values";
-
That query will still not take advantage of the index. Plus, it will return all dates in the current month. This is not what you said you wanted. If you want only ONE WEEK, surrounding the current date, I would use a BETWEEN clause on the date and calculate the first and last date : WHERE cdate BETWEEN DATE_SUB(CURDATE(), INTERVAL (DAYOFWEEK(CURDATE()) - 1) DAY) AND DATE_ADD(CURDATE(), INTERVAL (7 - DAYOFWEEK(CURDATE())) DAY)
-
WHERE YEAR(cdate) = CURDATE() AND : This will never be true since YEAR() is an integer (2013) and CURDATE() is a DATE (2013-07-08). If you have "thousands" of rows for a single date, then you probably should have the cdate column indexed. But the query you posted will NOT use the index, because you are performing calculations on the column. You will get better results using BETWEEN or IN WHERE cdate BETWEEN '2013-07-06' AND '2013-07-13'
-
Why are you changing it in JS? You really should send the user input AS IS to the server; you should store it (in the database) AS ENTERED by the user. ONLY when you decide to display it in HTML should you change it using nl2br. Then you do not have to jump through these hoops. What if you decide to output the data in some other format (i.e. Plain Text email, RTF Document, etc.)? You would have to convert it from the HTML line-breaks back to newlines (or whatever is appropriate for that format).
-
1) You have not stated a problem. What are you trying to accomplish; what is happening that should NOT happen; what is NOT happening that SHOULD happen. 2) Turn on error_reporting (in Development) so PHP will give you some help finding problems 3) I (personally) do NOT download attachments, and I'm sure a lot of others don't either. Post the pertinent code -- using ... tags 4) Since you need slashes in the regular expression, choose a different delimiter so you don't have to keep escaping them: preg_match("~opt/lampp/htdocs/enroll/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\\/", "$theData", $matches) I always use the tilde, since it is rarely in anything I would be searching. 5) In making that change, it appears that there is no closing delimiter on your expression; and why are you putting a backslash at the end of it? Or did you just keep adding "\" until it "looked right"? It looks like you want the literal slash ("/") as part of the expression at the beginning and the end. The preg_ family of functions require a delimiter around the regular expression. So the first and last characters have to be the same and are NOT part of the expression. (Then, there can be modifiers after the closing delimiter) preg_match("~/opt/lampp/htdocs/enroll/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/~", "$theData", $matches)
-
@AbraCadaver: That's an elegant solution, but there are a couple of problems with it: 1) The if($current_date <= $end_date) { is not needed since the condition is handled by the while loop 2) The $current_date->modify("next $day"); needs to be outside the foreach loop. In fact, you can eliminate the foreach and use in_array: $days = array('tuesday', 'thursday'); while($current_date <= $end_date) { if(in_array(strtolower($current_date->format('l')), $days)) { $date_string = $current_date->format('Y-m-d'); $values[] = "('$date_string', $ti, '$tch', '$drt', '$grp')"; } $current_date->modify("next $day"); } $values = implode(', ', $values); $query = "INSERT INTO clases (fecha, hora, teacher, duracion, grupo) VALUES $values"; @OP: You want to avoid running queries in a loop. This solution collects all of the values and executes a single INSERT statement after the loop. Also, as AbraCadaver said, you really should consider normalizing your database.
-
update.php You did not SELECT prod_id so it is NOT in the resultset. upd_prod.php If the error message is exactly the same -- LINE 36 -- and the error occurs when you POST the form to update the data, then the problem is: $prod_id = $_GET['prod_id']; Since the FORM action attribute does not provide the ID in the url. It should also be occuring here (when posted) <td><input type="hidden" name="prod_id" value=<?php echo $_GET['prod_id'];?>> </td> There are some other potential problems with this code: 1) You need to sanitize user input before using it in a query -- even if it is an admin page and not likely to be the target of hackers. Use mysql_real_escape_string on text fields; and cast integers (intval) and floats (floatval). 2) I would recommend using htmlspecialchars to display the text fields (name and brand) to prevent HTML issues. 3) the mysql extension is deprecated and will eventually go away. It is recommended that you use mysqli for new development. 4) You said the second file is called upd_prod.php -- but the code calls it edit.php
-
You say you don't want to use UPDATE but then ask for help with an UPDATE statement? The syntax for an UPDATE statement is different from the syntax for an INSERT statement An INSERT statement does not have a WHERE clause. By the way: You seem to have completely ignored this VERY IMPORTANT piece of advice
-
Print out the error message to see why: if (! mysql_query(...)) echo mysql_error();
-
sel($row_status['list_value'],$category) returns a value, so you need to echo it. value=<?php echo $row_status['list_value']?> You need quotes around the value (for HTML). So: <option <?php echo sel($row_status['list_value'],$category)?> value="<?php echo $row_status['list_value'];?>" > <?php echo $row_status['list_value'] ?> </option>Usually, I use the ID as the value so the database lookup on the submission script uses the primary key.
-
While using the IP address is not a sure-fire way to handle this (in fact, there is no sure-fire way unless you only allow registered users to vote); You should be able to do this in one query: SELECT media.*, IF (ISNULL(ratings.ip), 0, 1) AS HasRated FROM media LEFT JOIN ratings ON media.media_id = ratings.media_id AND ratings.ip = '$ipaddress' WHERE media.type = ...For each media row found, the computed column "HasRated" will be 1 if the IP has rated it, and it will be 0 (zero) if they have not. So you handle everything in a single loop with a single call to the database.
-
His original post did not have echo in it. It may be that the text() method is echoing the value rather than returning it. You're going to have to dig deeper to find out where the "pagetitle" value is coming from.
-
Basically, yes. Typically, after calling *_query() you would call *_fetch() to get a row of the data. That function would return false when there are no more rows to process. Have a look at the manual page link in my last post. In this case, since you don't really want the data, you can call *num_rows to see if it is zero (not found) or greater than zero (one or more found).
-
mysqli_query only returns false if the query fails to execute. When a query executes and returns no data, the function/method returns a valid object. The code you were told to insert is not valid for the intention of checking if data exists. You would need to check the number of rows returned in the result.
-
session_destroy vs session_unset & a few cookie questions
DavidAM replied to jdlev's topic in PHP Coding Help
@ginerjm: This is a "help" site, we are here to help people understand and fix things. We do not attack people for admitting they do not understand. If you don't want to be bothered by this kind of question, then move on to the next post. Don't try to pad your post-count by attacking our visitors. @jdlev: From the PHP manual session_destroy: session_unset() is a holdover from the days of session_register(). I have never used this function (didn't even know it was there until I read your post) -- so, I learned something new from you. The session data is held in the $_SESSION array during script execution. When the script is finished (or you call session_write_close the data is written to a disk file ON THE SERVER. The cookie (as with all cookies) is stored on the client. It contains only a hash (unique id) that identifies the session. The browser sends this cookie whenever it requests a page. The session_start() function retrieves this hash from the cookie (if one is sent by the browser) and locates the disk file by that name. It opens the file and reads the data into the $_SESSION array for the script. It will also send the cookie to the browser for the next request. So setcookie will NOT destroy the session data ON THE SERVER, it simply tells the browser to forget about the session. It will (if the browser is well behaved) expire the cookie so it can be deleted. YES. See the manual for session_destroy, the Example they give shows code to completely clear the session. Correct. The only thing the client can see is the hash (or ID) of the session. The client cannot directly see the contents of the SESSION. However, as you know, the file can be openned with notepad (or any file utility) ON THE SERVER, to see the contents. Since the session files are stored on the server in an area that is readable and writeable by the webserver, it is possible for someone with access to the server to view these files (especially on shared hosting). This is another reason we never store passwords in the session. I personally avoid using that kind of if: if ($_SESSION) it is not clear when reading the code at a later time, what you are testing there. And frankly, I'm not sure when that would be true and when it would be false. That makes it unreliable in my mind, so I would just use something more concrete. However, I suspect that if a new session has been started and nothing was ever stored in it, that first IF would be false. If you simply want to know if a session has been started, I believe if (session_id()) is a better test. That function returns an empty string if there is no session or it returns the id (the hash) if one has been started. Looks like PHP 5.4 has session_status which would be a better choice entirely. If you want to know about some specific session variable, if (isset($_SESSION['userid'])) would be my choice. -
php code for connecting to mysql database
DavidAM replied to mrchickenkiev's topic in PHP Coding Help
1) If that is your actual username and password for the database, you may want to change them right away. You have posted them on a public website that is indexed by Google (and others) regularly. In the future, when you post connection code, X-out the username and (especially) the password. $link = mysql_connect('localhost', 'XXXXX', 'XXXXX'); 2) The mysql (old library) funtions do not require the connection to be passed to every function. The library will use the last connection created. It is an optional parameter, and is useful if you need to connect to multiple different database servers. 3) in your "or die()" phrases attached to mysql calls, you should add the mysql_error call as part of the echo, it will tell you why the database rejected it. When the select database fails, it either does not exist, or the user does not have permission in it. Check your spelling (case may matter). Try $db = mysql_select_db('curem801_languages',$link)or die("Unable to select database: " . mysql_error()); and see what problem it reports. 4) If this is new development, you should be using the "improved" mysql library. The original one has been deprecated and there is no sense in learning it. See mysqli in the PHP manual.- 20 replies
-
Kind of left that out, didn't I. I would hardcode the path as either a configuration option of the application, or as a defined constant in a globally included file. Don't hardcode the value everywhere it is used, since it would have to be changed in multiple places. define('C_IMAGE_PATH_HTML', '/images/'); define('C_IMAGE_PATH_PHP', '/home/mad/www/images/'); something like that defines "images" as a subdirectory of your public directory for adding it to IMG tags; and the absolute path for PHP statements (such as move_uploaded_file). Obviously, you might have to change both of them when changing hosts, or if you move your image folder. # Use C_IMAGE_PATH_PHP for PHP access to the filesystem move_uploaded_file($_FILES['tmp_name'], C_IMAGE_PATH_PHP . $imageFileNameInDatabase); # Use C_IMAGE_PATH_HTML for HTML access to the images echo '<IMG src="' . C_IMAGE_PATH_HTML . $imageFileNameInDatabase . '">';
-
1) Suppressing errors is NOT a good idea. Let them get reported in DEVELOPMENT and fix them. Then log them in production. However, the "@" error suppression suppress only PHP errors. If the PHP code is good and the connection is attempted, it will return a value OR it will return FALSE if unable to connect. This is where the OR DIE() comes in. 2) The WHILE loop is your problem. I've never seen OR DIE() used in that way. while($row = $result->fetch_array() will load a row of data into the $row variable and process the statements inside the loop. Then it will try to fetch another row. When there are no more rows to fetch, this method returns FALSE, so you know it is done. With the OR DIE on there, it will ALWAYS be executed after processing the last row in the resultset. If you only expect one row, you don't need a loop. If you expect multiple rows, you don't want the OR DIE().
-
Don't store images directly in the database. Store them in a directory on the server, then store the filename in the database. The path should be the same for all images, so it is redundant to store that information; plus, if you change servers or move the folder, you will have to update every row in the table.
-
@ginerjm -- PHP is not strictly for serving web pages. It is a scripting engine and can be used for various other purposes. I often write scripts on my Linux box to manage certain aspects of that system. These scripts are run from the command-line (without a web-server). The term "download" generally means to retrieve a file from a remote system. The term "upload" generally means to send a file to a remote system. In both cases, the remote system is "acting" as a "server" and the "local" system is acting as a "client". @OP -- As I understand it, you are trying to retrieve ("download") a file from a remote server. This can be done, using either curl or file_get_contents. The file will be retrieved to the system where PHP is running. You can not then directly store it on a different system without some other "magic" (i.e. another script) going on. Ask your "friend" what precautions are in place to prevent direct downloads of images from this site. I tried requesting the file with wget, and received a "403: Forbidden" error from the server. It didn't take long to figure out how to get past that; they do, after all, have to be available for direct retrieval; but I would think someone with a legitimate reason to retrieve them would know what obstacles have been put in place.
-
code not executing - no error messages received
DavidAM replied to hance2105's topic in PHP Coding Help
This Array ( [fav] => Array ( ) )is the output from the print_r. And that indicates that the session array is empty. So the problem appears to be in the code that is building the list of favorites. If you turn on error reporting in that script and add an item, what messages do you get? -
While I absolutely agree with mac_gyver -- the data needs to be normalized -- the function you are looking for is array_search. Since you are using FETCH_ASSOC, this will return the column name for the value you have. Again, the database should be normalized rather than trying to work around issues that should not exist.
-
code not executing - no error messages received
DavidAM replied to hance2105's topic in PHP Coding Help
The code you posted does not show a session_start(). Turn on error reporting so you can see what is happening. Also dump the session at the start of the page to see what is there. Put as the very first line in the script. <?php error_reporting(E_ALL); ini_set('display_errors', 1); session_start(); printf('<PRE>%s</PRE>', print_r($_SESSION, true)); -
The standard way to process a query is (psuedo code): $sql = 'SELECT ...'; $res = mysql_query($sql); # Test to be sure the query did not fail # If you need the number of rows ... $rowCount = mysql_num_rows($res); # retrieve and process each row while ($row = mysql_fetch_assoc($res) { # do something with each row of data } mysql_free_result($res);You seem to have num_rows() and fetch_assoc() in the wrong places. Also, the mysql library extension in PHP has been deprecated (it is going away). For new development you should be using the improved version mysqli (there's an "i" on the end).
-
code not executing - no error messages received
DavidAM replied to hance2105's topic in PHP Coding Help
You bump a thread after 2 minutes? Really! That is against the rules. You do not have a session_start() in the code showing the favorites. Also, $ids = implode(',', $_SESSION['fav']); would be much less code than looping through the array.