Jump to content

Psycho

Moderators
  • Posts

    12,145
  • Joined

  • Last visited

  • Days Won

    127

Everything posted by Psycho

  1. I am in agreement with @Phi11W above. There are scenarios where some things need to be processed on a schedule, but that is not always the case. So, it would be helpful to know what you are wanting to "happen" every night and what will "happen" after the one minute when the user clicks a button. Depending on what you are trying to do the best solution can be different. But one of the preferred way to initiate things on a schedule is with a CRON job which is a scheduled task within a Linux server (which is where most PHP implementations are hosted). If you are hosting your application with a provider they likely have a custom interface for setting these up. You would start by creating a PHP file that will run a process (your nightly process or the process to run after one minute of the button click). For the nightly process you you set up the CRON job to run at a specific time each night. You should set up a notification to be sent and report if the process passed or failed. As for the process to run 1 minute after a button click someone may know a better process, but the only way I can think to do that would be to have a scheduled process that runs every 10 seconds (or some time that you specify). When a user clicks the button, you would add a record to the DB for the time they clicked it and a flag to indicate it had not been completed. Then every 10 seconds when the process runs, check the DB for any unprocessed records and "process them" and update the completed flag accordingly. From the user perspective you can always display the time to execute based on the timestamp that was added to the DB.
  2. That's not a valid comparison. There is logic within the PHP engine to know what to do with the asterisk symbol. It was purpose built to do multiplication. If it did not exist and you wanted to be able to multiply arbitrary numbers you would have to build a function. For example, if the PHP engine knew how to add, but not to multiple here would be one way: function product ($a, $b) { $product = 0; for ($i=0; $i<$a; $i++) { $product += $b; } return $product; } Using the asterisk is kind of like calling an internal function to do the multiplication. For your purposes, you can create a function to do what you need and call that function as a single line. outputDirectory($rootDirectroy); Your logic of a single line is the simplest solution is predicated on the assumption that there is a purpose built function for your needs. If not, one needs to be created. And, I will take readable, multi-line code over condensed code every time. It's a pain to go back to some old code that needs to be refactored and trying to decipher some complicated process that was condensed down to a few lines trying to figure out how it works. Give me separate lines for each step in the process with comments on what it is expected to do.
  3. I would add the following suggestion regarding this type of logic if ($row['fk_usertypes_id'] ==1) { echo "Hello 1"; } else { echo "Hello 2"; } Just because the value is not 1, you should not assume the value is 2 - even if those are the only expected values. I've seen multiple production issues where such logic was implemented and unexpected conditions caused impactful bugs. If you only expect the value to be 1 or 2, I would do the following. if ($row['fk_usertypes_id'] == 1) { echo "Hello 1"; } else if (($row['fk_usertypes_id'] == 2) { echo "Hello 2"; } else { //Throw error echo "Unhandled error"; } Although at this point a switch() statement might make more sense.
  4. A couple things. First please put code into code tags using the forum editor. I have fixed your initial post. Second, you say that you get a "blank screen", but you have provided no content of what debugging you have performed. You state you are looking for another way to iterate over the files - but you have already confirmed that the files do load and you can iterate over them - you just aren't getting results. So, rather than finding a different way to get the files (which you have already accomplished), you need to figure out why it is not working. I suspect the issue may be your variable names are causing confusion and you aren't passing what you think you are to the processing code. In example you post with a single file you have this: $file = file('myfile.xml'); In that case $file is an array of the contents of the file. Then you state that you tried thing such as $file = glob("directory/*"); foreach ($file as $line) { or $directory = 'directory'; $files = scandir($directory); foreach ($files as $file) { In the first case $line is a $file (not a line) and in the second case $file (in the foreach loop) is a reference to the file NOT an array of the contents of the file. I'm assuming you are not calling file() on the file reference within your loop. If you had called that first variable $linesAry, which is more accurate to what it is, I think you would have seen this yourself. This should work. Note I don't have a an environment to test on at the moment. So there could be some minor typos\errors. <?php //Make the DB connection $servername = "localhost"; $username = "dbuser"; $password = "dbpass"; $db = "dbdb"; $conn = new mysqli($servername, $username, $password, $db); if ($conn->connect_error){ die("Connection failed: ". $conn->connect_error); } //Get the contents of the directory $directoryStr = "directory/*"; echo "Processing directory: {$directoryStr}<br>\n"; $filesAry = glob($directoryStr); echo "Found: " . count($filesAry) . " files<br><br>\n"; //Iterate over each file foreach ($filesAry as $fileStr) { //Reset the variables for the data being searched $ip = ''; $hostname = ''; $port = ''; $portArray = array(); $portList = ''; $timestamp = ''; //Get content of the file into an array echo "Processing file: {$fileStr}<br>\n"; $linesAry = file($fileStr); //Iterate over each line of text in the file foreach($linesAry as $lineStr) { //Get IP Address if (strpos($lineStr, 'addrtype="ipv4"') == TRUE) { preg_match('/addr=".* addrtype/', $lineStr, $results); $ip = implode(" ",$results); $ip = ltrim($ip, 'addr="'); $ip = rtrim($ip, '" addrtype'); echo "<br><strong><u>Device</u></strong><br>"; echo "IP Address: $ip<br>"; } //Get Hostname if (strpos($lineStr, 'type="PTR"') == TRUE) { preg_match('/name=".*" type/',$lineStr,$results); $hostname = implode(" ",$results); $hostname = ltrim($hostname,'name="'); $hostname = rtrim($hostname, ' type'); $hostname = rtrim($hostname, '"'); echo "Hostname: $hostname<br>"; } //Get Ports if (strpos($lineStr, 'portid="') == TRUE) { preg_match('/portid=".*><state/',$lineStr,$results); $port = implode(" ",$results); $port = ltrim($port,'portid="'); $port = rtrim($port, '"><state'); echo "Port: $port<br>"; array_push($portArray, $port); } //Add Values to Database if (strpos($lineStr, '/host>') == TRUE) { $timestamp = time(); $mytime = new \DateTimeImmutable('@'.$timestamp); $portList = implode(", ",$portArray); $sql = "insert into _____ (ip,hostname,ports,timestamp) values ('$ip', '$hostname', '$portList', '$timestamp')"; if ($conn->query($sql) === TRUE) { echo "Data Added: $ip - $hostname - $portList - $timestamp <br>"; } else { echo "Error: ".$sql."<br>".$conn->error; } } } } //Close the DB connection $conn->close(); ?>
  5. The previous posters provided some good input and identified the issue - but maybe not as directly as it could be. The issue is that you do not provide the input field a name, i.e. name="clientSearch" or something like that function client_search(){ echo "<h1 color=#00000>Client Search</h1>"; echo "<label for='clientSearch'>Search Clients:</label>"; echo "<input type='text' id='clientSearch' oninput='getSuggestions(this.value)'>"; //What is the name of this field??? echo "<div id='suggestions'></div>"; } But, they are also correct that the organization of the code is problematic. I see no reason to create a function for creating that form field. I am big on writing code one and reusing it (that's assuming you use this field in multiple places) - but in the case of a field within a form it makes it difficult to "see" the entire form. Also, whenever I'm trying to debug issues with data passed from a form, I'll simply output the contents of $_POST or $_GET to the page.
  6. $earliestDateTs = false; foreach($data as $line) { $dateStr = substr($line, 0, 10); //Get just the date part of the string $dateTs = strtotime($dateStr); //Convert the date string to a timestamp if(!$earliestDateTs) { $earliestDateTs = $dateTs; } //If earliestDateTs not set (i.e. first iteration) set to this line's timestamp $earliestDateTs = min($dateTs, $earliestDateTs); //Set earliestDateTs to the minimum of the current value or this line's timestamp } echo "Earliest date: " . date('m/d/Y', $earliestDateTs);
  7. I will second this. I've been involved in the creation of several cloud based applications (browser, mobile apps, and desktop clients) for a commercial company. In my experience, native mobile apps are a pain for many reasons. For Apple apps there was a significant process to get approved to get the app on the iStore. Trying to verify compatibility between different mobile OSes and version was a huge pain. It's "different" from the browser version (assuming Product decided to make the same functionality available in a browser). So the front-end has to be coded and tested separately. And many others. It takes a little more though to design a responsive web application that will display appropriately on a mobile device vs a tablet vs a full size display. But, that extra work is benefitted by having a single application that can be repurposed across multiple devices. I just don't know why so many companies want to build mobile apps that could be served by a responsive web application. Of course, some functions require a mobile app (at least for usability), e.g. if the app needs to interact with data on the mobile device.
  8. You are defining those input fields as arrays. Note the "[]" at the end of the field name. <input type="checkbox" name="tam[]" value="tamzamanli" /> <span style="color: #fdb43f;"> Tam Zamanlı</span> <br /> <input type="checkbox" name="tam[]" value="yarizamanli" /> <span style="color: #fdb43f;"> Yarı Zamanlı</span> Is your intent to allow the user to select multiple options for the "tam" value? If so, this is a valid approach - but the results ill be passed as an array because of the "[]" in the field names. Checkboxes are unique in that if you don't check them - then there is no value passed when the form is submitted. Using the above logic, the first value checked would be passed as "$_POST['tam'][0]", the second one as "$_POST['tam'][1]", etc. So, you would need to write your logic to process that data accordingly. One way you could handle this is by imploding the array into a single string. But, not knowing all the ways you may need to use this data, I can't say if that is the best approach. Also, in your validation part of the script, you can check that $_POST['tam'] isset() and also check that its length is greater than 0: if(count($_POST['tam'])>) then . . . $tamValues = implode(', ', $_POST['tam']); echo "Selected tam values: " . $tamValues; //Assuming "tamzamanli" and "yarizamanli" were checked the output would be: // Selected tam values: tamzamanli, yarizamanli However, if your intent is that the user should only select one of the values for "tam" (and the similar inputs), then you should use a radio group instead. Using a radio group, each element will have the same name and only one record can be selected. You don't need to format the name as an array (but could be for other uses cases not related to your purpose). <input type="radio" name="tam" value="tamzamanli" /> <span style="color: #fdb43f;"> Tam Zamanlı</span> <br /> <input type="radio" name="tam" value="yarizamanli" /> <span style="color: #fdb43f;"> Yarı Zamanlı</span>
  9. A "tiny URL" typically refers to a 3rd party service that will accept a full/long URL and then provide a coded URL for a person to then use for communicating the IRL to people. Typically when in printed format since long URLs can be embedded in links for any digital communications. When those links are utilized, they are first directed to the 3rd party site, which then checks the "tiny URL" parameters to what is stored in their DB and then redirects the user to the intended original URL. Are you wanting code that will utilize a third party service to generate the tiny URLs or are you wanting to build your own tiny URL service? If the former, you would need to check those services and find one that allows for such external submissions. I would suspect they would have instructions for doing so if it is within their TOS. If you want to build your own, what have you done so far and where are you stuck? This is a "help" forum, not a do it for me forum.
  10. If you are wanting to change images - that might be very easy. If you can load a page where the image you want to change is displayed, you can just right-click on the image and select an option to see properties of the image where that image "lives" on the web server. E.g. in Chrome you can select "Open image in new tab" or "Inspect". For many websites, the path you can see in either of those would show you were the image is located on the webserver. However, some web applications might have a src for images that goes through some intermediate process to pull the image based on a parameter (e.g. something like "loadimage.php?img_id=5"). If that's the case, then you can open the php file the image src points to and try to decipher the logic on how it gets the image. One word of caution though, an image could be used in multiple places. If you are only intending to change it in one place it would also change it for any other locations you are unaware of. As for text, it is not as simple. Typically the content is "built" from many different files (as you've see by inspecting the index.php and trying to trace through the files that are called). If the text for a particular page is hard-coded within a file, you can use an IDE (or even robust file search tools) to search all the files in the repository for certain words/phrases within the content to see what files have that content. If the content is in a database, then you would have to figure out what tables(s) the content is stored in and search them for the content. however, if the content is within a database, I would think there would be an "admin" area of the site in order to update the content.
  11. Try this newent = newent.toUpperCase();
  12. Yeah, that was my revised query I sent to him and I can see why it is confusing. While it as not what I would ideally write it should work for him. Based on what I deduced from his code there is a transaction table and a candidates table. A transaction ID will be included in any transaction record created. Then, when that transaction ID is "USED" it will be included (or updated) in a record within the candidates table. The functionality he is trying to create is to identify if: Does the transaction ID exist Has the transaction ID been used That query will take the supplied ID from the form input and pull the transaction ID from both the transition table and the candidates table using a LEFT join. So, if the transaction ID does not exist (within the transaction table) then no records will be returned. If a record is returned, then the logic just needs to check the transaction ID from the Candidates table. If NULL then the transaction code has not been used. I probably would have pulled something like the candidate ID from the candidates table to check (or use a calculated group by to return a 0 or 1 value. But, I had no visibility of any other field names from that table and was too lazy to ask or provide an explanation when using some mock field name for him to change.
  13. This is a PHP "Help" forum, not a PHP "Do it for me" forum. But, I'll give you some code samples to start with. I don't have your database and am simply not going to take the effort to put one together to test the code. So, what I provide might not work out of the box. I'll leave it to you to fix any errors I miss. <?php session_start(); require_once 'INC/DBcon.php'; $error = ""; //Variable to hold error messages // Check if the user submitted a transaction code if(ISSET($_POST['transactioncode'])) { // Trim the transaction code and assign to variable $tcode = trim($_POST['transactioncode']); //Create a query to identify if the transaction code exists //AND if it has been used for a candidate by JOINing the tables $query = "SELECT t.transactioncode AS tCode, c.transactioncode AS cCode FROM tsc AS t LEFT JOIN Candidates AS c USING (transactioncode) WHERE transactioncode = ?" $stmt = $conn->prepare($query)->execute([$tcode]); $result = $stmt->fetch(); //Check if results were empty if(!$result) { //The transaction code does not exist $error = "The transaction code does not exist"; } //Check if the cCode (transaction code in candidate table) is not empty elseif (!empty($result['cCode'])) { //The transaction code has been used $error = "That code has already been used."; } else { //The transaction code exists and has not been used $_SESSION['tsc'] = $tcode; echo "<script>alert('Validation Succcessful')</script>"; header("location: Sign-up.php"); exit(); } } ?> <!DOCTYPE html> <html class="no-js" lang="en"> <head> </head> <body> <?php echo $error; ?> <form action="" name="regForm" onsubmit="return validateForm()" method="POST"> <h4 class="text-success"> <b>N/B:</b> Enter Session/Transaction ID/Number Correctly and click on PROCEED/FETCH, candidates will now commence registration.</h4> <br> <br> <div class="fCont"> <div class="fContL"> <label for="tsc"> TRANSACTION NUMBER/<br>SESSION ID/<br>TRACKING CODE: </label> </div> <div class="fContR"> <input type="text" id="tsc" name="transactioncode" placeholder="Your TRANSACTION NUMBER/SESSION ID/TRACKING CODE.."> </div> </div> <br> <br> <div class="fCont"> <input type="submit" id="submit" value="PROCEED/FETCH" class="submit" name="Submit1"> </div> </form> </body> </html>
  14. As Requinix alluded to, this is not a limitation of PHP, it is a limitation of the PhpSpreadsheet library. Excel files have evolved into highly complex files well beyond what a "spreadsheet" is intended for. In this case the checkboxes are not "data" within the spreadsheet as it would normally exist. The checkboxes are objects that sit "on top of" those cells and are not the values within the cells. It would be possible to accomplish what you are after but it would require extensive knowledge of how those objects are defined within the file structure and even then could require elaborate logic within the code to figure out which checkboxes align with which row. The very simple solution is to change the structure of the spreadsheet so the "value" for that column is actually in the cells of that column. Instead of using checkbox elements on top of the cells, I would change those cells to use data validation so that the cell becomes a drop-down selection where the user can only choose True or False.
  15. Programming, like any skills, is a matter of Crawl, Walk, Run. You learn by doing the very simple things, then build on that to learn intermediate skills, then (after a sufficient amount of time) you can learn to do more complex things. But, here's the thing. If you already know how to run a query against the database, you should already know how to work with an array and to build an output from it. Plus, the fact that you state you've been working with this language for two years and don't know these fairly easy tasks is incomprehensible to me. In fact, I am leaning towards the fact that you are a troll and just trying to get people mad based on your "not" understanding these things. I've even considered locking the thread.
  16. @forum It appears you are of the expectation that when retrieving the results of a Database query, that you should be able to just do an "echo" of the results and have it written to the page in some way. That's not how this works (with PHP/MySQL or any similar languages as far as I know). If you think about this logically, you would understand that would not be very useful for the majority of use cases. Here are just a couple of reasons; How should the results be formatted? What works for one scenario would not work for the other 9,999 scenarios. Not all DB queries would be output to the page without other "post-processing". E.g. maybe the results should include sub-totals for different categories, or some records should be displayed differently (e.g. a negative amount in red. It would be extremely difficult if the results were returned in an "echo" ready format to do anything with the data. A database returns DATA in a logical data type that a programming language or other resource can work with. It is up to the receiving application to determine what to do with the data. If you want to run a query and have it output to the page in some standard format. Then just create a simple function and you can call that function every time you call a query. That is the beauty of programming, you can write a little bit of code to do something repetitive and reuse that code whenever and wherever you choose. You only have to figure out how to do it one. Also, there is a VERY easy way to output a multi-dimensional array in a readable format (albeit not in a table). I do this all the time to be able to debug output from a query. $query=$db->query("SELECT * FROM msg"); echo "<pre>" . print_r($query, TRUE) . "</pre>";
  17. @mac_gyver is correct about the proper way to prevent duplicates. However, when it comes to account creation you should never inform the user that there are existing values for user IDs or email addresses. Malicious users use such "errors" to data-mine a site to find out what are valid usernames. They can then do all sorts of nefarious activities from trying to brute force passwords, sending users fishing emails purporting to be from the company of the site, etc. Best practice is that when a user registers for a site (assuming the data they entered was valid) is to provide a message to them stating something along the lines of "Thank you for registering, an email has been sent to you with instructions to complete your registration". If the username & email are not duplicates, then send an email with a link to complete the registration. If the email is an existing one (whether or not the username is the same), then send an email with a statement that a registration was attempted with the email address, but one already exists (and probably include a link with instruction on how to reset their password as they may have forgotten they registered previously). If it was a malicious attempt the user will know that someone else tried to register with their email address. What I remember was based on the email address being the User ID. So, I'm not certain what you would want to do if only the User ID is a duplicate. But, you don't want to allow a malicious user to harvest your application for valid User IDs.
  18. To add some context to @Barand's response. The code you provided is not "complete". I would expect that line is contained within an echo statement that uses double quotes. Within a string defined with double quotes the brace {} characters have special meaning - they allow you to include a PHP variable directly within the quoted string. But, you cannot manipulate the variable within the braces - only include the value of it. So, similar to what Barand showed, you need to find where that string starts and before the declaration of the string you will want to define a new variable which is the view count +1000. Then replace the view count variable within the quoted string with the new variable that you have defined.
  19. OK, I just realized that the prior code I posted has a problem - not a "technical" problem as it should do what it was intended to do. But, in retrospect, it allows for an attack vector. Ideally, you should not "leak" data about existing accounts. In the sample code I provided, a malicious user could identify if a particular email address was already used and then iterate through various usernames to see which one was used for that account (or vise versa). Instead, I would suggest that the account signup page always present the user will a message along the lines of "Your account request has been received, please check your email for more info". Of course, if there were data validation errors (e.g. not a valid email format, username blank or too short) you can present the user with those problems on screen. Going back to the "valid" submission and the potential duplicate errors, here is what I would do. Both the email and username or unique: Create a temp account and send an email with a link to confirm the account. Do not allow the user to "use" the account until it is confirmed. This prevents a malicious users from creating an account under someone else's email The email address is a duplicate (the username may or may not be a duplicate): Send an email to the existing user for that account with a message telling them that you are notifying them that a request was made to create a new account for their email address, but an account already exists The username is a duplicate, but the email address is not: This is a tough one. If the email is the user ID then it is covered in #2 above. But, in this situation it is quite possible that two people might want to use the same username, but you don't want to tell a malicious user about existing usernames. The best option I can think of is to send the sign-up user an email to the email address provided telling them the username is not unique. It still leaks data, but it would be harder to automate/brute force because they also have to check the email - although that can be automated as well.
  20. The query that Barand provided to create a table shows how to create a table in the database with a unique constrain on a field. His earlier response where he linked to an old post of mine showed how you would execute an INSERT query against a table with a unique constraint. So, let's restate all this another way: You need to configure your table such that the username and email fields have a unique constraint. That will prevent the DB from accepting any INSERT\UPDATE requests that would generate duplicate values in either of those fields. But, in doing so, any such queries would fail and you need to execute your logic a little differently. Step 1 is to set up those fields in the DB to be unique. The query Barand provided would create a new table from scratch. You could also create an update query for the table to modify its structure for those unique constraints (e.g. "ALTER TABLE `table_name` ADD UNIQUE(`field_name`);"). Or, if you are like me, I just use PHP Admin's console to modify tables. Open the Table in PHP MyAdmin and select the "Structure" tab. In the list of fields, there is a column on the right where the label UNIQUE is shown. Just click that label to make that field unique in the table. Step 2. Now that those fields are unique IF someone was to try and create a new profile with a username or email address that already exists in the table, the query will fail. So, you need to approach the INSERT logic differently. The code Barand linked to previously provides an example. Basically, you want to wrap the INSERT (or an UPDATE) query within a try{} block. Then, if it fails, you will have a catch{} block to determine IF the failure was due to a duplicate constraint or not. Now, your case is a little unique since there will be two potential unique constraints and you will want to advise the user "which" of the fields (or both) are a duplicate, so you need more logic than the example provided. Here is some sample code. Note that I have not tested it and expect I may have made some typos, but the point is about showing what the logic would look like $pdo = new PDO("mysql:host=$hostname;dbname=$databasename;charset=utf8", $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Enables exception mode try { //Attempt to execute the INSERT query $query ="INSERT INTO user2(username, email, password1, date) values(:username, :email, :password1, :date)"; $stmt = $pdo->prepare($query); $stmt->execute($arr); } catch (PDOException $e) { //Insert failed, check if it was due to duplicate constraint if ($e->getCode() == 1062) { // Duplicate username and/or email address - figure out which one(s) $query = "SELECT SUM(username=:username) as dupe_username, SUM(email=:email) as dupe_email FROM `photos`" $stmt = $pdo->prepare($query); $stmt->execute($inputArr); //This arr should only have the username & email values $result = $stmt->fetchAll(PDO::FETCH_ASSOC); $errors = ""; if($result['dupe_username']) { $errors .= "Username must be unique"; } if($result['dupe_email']) { $errors .= "Email address must be unique"; } } else { //Some other error occured throw $e;// in case it's any other error } }
  21. In addition to echoing out the query, you would want to check any variables in that part of the code. The construction of the ternary operator line looks odd. Typically I would put the conditions (especially when there are multiple) within parens. Although, that does seem to work in my install. I see that the $upwalle value is being put into quote marks in the query, which is not proper for a numerical value - same with the id value. Also, you are ALWAYS running the query even if you are not intending to change the value. You should only run the query if you are intending to make a change. Here is some very verbose debugging. I also made some minor tweaks to the code. What are your results when running this: echo "Get user for id: {$video->user_id}<br>"; $up_user = $db->where('id', $video->user_id)->getOne(T_USERS); echo "Get wallet amount for user: "; $uploader_wallet = $up_user->$user->wallet; echo "{$uploader_wallet}<br>"; echo "Calculate change to wallet: "; $upwallet = ($sell_video == 0 && $uploader_wallet >= 1) ? .5 : 0; echo "{$upwallet}<br>"; echo "Check if upwallet value is not zero: "; if($upwallet > 0) { echo "True - run update query<br>"; echo "Construct query: "; $query = "UPDATE ".T_USERS." SET `wallet` = (`wallet` - {$upwallet}) WHERE `id` = {$video->user_id}"; echo "{$query}<br>"; echo "Run query: "; $db->rawQuery($query); echo "Complete"; } else { echo "False - do not run update query<br>"; }
  22. Here is how I would do that: function parseDataString($inputStr) { $outputAry = array(); foreach(explode("|", $inputStr) as $catAry) { list($catName, $catValuesStr) = explode("=", $catAry); $outputAry[$catName]= explode(",", $catValuesStr); } return $outputAry; } $text = 'cat1=hello,world|cat2=one,two|cat3=value1,value2'; $result = parseDataString($inputStr); print_r($result);
  23. Let me add to Barand's response. The typical process I take with forms is as follows: Form pages will POST to themselves When a form page loads it will first determine if a submission was made. If no submission is made, proceed to creating the form If a submission was made, then I will have the code go through form validation logic to ensure that all required data was submitted and that all submitted data is appropriate (e.g. a numeric field should have a numeric value, a date field should include a value that can be interpreted as a date, if something should match a DB id value, make sure that value exists, etc.) During the validation, for any errors that are encountered save appropriate error messages in an array/object, then proceed to creating the form. If no errors in validation, then execute the code to act on the submitted data - e.g. do a DB INSERT. Then redirect to a confirmation page. CREATE THE FORM: If there was no form submission or if there were errors in the data validation, create the form for user input. If there were errors, you can repopulate any valid data back into the appropriate fields so the user does not need to reenter. For errors, you can list them all at the top of the page (easy) or you can list them out above/below the individual fields where the errors occurred. You would just need to store the errors in the array/object in a way to correspond them to the input fields where they originated. I also like to create functions for building my various input fields. That way I can call the function with appropriate parameters so it can build the field either with the default/empty value or with a previously entered value. That way I don't have to write the same 6-10 lines of code to handle those two scenarios for every input field.
  24. Unless there are additional fields in the query result set, you don't have all the corresponding fields shown in the example data. The example data has a "name" and "description". Your data has a description, but no name. You could use the SKU in place of the name. Also, I assume "unit_amount" is the price. Here is some (untested) code which should do what you need //Create the line items array $lineItems = array(); foreach ($resultID as $row) { $lineItems[] = array( "price_data" => array( "currency" =>"usd", "product_data" => array( "name"=> $row['sku'], "description" => $row['description'] ), "unit_amount" => $row['price'] ), "quantity" => $row['qty'] ) ); //Create full payment array $paymentArray = array( "success_url" => "https://www.domain.com/stripesuccess.php?sid={CHECKOUT_SESSION_ID}", "cancel_url" => "https://www.domain.com/cart.php", "mode" => 'payment', "line_items" => $lineItems ); //Set session for payment call $session = \Stripe\Checkout\Session::create($paymentArray);
  25. @Strider64 Maybe I am misreading your code, but I think I see a bug. In the block of code to consolidate the values into the array $attribute_pairs to perform the insert there is a condition that checks if the index is "id" - if so, it skips adding that value to the $attribute_pairs. But, there is no similar logic in the code block that dynamically creates the list of fields for the sql query. That code uses all the indexes in the $data array using array_keys($data). So, if the array $data did contain an index with the name "id" the query would fail because the number of fields for the insert would be one greater than the number of values. Either the "id" field needs to be excluded in the fields list OR the value if such a field exists can be set to NULL. Personally, I would leave such logic out since any code passing data to an INSERT function should only pass the relevant fields. Although, I could see the viability of including the ID if the function was doing an ON DUPLICATE KEY UPDATE. Or, I could be completely missing something and would appreciate pointing what that is.
×
×
  • 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.