-
Posts
5568 -
Joined
-
Days Won
201
Everything posted by mac_gyver
-
Display images by id into different sections on page
mac_gyver replied to glendango's topic in PHP Coding Help
following along with youtube videos isn't going to teach you how to produce a program that does what you want. to do that, you need to plan what result you want, then design, write, test, and debug the code that implements that plan. the task of producing the edit form involves retrieving the existing data (this should be done all at once, before the start of the html document), produce a form that has form fields that correspond to that data, populate the form fields with the existing data, where possible, and in the case of type='file' fields, where this is not possible, display the current image next to the form field. i do have one addition to what has already been posted. if you want to allow a maximum of three images, and since there can be from zero to three rows stored in the portal_images table for any particular id value, you would retrieve and store the portal_images data into a php array variable, using the image position as the array index (you indicated in the previous thread that there is a main image and two sub-images). then loop to produce the type='file' form fields/display the existing images, would need to loop three times, and only display an image if there is one in this php array variable for that position. so, what result are you trying to produce, specific to the type='file'/display existing images, using pseudo code - // query for and retrieve the existing data here, storing the results in php variables. // store the portal_images data in a php array variable, such as - $portal_images_result, with the position, 1,2,3, as the array index value. if the position to specific image mapping matters, your portal_images table needs a position column where you can assign and maintain the position for each set of images (i realize that your original three column design did this, but by storing each image in a separate row, you have a general purpose design that can support any number of images and has simpler code and queries to insert, update, and retrieve the data.) <form method='post' enctype='multipart/form-data'> // you need one opening form tag before the start of the first form field. i'm going to assume you are submitting the form data to the same page that the form is on, hence, no action='...' attribute in the form tag other form field types go here... // at the point of producing the type='file' form fields and displaying existing images - <?php // define configuration values $number_portal_images = 3; $portal_image_path = "images/"; // loop to produce the type='file' form fields and display existing images for($x = 1; $x <= $number_portal_images; $x++) { echo "Photo $x: "; echo "<input type='file' name='file[$x]'>"; if(isset($portal_images_result[$x])) { echo "<img src='$portal_image_path{$portal_images_result[$x]}' alt='Change Image by Clicking Browse' width='247' height='142'>\n"; } else { echo "there is no saved image for this position\n"; } echo "<br>"; }?> other form field types, such as a submit button </form> // you need one closing form tag after the last form field -
your logic doesn't make sense and won't work as written. if your passwords are hashed, then the sql query will never match a row (because the password column value will never be equal to the submitted $lpass value in the sql query). the use of the > 0 that Sepodati pointed out is causing $row to be a Boolean value and none of the $row elements will exist, so all the code using them won't work. i recommend that you start over and write just the code you need (you have several statements that aren't being used and even more that are not needed) to accomplish this task - Keep It Simple (KISS.) for this task, your form processing code needs to - 1) check if the current visitor is already logged in. if they are, there's no good reason to run the login form processing code. either display a message or redirect them elsewhere on your site. 2) make the database connection, without outputting any connection errors to the visitors on your site. the way to handle connection and other types of database statement errors is to use exceptions, let php catch the exception, and let php use it's error_reporting, display_errors, and log_errors settings to control what happens with the actual error information. when learning, developing, and debugging code, you should display the error information. when on a public/live site, you should log the error information. 3) detect that a post method form was submitted using simple generic code. just test if $_SERVER['REQUEST_METHOD'] == 'POST'. there's no good reason to write out code testing if all the form fields are set, that you have to change to match each different form. 4) trim and validate the input data. if the trimmed data is empty, there's no point in using it. if you store the validation errors in an array, you can validate all the inputs at once and use the array as an error 'flag'. if the array is empty, there are no errors. if the array is not empty, there are errors. only store the text of the error message in the array. 5) if there are no validation errors, use the submitted data. 5.1) produce and execute a prepared query to find if the email matches a row in your database table, fetch the row if found. if the row wasn't found, the email didn't match. setup an 'invalid login' error message. 5.2) check if the hashed password stored in the database table matches the submitted password. if the password didn't match, setup an 'invalid login' error message. 5.3) if both the email and password values match, set a session variable with the corresponding user's id (an auto-increment column in the database table.) the reason for NOT storing the email as the user's identifier in the session variable is because the value cannot be edited (directly by a moderator/administrator or by the user via a proper emailed link verification) and take effect without requiring the user to log out and back in again. --- to detect if the current visitor is logged in or not, test the session variable holding the user's id. if the session variable isset(), there's a logged in user and their id is the value in the session variable. if it is not set, the visitor is not logged in. if you want to get any related user information, such as their username, email, or permissions, use the user's id from the session variable and run a select query against the appropriate table(s). unfortunately, the php mysqli extension you are using is not the best choice, especially if using prepared queries. if you can, switch to use the php PDO extension. it is much simpler and more constant to use over the php mysqli extension. also, Don't Repeat Yourself (DRY). you have repeated the section of html markup for each different error message. what happens if you want to change the html markup for the error display? you will have to change it every place you have used it. if you follow the recommendation of using an array to hold the validation error messages (only the text of the message), you would loop over that array when displaying the errors and output the text of the message in the html markup you have defined. the html markup will only exist once and any changes will only need to be made in one place.
-
you have also mis-capitalized SESSION in the php variable usage. php variable names are case-sensitive. $_SESSION is not the same as $_Session. you would have been getting a php undefined variable error to help identify this problem. do you have your development system properly set up with php's error_reporting set to E_ALL and display_errors set to ON (preferably in the php.ini, so that you won't have to remember to set them) so that php will help you by reporting and displaying all the errors that it detects?
-
Display images by id into different sections on page
mac_gyver replied to glendango's topic in PHP Coding Help
the code you put inside the while(){...} loop braces would be one instance of the html markup that you want to repeat. if you have a need for a sequential counter, for things like Photo 1, Photo 2, ... and for DOM id's, you would set up a variable before the start of the loop, echo that variable any place you need the value, then increment the variable for the next pass through the loop. next, if you aren't actually using each of the the DOM id's, there's no good reason to have them in your html markup. they are just adding clutter and code that you must maintain. you also need one set of <form ...> </form> tags around all of the form fields. you are currently producing multiple opening <form ...> tags that aren't doing anything after the first one, since nested forms are invalid markup. you need to use prepared queries when supplying data to an sql query statement. you can research in the php.net documentation or on the web to find out what that means. if there isn't a $_GET['update']/$id value when your code is executed, you should not run any of this code. you need to validate all input data and only use it if it exists and is valid. you should also use an array name for the form field's name, so that you will receive an array of submitted files data that you can simply loop over to process. -
no matter what you do in the client/browser, your server-side form processing code will still need to determine what it should do if an image was successfully uploaded, if no image was selected, or if there is a different type of upload error, some of which will have a non-empty ['name'] element. and, in looking at your database table design, you should not be storing image data in multiple columns in a single row, but a separate row for each image. which triggered a thought. if you are replacing an existing image, why don't you just use the same destination name and let move_uploaded_file() replace the existing file with the new one?
-
the ['name'] element will be empty for reasons other than no file being selected. you must always use the ['error'] element in determining what to do with the submitted data. if a file isn't selected for a type='file' field, the ['error'] element for that field will be UPLOAD_ERR_NO_FILE (a value of 4.) your form processing code would need to detect that error value not include that that particular db table column in the update query (or perhaps more simply update it to its existing value.)
-
@drfred, re: post #1 - the first form, with the quotes is correct. the second form works, but throws two php errors about undefined constants, then php assumes you meant to enclose the two separate parts in quotes, the finally tries to include a file named - 'dbconfigphp' if whatever the actual error was and what you found that fixed the problem had been stated, we could have posted relevant help and then someone else that found this thread could have benefited from the solution you found yourself. re: post #3. you have missed the point of benanamen's post and you have a misunderstanding about how web servers work. if you have a web site that has hundreds of places where you are doing the same thing, you have a poorly designed implementation, that has taken a ton of extra hours creating and then more extra time when making any changes. if all these different places you are doing the same thing are just different pages on your site, with different content, you need to instead use a content management system, so that you only have a single main file that displays the different content. this will greatly reduce the amount of work you have in creating new content and in making any changes to the site. each request to a web server is completely separate from all other requests. each request to a page that makes a database connection in the code causes one connection to be made (hopefully your code isn't making more than one connection on any page), then the connection is closed either when you explicitly close it with code or php will automatically close it when the script execution ends. database connections don't persist between requests (actually they can, under very specific server setups, but only the client/server connection is kept open, the database session is not maintained.) re: the posted code - your code is open to sql injection (you need to use prepared queries) and you are storing too much in session variables. for the user's data, you should only store the user id in a session variable, to identify who the visitor is. you should query on each page request for the user's permissions, so that they can be edited by a moderator/administrator and they will take effect on the next page request. by storing the permissions in session variables, they will remain in effect until the visitor logs out and back in again. if you have a visitor that is posting spam, your current method won't allow the permission to post to be revoked.
-
the first paragraph in my reply told you what's causing the problem. the second paragraph told you how to get php to help you find the cause of the problem and to find all kinds of other simple mistakes you are likely to make while learning, developing, and debugging code. the reason no one told you what keys to press to make the problem go-a-way is that it is much better if you set up your development system to report and display all the errors php detects, so that you can find and fix all these simple problems in your code rather than expect others to do it for you.
-
you are getting messages combined because you are not initializing the message variable, which would be producing a php error the first time you reference it. one of the biggest things you can do to get php to help you, is to set php's error_reporting to E_ALL and display_errors to ON (preferably in the php,ini on your development system), so that php will report and display all the errors it detects. next, don't design database tables with columns like itemx, stuffx, nor write php code with numerical variable endings, or with code that isn't being used. use meaningful names for database columns and don't repeat code that's performing the same processing. you should run one query that gets the data you want in the order that you want it. the only apparent difference between the two sets of code that you have now is the subject line. you should only write program logic for things that are different, not duplicate all the logic for each possible value. as you loop over the result set from the single query, just use conditional logic to determine which subject to use (and any other actual differences between the two messages.)
-
why not just produce 'edit' links, in the first piece of code, that would have the id as a get parameter on the end of the each link? next, why are you making an in-line pdo connection, a mysql_ connection, and an PDO connection via an included file? this is just making more work and more different sections of code that you must keep track of. a point of programming, isn't to use the most code to accomplish a task. programming is already a tedious typing task, you should be looking for ways of reducing the amount of work you have to do to produce code. if you have code in an external .php file that's making a PDO connection, just use that connection in all cases and if you eliminate the select/option menu in favor of links, the code using the obsolete mysql_ statements will go-a-way. any post method form processing code needs to be near the top of your file, before the start of your html document.
-
so, have you set up your development environment with php's error_reporting set to E_ALL and display_errors set to ON, preferably in the php.ini, since putting the setting in your code won't help with php syntax errors, so that php will help you by reporting and displaying all the errors it detects. then, have you started over, designing, writing, and testing your code, one small functional piece at a time, since there are too many problems in the current code to waste the time trying to fix it. no one here is going to spoon-feed you all the basic information you have skipped learning. we are here to help with actual programming problems. if you need help learning the basic information that is a prerequisite to writing your own code that actually works, you need to take a programming class, hire a tutor, or work through and internalize the information in some beginner php online tutorials. if you are not at the point of understanding the terminology being used, you are not at the point of even asking questions, because you won't understand the answers. the wording/terminology used in any particular subject is not to exclude people, but to prevent needing to write out books worth of information when explaining each concept. this is why books have been written, to cover the basics. you need to go and do some book learning and some experimenting on your own so that you get up to speed with the subject you are trying to participate in.
-
display data in input text and Option from my sql using php
mac_gyver replied to maideen's topic in PHP Coding Help
the value attribute in your text form field is misspelled. it's not values as to how to select the correct option choice, you would output the selected attribute in the correct <option ,,,> tag, by comparing the current value being output inside the while loop with the value in $paramhead. -
issue in inserting data from dropdown into mysql table
mac_gyver replied to maideen's topic in PHP Coding Help
actually, no, it's not. there are two problems with the form - 1) the value attributes, that have already been pointed out. 2) the name you have given the submit button is the same as the select field name and only the last field with the same names will be used, so, you are getting the submit button value, which there is none, rather than the select field value. use a different name for the submit button. however, you need to do some other things - 1) the value you use for the options should be an id (auto-increment column) from tbl_paramhead, not the text/label string, because you should store an id in any table holding data related to a tbl_paramhead selection. 2) in your form code, the sql query does not have any external data being supplied to it, and using a prepared query here is wasting time typing and executing code that isn't doing anything useful. change the ->prepare() and ->execute() calls to just $stmt = $pdo->query($sql); the rest of the code using the result from the query will remain the same. 3) in your form processing code, you have missed a point of using a prepared query. you do not put data values directly into the sql query statement when using a prepared query. you put place-holders in the sql query statement for the values (without any single-quotes around the place-holders), then you supply the data values when you execute the query. also, in your form processing code - 4) the if($_SERVER["REQUEST_METHOD"] == "POST") conditional test should come first and/or be the only test you need. if your form processing code will only handle a single form, there's no need for any additional logic. 5) you need to validate all submitted form data before using it. if the text field is empty or no select option was picked, you should not run the INSERT query. if you use an array to hold he validation error messages, you can just test if the array is empty to dected if there are no validation errors. 6) there's no good reason to write out line after line of code that is just copying variables to other variables. the original variables are perfectly fine to use in the rest of the code. what happens if your form has 10 fields? are going to write out 10 lines of code copying each of the $_POST variables to other variables? the answer to this question should be no. if you do have a need to copy an array to other variables, such as if you are making a trimmed copy of the data, you can do it using a single statement, 7) if you put the form processing code and the form on the same page, you can display any validation errors when you display the form and you can populate the form fields with the submitted values when there is an error, so that the visitor doesn't need to keep filling in/selecting field values, they only need to correct the fields that have errors. -
if your goal is to get a web development environment setup, use one of the all in one WAMP packages, such as xampp - https://www.apachefriends.org/index.html this will get you a system with php correctly installed and working with the web server. if you need php to connect to an mssql database server, you need to install an appropriate php extension (see the list of choices at this link - http://php.net/manual/en/intro.mssql.php ). and again, if all you are trying to do is setup a web development environment, the all in one WAMP packages come with a database server. just because you are using windows as your operating system doesn't mean that you must use ms web and database server software.
-
so, your data is not normalized, making all your code and queries, to find and display, insert, update, or delete data, either written out by you or dynamically produced by code, overly complicated. the solution, is to properly store your data, then the code and each query, no matter how it gets produced, will be simple. the following is something that was already written as a reply in one of your threads - your current table design is making it harder for you to accomplish any task associated with the data. what you are doing is not that complicated, but you are making a wall of code that won't work. you even have the ->execute() method call outside of and after the end of the loop where it would need to be.
-
first of all, is your data properly normalized, especially since you have column(s) with numerical endings? it would be unusual to have that many unique meaning/purpose columns in one database table. if you do have one or more series of name-numbered columns, these should be stored in other table(s), one row per data item, in which case it would be straight-forward to dynamically process and insert/update/delete the row(s) of data.
-
unless you cut off some of the php code when you posted it, you are missing a closing } and would be getting a php parse/syntax error, assuming you have set php's error_reporting to E_ALL and display_errors to ON, in the php.ini on your development system (you cannot set these via php statements in your main code and have them show parse/syntax errors in the same code since your code never runs when there is a parse/syntax error.) you should also use $_POST, not $_REQUEST, and your post method form processing code should be near the top of your file, before the start of your html document.
-
Run query with default option from PHP select query
mac_gyver replied to samadhan's topic in PHP Coding Help
the reason you are getting different results in different browsers is because your html markup is completely wrong and different browsers deal with html errors differently. do NOT put a complete html document inside of a form tag. you should be producing a ONE complete and valid html document, with the form located at an appropriate place inside the body of that html document, not the other way around. -
the way to correctly use any of the php statements is to lean what they do, what parameters they accept as input, and what values they return. i recommend that you re-do your code, making use of the the following - 1) use the php PDO extension 2) make ONE database connection for the entire page 3) use exceptions to handle database errors. this will let you eliminate the error handling logic in your code. 4) use prepared queries to supply data values to the sql query statements 5) consolidate and put the post method form processing code near the top of your file 6) consolidate and put the SELECT queries, that are retrieving the data needed to display the page, next, and put it before the start of your html document. fetch the data from each query into an appropriately named variable. loop over these variables in your html document in order to output the data. 7) for the various select/option lists, store the choices in database tables, with an auto-increment column for an id. you would query for the choices and dynamically produce the option lists. the id would be used as the option value attribute and you would store the id in any table holding data related to the select/option choices. you would also 'select' the option choice that matches any existing stored data value. don't put/leave code and variables in your code if it isn't being used. 9) if you are going to LIMIT the number of rows of data that are being displayed, do that in the query, using a LIMIT clause. you should also use an ORDER BY clause in any SELECT query that is expected to match more than one row. 10) if you are going to use literal values in your code, such as the 1,2,3 for the table, use defined constants, with meaningful names, so that anyone looking at the code can tell what the 1,2,3 values mean any place they are being used. 11) it appears that your database tables have sequences of columns with times as part of the column name. if so, research 'database normalization' 12) it also appears like the three database tables hold similar data, only differing in a 'category'. if so, the data should be stored in a single table, with a category column.
-
back one problem, this is the reason that you DON'T put isset() tests around every form field. after you have detected that the form has been submitted (the $_SERVER['REQUEST_METHOD'] test) all form fields, except for unchecked checkboxes and unchecked radio buttons, will be set. by using isset() for form fields that WILL be set, if you have a valid form with those fields in them, you are hiding problems and just cluttering up your code with unnecessary typing. --- as to your current problem, sorry for how this sounds, but there is almost nothing about that code that is worth saving. it is even doing some database things that don't go together and are probably producing php error messages. here's a list, which is likely missing some of the problems, because there are just too many - 1) stop testing if boolean values are equal or not equal to true/false values. 2) if the current user is logged in, when you do a redirect to some other page, you must stop program execution, by having an exit; in your code. without an exit;, all the code on your page still runs. 3) don't use isset() around form fields that WILL be set. 4) don't use mysqli_real_escape_string() on a value before you have validated it and since you are using a prepared query, don't use mysqli_real_escape_string() at all. it changes the value and will cause your validation to operate on a different value than what was submitted and with a prepared query, you don't need to escape the data. 5) you should store validation error messages in a php array variable. this will let you setup separate and unique validation errors, except when logging someone in, you should not identify if it is the username/email or password that was wrong. for a login script, just output a generic message that the login failed. 6) for your login process, all you care about for validation is that the trimmed form data is not empty. you don't care about lengths (when registering a user, you would care about the lengths.) 7) don't use mysqli_stmt_init(), which you are using incorrectly anyways. if it hasn't already been mentioned, switch to use the php PDO extension. it is much easier to use than the php mysqli extension. this will avoid all the lines of code using - mysqli_stmt_init(), mysqli_stmt_bind_param(), mysqli_stmt_bind_result(). 9) you cannot directly use mysqli_fetch_array() with a prepared query and you should be getting a php error at this statement. if you switch to the PDO extension, you CAN use any of its fetch statements, regardless of how you execute the query. 10) if the user hasn't activated the account, you must test for and handle this condition first. 11) if the query matches a row, you know that the username matched. there's no good reason to re-test the username in php logic. 12) only if the query matched a row, the user has activated the account, and password_verify() confirms that the entered password matches the stored hash, should you store a value in the session variable and the value you store in the session variable should be the user's id (auto-increment column value), not the username. it appears to me that your code is unconditionally assigning the $username variable to the session variable, resulting in it being set even if the necessary conditions have not been met. while some of the indentation in your code may have been lost due to the forum's operation, it would help if you correctly indented your code, so that you can see where the statements are actually located in the logic. 13) i'm pretty sure i am repeating at this point, but do NOT store the username/password in cookies and do NOT populate any form fields with these cookie values. if you want a 'remember me' feature, at the point where the user has successfully logged in, generate a unique random token, store this in a cookie and store it in a column in your users table. if the visitor returns to your site and the login session variable doesn't exist and the cookie does, use the token value from the cookie to query for the user's id. if found, store the user's id in the session variable, the same as if they had just logged in via a username/password. what you would populate the form field values with are any submitted data values, when there are validation errors, so that the visitor doesn't need to keep tying in values. 14) you are also echoing things before the start of your html document. if you store the validation and login error messages in an array as has been suggested, you can test and output the contents of that array in an appropriate place inside your html document.
-
that would indicate that the sql query didn't match any row(s) and the while(){} loop to fetch the data was false/skipped. are you sure that particular barcode value exists in the database? any trans-posed digits? double digits? missing leading zeros (and the data type is actually character/text)? is the barcode value in your code from a copy/paste operation? we have seen cases where there are non-printing or non-ascii characters that got copied from elsewhere, that results in a non-match in values. if this could be the case, delete and TYPE the value you are using.
-
do you have php's error_reporting set to E_ALL and display_errors set to ON, so that php will help you by reporting and displaying any errors it detects. you should also be using exceptions for the pdo statements. you can enable exceptions when you make the connection. add an element to the options array with - PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION this will cause any errors with the pdo statements to throw an exception, which you should let php catch and use its error_reporting, display_errors, log_errors settings to determine what happens with the actual error information. you should also not catch the connection exception and echo the raw error information. if you remove the try/catch block you have now and let php catch the connection exception, it will use its error_reporting, display_errors, log_errors settings to determine what happens with the actual error information.
-
Uncaught Error: Call to a member function rowCount()
mac_gyver replied to ronc0011's topic in PHP Coding Help
your connection string is in single-quotes. this would result in the php variables NOT being replaced with their value. as to why this isn't throwing an exception from the connection code, i have seen cases where the DSN has been wrong/gibberish but with no error. in fact, just tested, the OP's connection code, with a correct username/password, results in the following from the var_dump() - if the OP had enabled exceptions in the connection code, there would be a 'no database selected' error at the ->query() statement. change the single-quotes to double-quotes in the 1st parameter in the connection code. edit: and you will need to remove the spaces as Barand has indicated above. -
^^^ it's even worse that that (thanks php.net.) when using OOP notation for the connection, an object is always returned and $db will always be an object (true) value. so, three things - 1) the or die(...) logic won't ever be triggered, 2) if you are using program logic to detect a connection error, you must use mysqli_connect_error() (or the ->connect_error property, assuming you have a php version where that works), and 3) if you can, switch to use the php PDO extension. it is much better implemented, simpler to use, and more constant than the php mysqli extension. avoid all the problems with handling connection and query errors by enabling exceptions, then simply let php catch the exception and use its error_reporting/display_errors/log_errors settings to control what happens with the actual error information. you can then remove (which currently isn't working anyways) or leave out any error checking logic in your code. to enable exceptions for the php mysqli extension, simply add the following line before the point where you are making the database connection - mysqli_report(MYSQLI_REPORT_ALL);
