Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
Pull amount of rows in MYSQL table and display?
Psycho replied to jackmcnally's topic in PHP Coding Help
I gave you a query to run. You can't simple write a query into the PHP code and expect it to do anything. This is very basic stuff. Besides you shouldn't have different DB connection scripts. You should only have one that any page which needs DB access should include. $con = mysql_connect("localhost","xxxxx","xxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("xxxxx", $con); $query = "SELECT COUNT(*) FROM xxxxx"; $result = mysql_query($query); $count = mysql_result($result, 0); echo "{$count} have signed up. Will you? "; mysql_close($con) -
There is nothing wrong with the code with regard to syntax, but as Pikachu2000 stated it really doesn't make sense for what you seem to be wanting to accomplish. However, I will state that there are issues witht hat code aside from syntax and purpose. 1. If you are using LIMIT 1 on the query why are you using a while loop. 2. Why extract the value and then add 1, just add 1 in the query. $query = "SELECT ArticleID + 1 FROM test_top ORDER BY ArticleID ASC LIMIT 1"; $result = mysql_query($query) or die(mysql_error()); $ArticleID = result($result, 0); But, really, what you are doing just doesn't make sense.
-
If the application " . . . won't accept apostrophes." Then, I suspect that he is not properly escaping the input prior to using them in a query. So, the queries are likely failing. You would have to go through the files to find anywhere a variable is used in a query and make sure that mysql_real_escape_string() is used on the variable before being used in a query.
-
Depending upon the level of error reporting some errors/warnings may be displayed while others are not. For example, if you try to reference a variable that has not been set, PHP may just assume a value of '0' and not display the warning. It looks like the error reporting level on your current machine is higher than the previous one you used. Basically, the person who coded the app did so with either little knowledge about these problems (because he had a low threshold for error reporting) or coded it with the intent of having a low error reporting level so he could be lazy in his coding. You could try and adjust the error reporting in your PHP.ini file. Or, better yet, notify the author of the problem. There is a support link on the url you provided.
-
Having an error such as "Could not insert admin" for users when in a production environment is fine. But, when you are in development you need to provide error handling that will help you find and fix errors. This will display the query and the error returned from MySQL: $insert2=mysql_query($insert) or die("Query: {$insert}<br>Error: " . mysql_error());
-
if($checkProfile) { $query = "SELECT COUNT(`id`) FROM `members_profile` WHERE `id` = '{$_SESSION['face']}'"; $result = mysql_query($query) or die(mysql_error()); $id_count = mysql_result($result, 0); if(!$id_count) { //ID does not exist } else { //ID does exist } }
-
I'm more than willing to help you, but you are still not really providing any useful information. If you want free help, then take some time to explain your problem. The questions you are asking probably make perfect sense to you since you have the context of the steps you have taken thus far and know what it is you are trying to accomplish. But, the question is vague to us because we don't have that context. If $_SESSION['face'] is the value from the "other" table, then your code above (while not the appropriate implementation) would work to determine if there are any records with that value in the "member_profiles" table. Also, since you already have the value from the first table, your question about is misleading. So, again, I will ask what problems are you experiencing? EDIT: OK, I see your error (basic PHP string concatenation). You should definitely be getting some type of error with that code, so why did you not provide it?
-
And what problems are you experiencing? Are you getting errors, what? I definitely see problems in your logic, but you can at least take the two seconds necessary to STATE what, exactly, you need help with. You state But, I don't see a "table1" or "table2" anywhere in your code. I assume "members_profile" is one of the tables, but what is the other table and what is the field of the foreign key reference? Do, you just want ONE check for both tables (which would require just one query) or are you wanting to check the "members_profile" table and then the other table?
-
You can programatically disable magic quotes at runtime if needed. The manual provides an example script that will check if magic quotes are enabled and, if so, will run stripslashes(). Even if your current host doesn't have magic quotes enabled if they were to do so in the future or if you moved to a different host that does, your code will still work. Also, regarding validating/sanitizing your variables, mysql_real_escape_string() will protect your queries from SQL Injection (and should be a last step). But, it is not all that you need if you want to prevent errors. As the name implies, mysql_real_escape_string() is for sanitizing string data. If you have a DB field that requires integer values and a non-numeric value is passed, mysql_real_escape_string() will not prevent the query from failing. It is sometimes a grey line as to where validation ends and sanitizing begins. Here are some suggestions on the steps I typically take: - Always use trim() on user submitted values (unless there is a valid reason not to) before doing any validations on length. Otherwise, a space entered into a required field would pass validation. - Be careful about using any other functions that will modify the user input prior to validations [striptags(), htmlspecialcharacters(), etc.]. Only run those after initial validation is done unless you have a valid reason for doing otherwise. In fact, I almost never run those type of functions on input before storing in the database. Instead I run it at the time I pull the values from the database when I display them on the page. This makes the data device independent. So, if I was to output the data to an XML feed or something other than an HTML page, converting characters to their HTML entities would not make sense. - For any data that should be a numeric value (int, float, etc) use an appropriate PHP function to convert the value to that type of numeric value. Then validate that the value is appropriate. - Always do PHP validations before DB validations. For example, if a user submits a form for data to update an existing record, one fo the values will be the primary key for the record - so you may want to validate that the record exists before running the update. But first, you should validate that all of the update data is valid first (required fields have input, amounts are numbers, etc.) before checking if the record exists. DB transactions are one of the more costly processes.
-
This could probably be more efficient, but it works for what you want. function getListOfMonths($startDate, $endDate) { //Get timestamps for the first of each date passed $startDateTS = strtotime($startDate); $endDateTS = strtotime($endDate); //Some basic validation if(!$startDateTS || !$endDateTS || ($startDateTS > $endDateTS)) { return false; } //Get month and year vars $startMonth = date('m', $startDateTS); $startYear = date('Y', $startDateTS); $endMonth = date('m', $endDateTS); $endYear = date('Y', $endDateTS); //Normalize the dates to 12noon on the 1st of the month $startDateTS = mktime(12, 0, 0, $startMonth, 1, $startYear); $endDateTS = mktime(12, 0, 0, $endMonth, 1, $endYear); //Get the months between (inclusive) $months = array(); while($startDateTS <= $endDateTS) { $months[] = date('m-Y', $startDateTS); $startDateTS = mktime(12, 0, 0, ++$startMonth, 1, $startYear); } return $months; } $dates = getListOfMonths('11/12/2011', '1/1/2012'); print_r($dates); Output: Array ( [0] => 11-2011 [1] => 12-2011 [2] => 01-2012 )
-
OK, looking at your update script I see you are giving the input fields all the same name! They need to have individual names and/or be array indexes. Here is what I would do: Create all the input field as array names and use the record id as the index for those arrays. something like: echo "<input type='text' name='name[{$rowmembers['id']}]' value='{$rowmembers['username']}' /><br>\n"; Then in your script to process the changes, just do a foreach() on one of the fields and us the id to reference all the fields to update that record foreach($)POST['name'] as $id => $name) { $firstName = $_POST['first_name'][$id]; $lastName = $_POST['first_name'][$id]; $email = $_POST['first_name'][$id]; //sanitize and validate input then run update query }
-
You can start by making your drop-down to NOT be hard coded. At the very least make your options a hard-coded array, then build the select list dynamically so you can auto-select the appropriate value. Here is some rough sample code <?php $selectedValue = 'b'; $colorList = ( 'r' => 'Red', 'g' => 'Green', 'b' => 'Blue', 'y' => 'Yellow', 'p' => 'Purple' ) $colorOptions = ''; foreach($colorList as $value => $label) { $selected = ($selectedValue==$value) ? ' selected="selected"' : ''; $colorOptions .= "<option value='{$value}'>{$label}</option>\n"; } ?> Select a color: <select name="color"> <?php echo $colorOptions; ?> </select>
-
I would say it is impossible to build any type of captcha - or any spam prevention method - that is foolproof. Anything hurdle could be overcome with the right tools and enough time. A math captcha could be pretty easy to overcome. The code would just need to be able to identify the values and the operation to be performed (add, subtract, divide, etc.). "How do they know what variables to send?" Easy, they just look at your HTML source code for the form and they can see exactly what fields will be sent in the POST/GET data. But, unless you have a site where someone wants to take the time to build the logic to overcome your prevention method you will be fine. Most spammers are going to want to find solutions to overcome the ready-made captchas that are implemented across many sites that they can reuse rather than build a solution specific to one site. SO, even a simple match captcha "should" suffice. Well, unless your site will become the next Facebook, but in that case you would have the resources to pay people to do it.
-
Well, you still want to sanitize the values before using in a query. Since these are 'id' values I assume they are integers. So, you shouldn't have been using mysql_real_escape_string() to begin with. That function is for "string" data. For integers you could use something like intval(). If the value cannot be interpreted as an integer, intval() will return 0. You could either run your query with any 0's that are produced - since there would be no matching records they wouldn't do anything. Or, you could remove the 0 elements using array_filter. Also, don't create your queries directly in the mysql_query() function. Instead, create them as a string variable so you can echo them to the page during the debugging process. $updateIDs = implode(', ', array_filter(array_map('intval', $_POST['checkbox']))); $query = "SELECT * FROM users WHERE id IN ({$updateIDs})"; $members = mysql_query($query);
-
What makes you think that there is a performance problem with that code? more than likely the problem is a bandwidth issue - especially fi you are using very large images or a problem with the javascript. But, since you ask, here are some things you can do - but most likely these will only provide marginal performance benefits which you won't even see. 1. List out the fields in your SELECT query instead of using '*'. Selecting all the fields when you don't need them is a waste of resources. 2. I don't know if your query is returning only one record or multiple, but you are only using the first record. So, if you are getting more than one record and only using the first, then limit your query to only one using 'LIMIT' 3. Don't assign a value from the query result to another variable only to use that variable once. Just use the value from the fetched record. 4. Your if/else statement to determine the 'sessions" text is only needed in the last else statement for the no pics value. So, put that code within the last else statement so it isn't executed unnecessarily. 5. Not sure if this would help, but it would make the code cleaner. I see you are using three variables in the same configuration multiple times in the while loop. I would assign them to a single variable and use that in the output. <?php $g = mysql_real_escape_string($_GET['g']); $query = "SELECT Day_Played, Opponent, no_Pics, Year_Played, Day_Played, Sessions FROM pinkpanther_games WHERE Gallery_no = '$g' LIMIT 1"; $results = mysql_query($query) or die("Query failed ($_query) - " . mysql_error()); $row = mysql_fetch_assoc($results); $title = "<h1>{$row['Day_Played']} vs {$row['Opponent']}</h1>"; $links = ''; if ($row['no_Pics'] == 0) { $links .= "<li> <a class='thumb' href='../images/nopics.jpg' title=''><img src='../images/nopicsthumb.jpg ' /></a></li>"; } else if ($row['no_Pics'] == 10000) { $links .= "<li> <a class='thumb' href='../images/coming.jpg' title=''><img src='../images/comingthumb.jpg ' /></a></li>"; } else { if ($row['Sessions'] == 1) { $sessions = "Session1"; } else { $sessions = "Session2"; } $y = 1; while ($y <= $row['no_Pics']) { $rootPath = "{$row['Year_Played']}/{$sessions}/{$row['Day_Played']}"; $links .= "<li> <a class='thumb' href='../images/Sections/pinkpanthers/{$rootPath}/{$y}.jpg' title=''><img src='../images/Sections/pinkpanthers/{$rootPath}/thumbs/{$y}.jpg ' /></a><div class='caption'><div class='download'><a href='../images/Sections/pinkpanthers/{$rootPath}/big/{$y}.jpg ' target='_blank' />Download</a></div></div></li>"; $y ++; } } ?> <div id="Info"> <div id="page"> <div id="container"> <?php echo $title; ?> <!-- Start Advanced Gallery Html Containers --> <div id="gallery" class="content"> <div id="controls" class="controls"></div> <div class="slideshow-container"> <div id="loading" class="loader"></div> <div id="slideshow" class="slideshow"></div> </div> <div id="caption" class="caption-container"></div> </div> <div id="thumbs" class="navigation"> <ul class="thumbs noscript"> <?php echo $links; ?> </ul> </div> <div style="clear: both;"></div> </div> </div> <div id="footer"></div>
-
How to add "id=" to a conformation statement.
Psycho replied to Matt Ridge's topic in PHP Coding Help
You should pass variables using a name/value pair echo "<p>Your comments have been successfully entered. Would you like to <a href=\"1-1.php?id={$_GET['id']}\">view the final report</a>?</p>"; -
You are passing an array $_POST['checkbox'] You cannot perform mysql_real_escape_string() on an array. This line of code first tries to run mysql_real-escape_string() on the array and then do implode. $update = implode ("','", mysql_real_escape_string ($_POST['checkbox'])) I'm guessing the mysql_real_escape_string() is returning false which is why implode() is producing the error you displayed above - can't perform implode() on the boolean false. But, seriously - you named your checkbox inputs 'checkbox'?! Name them something descriptive such as 'member_id' fior crying out loud. Also, you cannot duplicate element ids in an html page, so you can't use 'checkbox[]' as the id for the fields. Instead, just append the id to the id 'checkbox_{$rowmembers['id']}'
-
yes, you can have a switch() inside a switch() just like you can have a while() inside a while(), an if() inside an if(), etc.
-
Pull amount of rows in MYSQL table and display?
Psycho replied to jackmcnally's topic in PHP Coding Help
[quote author=jackmcnally link=topic=348213.msg1643088#msg1643088 date=1321769606 I have a 'pre-release' sign up form, where people put in their email address and name, and it transmits to a MYSQL database. That's working fine. If you have what you say you do above, then you should already know how to do all that. Unless that is you didn't write the code for the sign up form. -
Pull amount of rows in MYSQL table and display?
Psycho replied to jackmcnally's topic in PHP Coding Help
SELECT COUNT(*) FROM table_name -
No idea what you mean. But a switch will work wherever you put it - assuming you have coded it correctly.
-
And, I'll throw this out there . . . even though you only have three options right now, using a series of if . .elseif . . else statements can get messy. This is exactly what the switch() operator is for. This may look to be more work because of the additinoal lines of code, but it will be much more flexible and less error prone. switch($_SESSION['collection']) { case 'dropoff': echo "Please drop it off with us"; break; case 'collect': echo "Please collect it from me"; break; case 'ship': default: echo "Please ship it to you"; break; }
-
Problem sending data from a html form to a php file
Psycho replied to ddiddy's topic in PHP Coding Help
I assume you are getting that error when you FIRST load the page and not when you actually submit the form. That is because of your if() condition if($_POST['numar']!="") The PHP parser is throwing a warning because it can't test $_POST['numar'] because it doesn't exist (if you haven't POSTed the form). Instead you should use isset() if(isset($_POST['numar'])) Although you should probably also run trim on the value and test that it's not empty in the validation logic. -
OK, I just took a closer inspection of your code and saw this var_dump($legacyEntityIds); // Loop through all legacy video entity_id's for ($i = 0; $i < $legacyEntityIds['data']['ENTITY_ID']; $i++) { You have a for() loop that continues while $i < $legacyEntityIds['data']['ENTITY_ID'] but $legacyEntityIds['data']['ENTITY_ID'] is an array - it is not the length of the array. Beside, you should NOT (normally) be using a for() loop with a dynamic variable for the index to process an array. You should be using a foreach loop. Also, running queries in loops is very poor implementation.
-
All I see is an extra '<br>' tag at the end. Are you sure that tag isn't being echo'd to the page in some code after your for() loop? You can easily verify if it is due to an empty/null value magically being produced in your array. Change the line that produces the output to this echo "[{$legacyEntityIds['data']['ENTITY_ID'][$i]}]<br />\n"; If the problem is due to an empty item being added to the array, then your output will look like this (note the [] in the last line): [1681799]<br /> [1681872]<br /> [1681871]<br /> [1681870]<br /> [1681869]<br /> [1681868]<br /> [1681867]<br /> [1681866]<br /> [1681865]<br /> [1681864]<br /> []<br /> However, if that last BR tag is not generated in that loop then the last lines will look like this [1681867]<br /> [1681866]<br /> [1681865]<br /> [1681864]<br /> <br />