Jump to content

Psycho

Moderators
  • Posts

    12,157
  • Joined

  • Last visited

  • Days Won

    129

Everything posted by Psycho

  1. This absolutely is possible. I have a working script for this, but might take me a while to find it. However, I have no knowledge of Joomla so YOU would need to figure out how to make it work. The key is you would put the MP3 files in a directly that is not publicly accessible. You could use .htacxcess, but I like using a non-public folder. Anyway, all requests for an MP3 files will be through a URL such as mysite.com/playmp3.php?id=123 where the parameters on the URL identify the MP3 to be played. I built this to pass the ID of the database reocrd associated with the MP3 file, but you can tweak that as needed. You can put logic on that page to check if the user is logged in. If no, kick them to another page. If yes, get the file path to the file and read() the file and pass the result to the user. You can even create playlists that use these URLs and they will play in your MP3 player just as if they were on your PC.
  2. I used your exact wording (which I wouldn't use) and did a Google search: "PHP how long it takes for the page to get built" and lo and behold the fourth result provided an answer to what you are looking for.
  3. I see what you mean. I could have been more clear. What I was trying to state was that the possibility of collisions within that space of permutations is so infinitesimally remote that the discussion of whether they are an issue or not for passwords is not even worth discussing. And, trying to even use collisions for the purpose of cracking a password would be a foolish endeavor. I don't see the point. Are you thinking that storing it in this way will trip up someone trying to brute force the values? I guess that is a possibility, but think about "who" you are trying to protect the data from. This would be people with decent technical skills. Assuming you are already using a good hashing method, these would be people that have enough knowledge to reverse engineer the hashing method to create the logic to run a brute force attack. Do really think this type of person would not recognize that the hash is stored in binary and just add that to the brute-force process? I would run off the assumption that a person who has infiltrated my DB has likely accessed the source files as well. And, in that case they can "see" that the values are stored in binary. All this does is add a small level of obfuscation. And, obfuscation does not equal increased security in my opinion.
  4. Was that in response to my post? I was agreeing with you. Perhaps it is you that is confused. I specifically stated that collisions were a non-issue with respect to passwords. The collisions are only an issue when using a hash for something such as a checksum where an alternative file could be created to appear to be the target file with potential malicious modifications, and yet produce the same hash. It is not an easy thing to do, but it is possible. Again, I was just elaborating on your previous comment.
  5. To elaborate: MD5 hashes are commonly used as a checksum on files so you can verify the file you just downloaded has not been tampered with from what the original provider intended (e.g. someone has inserted a virus). It is in this context that collisions become an issue. With a large source it is possible to create another file with the same size which would produce the same hash - defeating the purpose of a checksum. With the "relatively" limited number of possible password combinations that could be produced with 8-40ish of the available characters, I would guess it is a safe bet that no collisions would exist in that range.
  6. There are a lot of problems with that code, the least of which is not getting the 'count'. 1. Don't use the mysql_ functions - they have been deprecated a long time. Use either mysqli_ or PDO 2. YOu are completely open to SQL injection 3. No need to check for $_POST['submit']. You are only interested in the 'type' so just check for that. Or, where there are multiple values being submitted, you should check the request method. 4. You're not checking for errors As to your specific request, you are defining $month from the exploded string of the last modified date, and then you define count from the mysql_num_rows() of $month. That makes absolutely no sense. mysql_num_rows() is used to count the number of rows of a database result. If you don't want the data and only need a cont - then query just the count and not the data. I think what you really want is the data count broken out by year and month. Start with this: <?php if(isset($_POST['type'])) { $type = mysql_real_escape_string($_POST['type']); $query = "SELECT YEAR(last_modified) as year, MONTH(last_modified) as month, COUNT(id) as count FROM leads WHERE lead_customer ='{$type}' GROUP BY year, month ORDER BY year, month"; $result = mysql_query($query); while ($row = mysql_fetch_array($result)) { echo "Year: {$row['year']}, Month: {$row['month']}, Count: {$row['count']}<br>\n"; } } ?>
  7. @jcbones: maybe I am not seeing something in the code I provided, but I don't see how it is possible that the header would show when there are no records or how the changes you provided would make any difference. Here is what I see: $result= mysql_query($query) or die("Query $query failed : " . mysql_error()); //Create city output $cityData = array(); while($cityData[] = mysql_fetch_assoc($result)) {} After the query is run, an empty array is defined to hold the records from the query. Then a while() loop is used to append those records to that array. Therefore, if there were no records - the array would still be empty. $cityTable = createEntityOutput($stateName, "Independent cities of %s", $cityData, "<a href='services.php?city=%d'>%s</a><br />\n", 3); Next, the function to create the output is called passing the above array as one of the parameters. Again, either that array is empty (if there were no results from the query) or it contains the results from the query function createEntityOutput($stateName, $headerFormat, $entityData, $entityFormat, $columns) { //If no records, return empty string if(!count($entityData)) { return ''; } Then the very first lines in the function check to see if that passed array is empty or not. If so, it returns an empty string. Otherwise, it continues with creating the output - including the header, which the OP states is being displayed. Therefore, I have to assume the current problem is due to one of three things: 1. The OP modified the code I provided such that the header is always displayed (e.g. maybe it is hard coded later in the code rather than being dynamically created with the function. 2. The result of the query is not empty. Perhaps the "data" in the records returned are empty, but the query is returning results. 3. There is a gap in the code I provided that I am not seeing.
  8. Yeah, several: 1. Don't use "SELECT *" unless you are using all the fields in the table 2. Don't use the mysql_ functions. Use either mysqli_ or PDO. I didn't change it in the code below as there are some statements not included. 3. No need to define a variable, if you are only going to use it once $state_name = $row["st_name"]; Just use $row["st_name"] 4. Don't echo the actual DB error to the page in a production environment. It gives malicious people information they can use to get into your system 5. The code to output the counties is waaaaaay over-complicated. I can't even tell what you are doing. I am going to assume you are displaying the records in three columns, the first third in the first column, the second third in the second, etc. rather than having them display left to right. 6. If you are going to run logic more than once, don't copy/paste the code. Create a function and call it multiple times. That way when you have a bug you only need to fix it in one place. Also, by doing this you are assured of consistent results. This was a significant rewrite without any testing, so there may be a few errors to resolve <?php //Function to create output for counties/cities of a state function createEntityOutput($stateName, $headerFormat, $entityData, $entityFormat, $columns) { //If no records, return empty string if(!count($entityData)) { return ''; } //Create the output $output = "<h2>" . sprintf($headerFormat, $stateName) . "</h2>\n"; $output .= "<table width='100%'>\n"; //Create needed variables $recTotal = count($entityData); $recPerCol = ceil($recTotal / $recCols); $colWidth = floor(100 / $columns); $recCount = 0; //Create entity output $output .= "<tr>\n"; foreach($entityData as $data) { $countyCount++; //Open new column, if needed if($recCount%$recPerCol==1) { $output .= "<td valign='top' width='{$colWidth}%'>\n"; } //Create output for single entitiy $output .= sprintf($entityFormat, $data['id'], $data['name']); //Close column, if needed if($recCount%$recPerCol==0 || $recCount==$recTotal) { $output .= "</td>\n"; } } $output .= "</tr>\n"; $output .= "</table>\n"; return $output; } //Run query to get state data $query = "SELECT st_name FROM state WHERE st_id=$statecode"; $result = mysql_query($query) or die("Query $query failed : " . mysql_error()); $state = mysql_fetch_assoc($result); $stateName = $state['st_name']; //Run query to get county data $query = "SELECT county_id AS id, county_name AS name FROM counties WHERE st_id=$statecode AND visible=1 ORDER BY county_name ASC"; $result = mysql_query($query) or die("Query $query failed : " . mysql_error()); //Create county output $countyData = array(); while($countyData[] = mysql_fetch_assoc($result)) {} $countyTable = createEntityOutput($stateName, "Counties of %s", $countyData, "<a href='services.php?county=%d'>%s</a><br />\n", 3); //Run query to get state data $query = "SELECT city_id AS id, city_name AS name FROM cities WHERE st_id=$statecode AND visible=1 ORDER BY city_name ASC"; $result= mysql_query($query) or die("Query $query failed : " . mysql_error()); //Create city output $cityData = array(); while($cityData[] = mysql_fetch_assoc($result)) {} $cityTable = createEntityOutput($stateName, "Independent cities of %s", $cityData, "<a href='services.php?city=%d'>%s</a><br />\n", 3); ?> <?php echo $countyTable; ?> <br> <?php echo $cityTable; ?>
  9. Psycho

    case help

    I'm not understanding what you are trying to do with that CASE condition. If I am reading the query correctly you are hard-coding @category to be "Videos". So what is the purpose of the CASE statement to test the value of @category? But, you could just add another condition to the JOIN (if I understand the intent correctly). LEFT JOIN categories c ON c.name = 'Videos' AND @category != 'All'
  10. You're editing files ON A LIVE SITE?! That's suicide. Take a backup of the code and the database and make changes in a development environment! Anyway, your original "request" was vague. But, now you've confirmed that you really DON'T want to sort by street. What you really want is to sort by pr_live, then by pr_modified THEN by street. Therefore the query should probably look like this: SELECT * FROM property LEFT OUTER JOIN pr_imgs ON property.pr_id = pr_imgs.pr_id AND pr_imgs.pr_img_count = '0' ORDER BY property.pr_live DESC, property.pr_modified DESC, property.pr_street ASC Also, you should not use '*' in the SELECT and should instead list out the actual fields you will use. And, that was production code? There's a lot of inefficient code in there. I hope you looked at the code I provided to see the types of changes that can be made. I assume the same types of problems exist elsewhere.
  11. OK, I read through your code and you are already ordering the query that is used to get those results. SELECT * FROM property LEFT OUTER JOIN pr_imgs ON property.pr_id = pr_imgs.pr_id AND pr_imgs.pr_img_count = '0' ORDER BY property.pr_live DESC, property.pr_modified DESC You should order the results how you want them displayed. So, are you wanting them to ALL be sorted on 'pr_street' or are you wanting them to be sorted as they are now and then sorted by 'pr_street' where 'pr_live' and 'pr_modified' are the same? There's a lot more I would change, but give this a try (might be some minor typos) <?php /////////////// SEO /////////////// $keywords = ""; $description = ""; /////////////// DB Connection /////////////////// include('../includes/connect.php'); include('../includes/login.php'); if(isset($_GET['delete'])) { $del_id = $_GET['delete']; $query = "SELECT pr_img_id, pr_img_path_xl, pr_img_path_l, pr_img_path_m, pr_img_path_s, pr_img_path_xs FROM pr_imgs WHERE pr_id = '$del_id'"; $result = mysqli_query($db, $query); $deleteIDs = array(); while($row = mysqli_fetch_array($result)) { if(!empty($row['pr_img_path_xl'])){ unlink('..'.$row['pr_img_path_xl']); } if(!empty($row['pr_img_path_l'])){ unlink('..'.$row['pr_img_path_l']); } if(!empty($row['pr_img_path_m'])){ unlink('..'.$row['pr_img_path_m']); } if(!empty($row['pr_img_path_s'])){ unlink('..'.$row['pr_img_path_s']); } if(!empty($row['pr_img_path_xs'])){ unlink('..'.$row['pr_img_path_xs']); } $dir_to_remove = dirname(getcwd()).'/images/properties/'.$row['pr_img_id']; rmdir($dir_to_remove); } //Remove records for deleted id $deletedIDList = implode(); $query = "DELETE property, pr_imgs FROM property LEFT OUTER JOIN pr_imgs ON property.pr_id = pr_imgs.pr_id WHERE property.pr_id = '$del_id'"; $deleted = mysqli_query($db, $query); if($deleted){ header('Location:index.php'); //print $delete_query; } } $sel_pr_type = 1; // 1 = For Rent Residential, 2 = For Rent Commercial, 3 = For Sale $query = "SELECT * FROM property LEFT OUTER JOIN pr_imgs ON property.pr_id = pr_imgs.pr_id AND pr_imgs.pr_img_count = '0' ORDER BY pr_street ASC"; $result = mysqli_query($db,$pr_sel_query); $propertyList = ''; while($row = mysqli_fetch_assoc($result)) { $liveText = ($row['pr_live']) ? ' • <span class="live">Live</span>' : ''; $propertyList .= "<div class='property'>\n"; $propertyList .= " <div class='thumb'>\n"; $propertyList .= " <a href='/property_details.php?property={$row['pr_id']}'><img src='{$row['pr_img_path_s']}' width='100' height='100' /></a>\n"; $propertyList .= " </div>\n"; $propertyList .= " <div class='details'>\n"; $propertyList .= " <h4><a href='/property_details.php?property={$row['pr_id']}'>{$row['pr_title']}</a></h4>\n"; $propertyList .= " <ul>\n"; $propertyList .= " <li>Bedroom: {$row['pr_bedroom']} • Bathroom: {$row['pr_bathroom']}</li>\n"; $propertyList .= " <li class='adrs'>{$row['pr_street']}, {$row['pr_city']}, {$row['pr_state']} {$row['pr_zip']}</li>\n"; $propertyList .= " <li>Price: ${$row['pr_price']} 4 • Size: {$row['pr_size']} sq ft</li>\n"; $propertyList .= " <li>\n"; $propertyList .= " <a href='/admin/add-property.php?edit={$row['pr_id']}'>EDIT</a> •\n"; $propertyList .= " <a href='/admin/index.php?delete={$row['pr_id']}' class='red' onclick='return confirm('Are you sure you want to deletet this Property?');'>DELETE</a>{$liveText}\n"; $propertyList .= " </li>\n"; $propertyList .= " </ul>\n"; $propertyList .= " </div>\n"; $propertyList .= "</div>\n"; } include('../includes/head.php'); include('../includes/header.php'); ob_end_flush(); // ob_start() in /includes/login.php ?> <div class="content"> <div class="hldr"> <?php if($loggedin){ ?> <div class="left"> <h2><a href="/admin/">Admin</a></h2> <?php echo $propertyList; ?> </div> <div class="right"> <div class="sidebarHome"> <div class="sidebarHome"> <p><strong><a href="/admin/">Admin Home</a></strong></p> <p><strong><a href="add-property.php">Add Property</a></strong></p> <p><strong><a href="for-rent-res.php">Edit Properties for Rent - Residential</a></strong></p> <p><strong><a href="for-rent-com.php">Edit Properties for Rent - Commercial</a></strong></p> <p><strong><a href="for-sale.php">Edit Properties for Sale </a></strong></p> <p><strong><a href="index.php?logout=1">Log Out </a></strong></p> </div> </div> <div class="clear"> </div> </div> <?php } else { ?> <div class="fullpage"> <div class="login"> <?php print $error_msg; ?> <form method="post" action="index.php"> <label>Username:</label> <input type="text" name="user" class="txt" /> <label>Password:</label> <input type="password" name="pass" class="txt" /><br /> <input type="submit" name="login" value="Login" class="submit" /> </form> </form> </div> </div> <?php } ?> </div> <?php include('../includes/footer.php'); ?>
  12. That code is hard to follow and it seems you are doing some unnecessary things. For example this while($pr_row = mysqli_fetch_array($result)){ $pr_id[] = $pr_row[0]; $pr_type[] = $pr_row['pr_type']; $pr_live[] = $pr_row['pr_live']; $pr_title[] = $pr_row['pr_title']; $pr_street[] = $pr_row['pr_street']; $pr_city[] = $pr_row['pr_city']; $pr_state[] = $pr_row['pr_state']; $pr_zip[] = $pr_row['pr_zip']; $pr_price[] = $pr_row['pr_price']; $pr_bedroom[] = $pr_row['pr_bedroom']; $pr_bathroom[] = $pr_row['pr_bathroom']; $pr_size[] = $pr_row['pr_size']; $pr_img_path_s[] = $pr_row['pr_img_path_s']; } Why dump all the values from the query into separate arrays and why is the first value set using the numeric index from the results instead of the named index? That value HAS to have a field name - use that. And, you can just output the results when you read the records from the result set from the query. Let me try and provide a solution in a few minutes.
  13. Some tips to start out with: Never ASSUME which branch of your code is being executed. Any time you have branching logic (e.g. If/Else) and you are not getting the results you expect - Test It! Also, put comments in your code. Yes, it may make sense while you are writing it, but comments add a lot of value. When someone else is reviewing your code (such as those you are asking help from) it save a lot of time to read the comment and understand the context of the following code rather than having to look at the variables or functions and then backtrack through the code to see what the values are or what the functions do. Plus, when you have to go back into the code weeks, months, years later it will save you a lot of time as well. Indent your code to show the logical structure. I can see you did indent, but it is not very well structured (e.g. the closing brackets at the end for one example). Don't query "*" when you aren't using all the data. What is this? if($access == 1) { }else { //Code follows Why not just use if($access != 1) { //Put code here } Or, since I assume the value of $access will be either 1 or 0, you could just use if(!$access) { //Put code here } There are several gaps i the logic. I would suggest actually drawing the logic out on paper in a flow chart type format. This helps to ensure you cover all eventualities. For example, I'm not sure why you check the user ID in the session and the 'logged' value in the session? If you have a user ID in the session data doesn't that mean the user is logged in? Seems multiplicative. Plus, you should do the most important things first. The current logic checks if the user has rights to override maintenance before you check if the environment is in maintenance. Why not check if the environment is in maintenance first? If not, you can bypass the rest of the logic? Plus, since this is a maintenance mode script, you need to assume you are in maintenance mode if any query fails (i.e. the DB could be down). Here is a quick and dirty rewrite (not tested) <?php //Set to false to suppress debugging messages $__DEBUG = true; session_start(); include "config.php"; include "security.php"; //Create function to redirect function gotoMaintenance() { header('location:/maintenance/'); exit; } //Check if environment is in maintenance mode $query = "SELECT check FROM maintenance"; $result = mysql_query($query); //If query failed assume maintenance mode if(!$result) { if($__DEBUG) { echo "Query: {$query}<br>Error: " . mysql_error(); exit(); } gotoMaintenance(); } //Check maint mode value $server = mysql_fetch_assoc($result); //Check if server is in maint mode. if($server['check']) { //Set id to session value if set, false otherwise $id = isset($_SESSION['userinfo']['id']) ? $_SESSION['userinfo']['id'] : false; //Check if user has override $query = "SELECT bypassmaintenance FROM fuserights WHERE userid='$id'"; $result = mysql_query($query); //If query failed assume maintenance mode if(!$result) { if($__DEBUG) { echo "Query: {$query}<br>Error: " . mysql_error(); exit(); } gotoMaintenance(); } //Check user override status $user = mysql_fetch_assoc($result); if(!$user['bypassmaintenance']) { //User does not have override status if($__DEBUG) { echo "Server is in maint mode and user does not have override status."; exit(); } gotoMaintenance(); } } //If the code reaches this point . . . //Server is not in maintenance mode or user has maint mode override ?>
  14. OK, maybe I inferred a requirement to force a redirect after 30 seconds. Even so, the logic I provided will still apply but can be simplified. As LeJack has stated, cookies are the wrong solution since they reside on the user's PC and can be edited or deleted. You need to enforce this on the server side using data that is stateless - i.e. does not change due to expiring cookies or sessions. Here is a quick revise of what I posted previously that is much simplified. This is all off-the-cuff, so I'm sure there are some loose ends to resolve <?php //Get uesr ID if passed $userID = isset($_GET['userid']) ? $_GET['userid'] : false; //Create flag for expired status, default to true $expired = true; //Run query to get expiration time from DB for selected user $userIDSql = mysqli_real_escape_string($link, $userID); $query = "SELECT expiration FROM users WHERE user_id = '$userIDSql'"; $result = mysqli_query($link, $query); $user = mysqli_fetch_assoc($link, $result); //Will return false is no record returned //Verify a record was retrieved for selected user if($user) { //If the expiration value is NULL, then user has not tried to access the page yet if($user['expiration']=='') { //Add the expiration for the user $user['expiration'] = date('Y-m-d', time()+30); $query = "UPDATE users SET expiration = '$expiration' WHERE user_id = '$userIDSql'"; $result = mysqli_query($link, $query); } //Verify expiration time is in the future if(strtotime($user['expiration']) > time()) { $expired = false; } } //If expiration is true (user not found or expiration has passed) //Redirect to some other page if($expiration) { //If expiration is past current, redirect user somewhere header("Location: somewhere.php"); exit; } // . . . continue with displaying the page ?>
  15. @supertrooper. I gave you an answer for what you want to achieve. WHat, specifically, did you not understand? This forum is for people to get help with code they have written. I understand you didn't provide any, but there is an assumption that people coming here have some understanding of the technology. So, I'll be generous, here is some "sample" code. You still need to flesh it out though - specifically the parts I put // . . . where you need to build the DB queries to run. Also, I didn't put in any error handling in the case that a user ID does not exists. I'll leave that to you to figure out. <?php //Get uesr ID if passed $userID = isset($_GET['userid']) ? $_GET['userid'] : false; if(!$userID) { //No userid passed, redirect somewhere (Note, not valid if User ID can be '0' header("Location: somewhere.php"); exit; } //Run query to get expiration time from DB // . . . // . . . // . . . $expiration = "SET AS VALUE FROM DB OR FALSE IF NOT SET"; if($expiration!=false && $expiration <= time()) { //If expiration is past current, redirect user somewhere header("Location: somewhere.php"); exit; } if(!$expiration) { //Expiration not set, set it to 30 seconds from now and populate record in DB // . . . // . . . // . . . //Set value for page refresh $refreshSeconds = 30; } else { //Expiration is set in future //Calculate remaining seconds $refreshSeconds = $expiration - time(); } ?> <html> <head> <meta http-equiv="refresh" content="<?php echo $refreshSeconds; ?>"> </head> <body> <?php echo "Content goes here"; ?> </body> </html>
  16. Not sure what you are trying to achieve here. If you are trying to prevent the user from viewing content after that 30 seconds it is an impossible task. It would be very easy for someone to circumvent that if they have any clue about how the process works. But, since you asked: 1. On page load check to see if there is an expiration timestamp for that user ID in the database (we'll see how it gets there later). If no, skip to step 3 2A. If yes, AND if the current time is past the expiration, use a header() function to redirect to some other page. 2B. If Yes AND the current time is not past the expiration, display the page and set a META REFRESH tag with the number of seconds until the expiration timestamp 3. If the expiration timestamp is not set, insert/update the entry for the user setting an expiration timestamp 30 seconds in the future. Then display the content using a META REFRESH tag to redirect after 30 seconds.
  17. Step 1: echo [ "Addtion: " . $x ] + $y . "<br>"; PHP CONCATENATES the String "Addition" and the number 4 creating the string "Addition: 4", which results in: echo "Addtion: 4" + $y . "<br>"; //Step 2: echo [ "Addtion: 4" + $y ] . "<br>"; PHP ADDS the string "Addition: 4" with the number 2 Since the string is not a number, PHP converts it to one. Since it begins with an alpha character it converts it to 0. Thus, you get [ 0 + 2]. Result: echo 2 . "<br>"; Step 3: echo [ 2 . "<br>" ]; PHP CONCATENATES the Number 2 and the string "<br>" Result echo "2 <br>";
  18. That code works perfectly fine. $name = "Address"; if (preg_match("/ss$/", $name)) { $name = $name . "'"; } echo $name; //Output Address' I'm guessing that the values may not contain what you think they contain. Are there any spaces or other non-printable characters at the end? You may want to trim() them first. But, regular expressions are slow and should be avoided if there are string functions you can use as an alternative. Also, there is no need to use preg_match() function to then add an additional character. You could just use the preg_replace() function. But, I would not do this with RegEx anyway. I would use string functions. Just use substr() to get the last two characters and see if they are both 's'. $name = "Address"; $name = trim($name); if(strtolower(substr($name, -2))=='ss') { $name .= "'"; } echo $name; //Output Address' If that does not work, then do a var_dump() on $name before the function and post the results here.
  19. SELECT user, COUNT(car) as car_count FROM table_name GROUP BY user ORDER BY car_count
  20. As I stated, I didn't test that code. I don't have your DB to test it with. But, if you are going to modify code - pay attention to what you are doing. You changed some things that should not. For example you changed the field names using () instead of [], which would prevent them from being correct arrays. One problem with the original code I posted was that the variable $formHTML to hold the form fields was using "=" instead of ".=" to concatenate the data. So, you would only end up with the very last value - a single "<td>". Try this <?php //Connect to DB $hoster="xxx"; $username="xxx"; $password="xxx"; $db_name="xxx"; mysql_connect("$hoster", "$username", "$password") or die("Unable to connect to DB server: " . mysql_error()); mysql_select_db("$db_name") or die("Cannot select DB: " . mysql_error()); //If form was posted, process the data $updateErrors = array(); $errorMsg = ''; //Set default error message if($_SERVER['REQUEST_METHOD']=='POST') { foreach($_POST['records'] as $id => $record) { $query = "UPDATE gbook SET www='{$record['www']}', email='{$record['email']}', pwd='{$record['pwd']}' WHERE id='$id'"; $result = mysql_query($query); if(!$result) { $updateErrors[] = $id; } } //If no errors, redirect if(!count($updateErrors)) { header("location:editmulti4.php"); exit(); } $errorMsg = "Updates to the following record IDs failed: " . implode(', ', $updateErrors); } //Create the form $query = "SELECT id, www, email, pwd FROM gbook"; $result = mysql_query($query) or die("Error running query: " . mysql_error()); $formHTML = ''; while ($row = mysql_fetch_assoc($result)) { $formHTML .= "<tr>\n"; $formHTML .= "<td>{$row['id']}</td>\n"; $formHTML .= " <td><input value='{$row['www']}' name='records[{$row['id']}]['www']' type='text' id='www'></td>\n"; $formHTML .= " <td><input value='{$row['email']}' name='records[{$row['id']}]['email']' type='text' id='email'></td>\n"; $formHTML .= " <td><input value='{$row['pwd']}' name='records[{$row['id']}]['pwd']' type='text' id='pwd'></td>\n"; $formHTML .= "</tr>\n"; } ?> <html> <body> <div style="color:#ff0000"><?php echo $errorMsg; ?></div> <form name="form1" method="post" action=""> <table width="500" border="0" cellspacing="1" cellpadding="0"> <tr> <th><strong>Id</th> <th><strong>www</th> <th><strong>email</th> <th><strong>pwd</th> </tr> <?php echo $formHTML; ?> <tr><td colspan="4"><button type="submit" id="submit">Submit</button></td></tr> </table> </form> </body> </html>
  21. You are storing the entire HTML code to your database? Why not just store the variable parameters separately and build the URLs dynamically. That makes it much more flexible. For example, you might just store three values: height, width and code. Then when you need to output the HTML you would build the entire iframe using those three values.
  22. Some other notes: 1. Don't use mysql_ functions. They are deprecated. Use either mysqli_ or PDO. I didn't make any changes though, because I am too lazy at the moment. 2. Do not use "SELECT *" and then a row count to determine the number of records. You are making the server select ALL data in the entire table just to get a count. Use the SQL COUNT() function. In fact, never use "*" for your select unless you absolutely need every column. 3. Why do you have nested tables? 4. Don't use TD tags for the table headers. Use TH tags - that's what they are for and will be bold and centered by default! 5. The logic is a mess. You go through all the logic to build the page then, at the end, you have a line that may redirect the user to another page. That should be before any logic to create the page. Otherwise, it is a complete waste of effort if you do redirect. 6. Don't run queries in loops. Always try to create ONE query. I didn't modify it here because I think it would confuse you. 7. Indent your code so you can "see" the structure 8. The ID should not be an input field. Here is a complete rewrite. I did this on-the-fly with no testing. So, there may be a few minor errors. But, this is a much better logical workflow than there was previously <?php //Connect to DB server and select DB $hoster="db.mkq.de"; $username="dbxxxxxx"; $password="xxxxxx"; $db_name="xxxxxx"; mysql_connect("$hoster", "$username", "$password") or die("Unable to connect to DB server: " . mysql_error()); mysql_select_db("$db_name") or die("Cannot select DB: " . mysql_error()); //If form was posted, process the data $updateErrors = array(); $errorMsg = ''; if($_SERVER['REQUEST_METHOD']=='POST') { foreach($_POST['records'] as $id => $record) { $query = "UPDATE gbook SET www='{$record['www']}', email='{$record['email']}', pwd='{$record['pwd']}' WHERE id='$id'"; $result = mysql_query($query); if(!$result) { $updateErrors[] = $id; } } //If no errors, redirect if(!count($updateErrors)) { header("location:editmulti3.php"); exit(); } $errorMsg = "Updates to the following record IDs failed: " . implode(', ', $updateErrors); } //Create the form $query = "SELECT id, www, email, pwd FROM gbook"; $result = mysql_query($query) or die("Error running query: " . mysql_error()); $formHTML = ''; while($row = mysql_fetch_assoc($result)) { $formHTML = "<tr>\n"; $formHTML = " <td align='center'>{$row['id']}</td>\n"; $formHTML = " <td align='center'>\n"; $formHTML = " <input name=\"records[{$row['id']}]['www']\" type='text' id='www' value='{$row['www']}'>\n"; $formHTML = " </td>\n"; $formHTML = " <td align='center'>\n"; $formHTML = " <input name=\"records[{$row['id']}]['email']\" type='text' id='email' value='{$row['email']}'>\n"; $formHTML = " </td>\n"; $formHTML = " <td align='center'>\n"; $formHTML = " <input name=\"records[{$row['id']}]['pwd']\" type='text' id='pwd' value='{$row['pwd']}'>\n"; $formHTML = " </td>\n"; $formHTML = "</tr>\n"; } mysql_close(); ?> <html> <body> <div style="color:#ff0000"><?php echo $errorMsg; ?></div> <form name="form1" method="post" action=""> <table width="500" border="0" cellspacing="1" cellpadding="0"> <tr> <th><strong>Id</th> <th><strong>www</th> <th><strong>email</th> <th><strong>pwd</th> </tr> <?php echo $formHTML; ?> <tr> <td colspan="4" align="center"><button type="submit" id="submit">Submit</button></td> </tr> </table> </form> </body> </html>
  23. FYI: Using an input button as a submit button to check if the form was submitted is not the best way. It's possible to submit a form without clicking the button. You should instead check the request method if($_SERVER['REQUEST_METHOD']=='POST') And, what are you expecting to "happen". There is nothing in your code that would produce output. Based on the other undefined variables that ch0cu3r pointed out, I would expect you would get new records with empty values.
  24. No, it is not. A value is submitted through a POST or GET request through one of the global variables such as $_POST['field_name'] or $_GET['field_name']. $submit is a variable that would need to be defined.
  25. Do you "have" to convert? No. But, the mysql_ extension is deprecated and will be completely disabled in a future version of PHP. Assuming you are on a hosted server, your host could update to a newer version of PHP at some point that would break your code. Since it still works in current PHP and hosts typically don't upgrade right away (or maintain support for older versions) it's likely it won't be an issue for quite some time. But, it's much better to be proactive and do it when you have time instead of being surprised and having to scramble when it does happen. You are simply using mysql_result to get the value from queries that should be returning one record with one value. There is a mysqli_ method, but it is a different beast from the mysql_result function. I think the code needs a complete overhaul, there is on simple solution - create your own function. Create a function that takes the result of the query and uses the available mysqli_ functions to get the first record, then return the first value. If you were to look at the manual for the mysqli_result method you would see that the first entry has a comment specifically related to your issue and provides the exact same suggestion and sample code. You can just add that function to your code and rename all the mysql_function calls to whatever you decide to name the function.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.