Jump to content

Psycho

Moderators
  • Posts

    12,145
  • Joined

  • Last visited

  • Days Won

    127

Community Answers

  1. Psycho's post in Help with directory loop was marked as the answer   
    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(); ?>  
  2. Psycho's post in please help - don't know how to sequence call-ups was marked as the answer   
    No. It is a lot to go through. But, I can tell that there is a lot of unneeded code. For example the big sections where you are echoing out "<? echo $data["BFG002"] ?>" should be put in a function and called, when needed. And it makes no sense to go in and out of PHP code between those values.

    For example, you can reduce all of this:
    [quote]<? echo $data["BFG001"] ?> <? echo $data["BFG002"] ?> <? echo $data["BFG003"] ?> <? echo $data["BFG004"] ?> <? echo $data["BFG005"] ?> <? echo $data["BFG006"] ?> <? echo $data["BFG007"] ?> <? echo $data["BFG008"] ?> <? echo $data["BFG009"] ?> <? echo $data["BFG010"] ?> <? echo $data["BFG011"] ?> <? echo $data["BFG012"] ?> <? echo $data["BFG013"] ?> <? echo $data["BFG014"] ?> <? echo $data["BFG015"] ?> <? echo $data["BFG016"] ?> <? echo $data["BFG017"] ?> <? echo $data["BFG018"] ?> <? echo $data["BFG019"] ?> <? echo $data["BFG020"] ?> <? echo $data["BFG021"] ?> <? echo $data["BFG022"] ?> <? echo $data["BFG023"] ?> <? echo $data["BFG024"] ?> <? echo $data["BFG025"] ?> <? echo $data["BFG026"] ?> <? echo $data["BFG027"] ?> <? echo $data["BFG028"] ?> <? echo $data["BFG029"] ?> <? echo $data["BFG030"] ?> <? echo $data["BFG031"] ?> <? echo $data["BFG032"] ?> <? echo $data["BFG033"] ?> <? echo $data["BFG034"] ?> <? echo $data["BFG035"] ?> <? echo $data["BFG036"] ?> <? echo $data["BFG037"] ?> <? echo $data["BFG038"] ?> <? echo $data["BFG039"] ?> <? echo $data["BFG040"] ?> <? echo $data["BFG041"] ?> <? echo $data["BFG042"] ?> <? echo $data["BFG043"] ?> <? echo $data["BFG044"] ?> <? echo $data["BFG045"] ?> <? echo $data["BFG046"] ?> <? echo $data["BFG047"] ?> <? echo $data["BFG048"] ?> <? echo $data["BFG049"] ?> <? echo $data["BFG050"] ?>  <? echo $data["BFG051"] ?> <? echo $data["BFG052"] ?> <? echo $data["BFG053"] ?> <? echo $data["BFG054"] ?> <? echo $data["BFG055"] ?> <? echo $data["BFG056"] ?> <? echo $data["BFG057"] ?> <? echo $data["BFG058"] ?> <? echo $data["BFG059"] ?> <? echo $data["BFG060"] ?> <? echo $data["BFG061"] ?> <? echo $data["BFG062"] ?> <? echo $data["BFG063"] ?> <? echo $data["BFG064"] ?> <? echo $data["BFG065"] ?> <? echo $data["BFG066"] ?> <? echo $data["BFG067"] ?> <? echo $data["BFG068"] ?> <? echo $data["BFG069"] ?> <? echo $data["BFG070"] ?> <? echo $data["BFG071"] ?> <? echo $data["BFG072"] ?> <? echo $data["BFG073"] ?> <? echo $data["BFG074"] ?> <? echo $data["BFG075"] ?> <? echo $data["BFG076"] ?> <? echo $data["BFG077"] ?> <? echo $data["BFG078"] ?> <? echo $data["BFG079"] ?> <? echo $data["BFG080"] ?> <? echo $data["BFG081"] ?> <? echo $data["BFG082"] ?> <? echo $data["BFG083"] ?> <? echo $data["BFG084"] ?> <? echo $data["BFG085"] ?> <? echo $data["BFG086"] ?> <? echo $data["BFG087"] ?> <? echo $data["BFG088"] ?> <? echo $data["BFG089"] ?> <? echo $data["BFG090"] ?> <? echo $data["BFG091"] ?> <? echo $data["BFG092"] ?> <? echo $data["BFG093"] ?> <? echo $data["BFG094"] ?> <? echo $data["BFG095"] ?> <? echo $data["BFG096"] ?> <? echo $data["BFG097"] ?> <? echo $data["BFG098"] ?> <? echo $data["BFG099"] ?> <? echo $data["BFG100"] ?> <? echo $data["BFG101"] ?> <? echo $data["BFG102"] ?> <? echo $data["BFG103"] ?> <? echo $data["BFG104"] ?>[/quote]

    To this:
    [code]<?php
    for ($i=1; $i<103; $i++) {
      $aryIdx = "BFG" . str_pad($i, 3, '0', STR_PAD_LEFT);
      echo " " . $data[$aryIdx];
    }
    ?>[/code]
  3. Psycho's post in Loop through line items (Stripe) pulled from database was marked as the answer   
    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);  
  4. Psycho's post in Simplify code was marked as the answer   
    Here 0is how I would handle that
    function columninfo($table, $col = NULL) { //State the error condition check if(!$this->CheckTable($table)){ return false; } //State the error condition check if($col!=NULL && !$this->Checkfield($table, $col)){ return false; } //No errors $stmt = $this->db->prepare('SELECT * FROM '.$table); $stmt->execute(); $numCol = $stmt->columnCount(); $colAry = array(); for ($i = 0; $i < $numCol; $i++) { if($stmt->getColumnMeta($i)['name'] == $col) { //Return type for selected column return $stmt->getColumnMeta($i)[0]; } else { //Append current column to return arrray $colAry[] = $stmt->getColumnMeta($i); } } //Return array for all columns return $colAry; }  
  5. Psycho's post in I have AND operator in Where statement of query, how can i know which statement did not returned was marked as the answer   
    You can give this a try. I think it's probably a little more verbose than it needs to be, but should do what you are asking. Not going to guarantee it is what you want, so run it through some tests first
    <?php //Var to hold result $result = false; //Query for an exact match on both gpw and ewt $query = "SELECT gpm, ewt, totCool from {$uniluxModel} where gpm = :uniluxGpm AND ewt = :uniluxEwt"; $stmt = $dbConn->prepare($queryStr); $stmt->execute(array(':uniluxGpm' => $uniluxGpm, ':uniluxEwt' => $uniluxEwt)); if($stmt->rowCount() > 0) { //There was an exact match $result = $stmt->fetchColumn() } //If no result try getting the two closest records matching gpm and high/low for ewt if (!$result) { $query = "( SELECT gpm, ewt, totCool FROM wxyz WHERE gpm = :uniluxGpm1 AND ewt < :uniluxEwt1 ORDER BY gpm DESC LIMIT 1 ) UNION ( SELECT gpm, ewt, totCool FROM wxyz WHERE gpm = :uniluxGpm2 AND ewt > :uniluxEwt2 ORDER BY gpm ASC LIMIT 1 )"; $stmt = $dbConn->prepare($queryStr); $stmt->execute(array(':uniluxGpm1' => $uniluxGpm, ':uniluxEwt1' => $uniluxEwt, ':uniluxGpm2' => $uniluxGpm, ':uniluxEwt2' => $uniluxEwt)); if($stmt->rowCount() > 0) { //There was a result $result = $stmt->fetchColumn() } } //If no result try getting the two closes records matching ewt and high/low for gpm if (!$result) { $query = "( SELECT gpm, ewt, totCool FROM wxyz WHERE gpm < :uniluxGpm1 AND ewt = :uniluxEwt1 ORDER BY gpm DESC LIMIT 1 ) UNION ( SELECT gpm, ewt, totCool FROM wxyz WHERE gpm > :uniluxGpm2 AND ewt = :uniluxEwt2 ORDER BY gpm ASC LIMIT 1 )"; $stmt = $dbConn->prepare($queryStr); $stmt->execute(array(':uniluxGpm1' => $uniluxGpm, ':uniluxEwt1' => $uniluxEwt, ':uniluxGpm2' => $uniluxGpm, ':uniluxEwt2' => $uniluxEwt)); if($stmt->rowCount() > 0) { //There was a result $result = $stmt->fetchColumn() } } //If no result get the two closest records that are both above gpm and ewt and both below gpm and ewt if (!$result) { $query = "( SELECT gpm, ewt, totCool FROM wxyz WHERE gpm < :uniluxGpm1 AND ewt < :uniluxEwt1 ORDER BY gpm DESC, ewt DESC LIMIT 1 ) UNION ( SELECT gpm, ewt, totCool FROM wxyz WHERE gpm > :uniluxGpm2 AND ewt > :uniluxEwt2 ORDER BY gpm ASC, ewt ASC LIMIT 1 )"; $stmt = $dbConn->prepare($queryStr); $stmt->execute(array(':uniluxGpm1' => $uniluxGpm, ':uniluxEwt1' => $uniluxEwt, ':uniluxGpm2' => $uniluxGpm, ':uniluxEwt2' => $uniluxEwt)); if($stmt->rowCount() > 0) { //There was a result $result = $stmt->fetchColumn() } } if(!$result) { //No records that match either value echo "Not enough data to compute"; } else { //Do something with the data } ?>  
  6. Psycho's post in associative array and foreach was marked as the answer   
    I am pretty certain that your source array is not constructed how the instructor intended. You are simply assigning an array of values to each associative key. I would think the source array should have an element for each employee with each value assigned to an associative key. Something like this:
    $employees = array ( array('name' => 'Employee-1', 'department' -> 'IT', 'salary' => '5000'), array('name' => 'Employee-2', 'department' -> 'HR', 'salary' => '4000'), array('name' => 'Employee-3', 'department' -> 'Marketing', 'salary' => '3000'), array('name' => 'Employee-4', 'department' -> 'Sales', 'salary' => '1500'), // etc. . . . ); The loop over each record in the $employees array
    foreach($employees as $employee) { echo "Name: {$employee['name']}<br>"; echo "Department: {$employee['department']}<br>"; echo "Salary: {$employee['salary']}<br>"; }  
  7. Psycho's post in How to detect if a user is online? was marked as the answer   
    With a web application, you can certainly record when a user logs in, but even if you have a logout function a user can simply close the browser window. So, you do need a way to track that they are still there. Since this is a game where two people are playing each other, I think you need to do more than just track when they hit a new page. Here is what I would do:
    Create a last active field in the user table. Every time you see activity from the user, update the timestamp.
       Determine "how long" of a time period that you would consider someone as still active: 5 minutes, 10 minutes, ??? Then use that time period to query for active players based on those whose last active timestamp is within the last X minutes. This can also be used for two players already in a game to notify one that the other has dropped off.
      Once two users start a game use AJAX to both continually update their last active value AND to proactively notify them of anything relevant. E.g. when it is their turn, if the other user drops off, etc. AJAX is simply javascript that makes a server call and returns back data to the user which you can then implement additional logic to act on that returned data. You can update the content in their browser window based on the move the other player made, make a notification, whatever. In this case, I would have the AJAX make a call every X seconds (10, 20, 30 ???). That call would do several things: Update the last active timestamp for the user Check if the other user is still active. Since the other player will also have AJAX running, their last active timestamp should never be greater than the time you set for the AJAX calls to be made. So, if the other players last active timestamp is more than double that time period, I would let the user know that the other user has dropped Check if the other user has made a move (if it was their turn). If so, alert the user that the other user has made their move, show the results of that move, and tell the player it is now their turn. I'm sure there are some things I am leaving out, but the core of it is to use regular calls via AJAX to determine when users have completed a turn and to ensure they are still online. Be sure to use a JavaScript framework to do this (such as JQuery) instead of trying to build the AJAX code with native JavaScript.
  8. Psycho's post in CSS Active Dropdown was marked as the answer   
    OK, I gave you a lot of information, so let's take it one step at a time.
     
    1. Your main problem was that the function Active() was either applying the 'dropdown' class OR the 'active' class. The dropdown class is the one that applied the styles which create the dropdown affect. So, if you only apply the 'Active' class you lose the dropdown affect. You can apply multiple classes to the same element by separating them with spaces. So, you want to always apply the 'dropdown' class to all of the relevant element and add the 'active' class only to the one where it applies.
     
    2. Even if you were to properly apply the classes per #1 (Inactive class="dropdown" or Active class="dropdown active"), the definition for the 'active' class would do nothing because it is applied to the <li> element. The background colors you are seeing are due to styles applied to the anchor tags (<a></a>) not the <li> tags. That can be easily fixed, by changing the definition for active in the stylesheet to:
    li.active a {     background-color: #990000;   } What that means is for any <li> elements with the 'active' class, find any anchors (<a></a>) and apply the formatting.
     
    Those two things alone will directly fix your problem. But, your HTML follows a predictable format. Rather than copy/paste code and change labels, hrefs, etc. - create the content with a function. That way you know you won't have any copy/paste errors. This is especially helpful when you need to make changes to the format. So, I suggest creating an array that defines the menu (the parent links and the child links), then creating a function to produce the HTML output. This way you can easily add/edit/modify the menu links by just changing the array - which you can use as an include file. You would not have to modify core code to change the menu. Or, if you want to change the menu structure you just need to change the function. So, I provided an array for the current menu items you had as well as a function to create the menu - as well as fix the above issues.
     
    Here is a working script with all the pieces
    <?php   //hardcoded $webpage value for testing purposes $webpage = "drivers.php";   //definition of available menu $menuLinks = array(     'Home' => array(         'href' => 'menu.php'     ),     'Territory Manager' => array(         'href' => 'tms.php',         'children' => array (             'Add TM' => '#',             'Search TM' => 'search.php?search=TM'         ),     ),     'Sales' => array(         'href' => 'sales.php',         'children' => array (             'Add Sales Person' => '#',             'Search Sales' => 'search.php?search=sales'         ),     ),     'Drivers' => array(         'href' => 'drivers.php',         'children' => array (             'Add Driver' => '#',             'Search Drivers' => 'drivers.php'         ),     ),     'Passengers' => array(         'href' => 'passengers.php',         'children' => array (             'Add Passenger' => '#',             'Search Passengers' => 'search.php?search=passengers'         )     ) );   //Function to create html content for menu function createMenu($menuLinks, $webpage=false) {     $menuLinksHtml = '';     foreach($menuLinks as $parentLabel => $parentLink)     {         //Determine link if parent is active or not         $active = ($webpage == $parentLink['href']) ? ' active' : '';         $menuLinksHtml .= "<li class=\"dropdown{$active}\">\n";         //Determine if parent link has children         if(!isset($parentLink['children']))         {             //No child elements             $menuLinksHtml .= "<a href='{$parentLink['href']}'>{$parentLabel}</a>\n";         }         else         {             //Has child elements             $menuLinksHtml .= "<a href=\"javascript:void(0)\" class=\"dropbtn\">{$parentLabel}</a>";             $menuLinksHtml .= "<div class=\"dropdown-content\">\n";             foreach($parentLink['children'] as $childLabel => $childLink)             {                 $menuLinksHtml .= "<a href=\"{$childLink}\">{$childLabel}</a>\n";             }             $menuLinksHtml .= "</div>\n";                      }         $menuLinksHtml .= "</li>\n";     }     //Return HTML content     return $menuLinksHtml; }     ?> <html> <head> <style> /***** Begin Menu CSS *****/ ul {     width: 100%;     list-style-type: none;     margin: 0;     padding: 0;     overflow: hidden;     background-color: #333; }   li {     float: left; }   li a, .dropbtn{     display: inline-block;     font-size: 15px;     color: white;     text-align: center;     padding: 14px 16px;     text-decoration: none;     border-right: 1px solid #bbb; } /* Color of the main menu text when hovering */ li a:hover {      background-color: red; } /* Once the mouse has moved off the main menu button and is now highlighting a sub menu button, this defines what that main menu button color is */ .dropdown:hover{     background-color: red; } /* Color of main menu button when not selected */ .dropbtn {     background-color: 333; } li .dropdown {     position:relative;     display: inline-block;      } li:last-child {     border-right: none; } .dropdown-content{     display: none;     position: absolute;     background-color: #f9f9f9;     min-width: 160px;     box-shadow: 5px 7px 5px 0px rgba(0,0,0,0.2);     z-index: 1; } /* Links inside the dropdown */ .dropdown-content a{     color: black;     padding: 12px 16px;     text-decoration: none;     display: block;     text-align: left;     background-color: #f6f6f6; /* Sets background color of the drop down menu (not selected) */ } /* Change color of dropdown links on hover */ .dropdown-content a:hover {background-color: #ccc}   .dropdown:hover .dropdown-content{     display: block; } /* I have no idea what this does as it appears nothing... li a:hover:not(.active) {     background-color: #blue; } */ li.active a {     background-color: #990000;   } .active dropdown-content{     display: none;     position: absolute;     min-width: 160px;     box-shadow: 5px 7px 5px 0px rgba(0,0,0,0.2);     z-index: 1; } .active dropdown-content a{     color: black;     padding: 12px 16px;     text-decoration: none;     display: block;     text-align: left; } /***** End Menu CSS *****/ </style> </head>   <body>   <ul> <?php echo createMenu($menuLinks, $webpage); ?> </ul>   </body> </html> EDIT: Removed the Active() function that is not used in my code.
  9. Psycho's post in Queries equal same amount of rows but should not was marked as the answer   
    I'm making some assumptions here, but I would think that a vote should indicate a vote for or against the issue. But, your logic seems to imply that votes are only to indicate a "for" vote and all users must for for in order for it to pass. That seems like odd logic. Even if a unanimous decision is required, you should have some allowance for when someone doesn't cast a vote.
     
    Plus, you can easily determine 1) How many voters there are, 2) How many users have votes, and 3) The results of the vote with a single query. You don't state whether the votes table has an identifier for the user who casts a vote - but it should.
     
    Query
    SELECT COUNT(u.user_id) as users,        COUNT(v.vote_id) as votes,        (COUNT(u.user_id)=COUNT(v.vote_id)) as passed FROM votes v RIGHT JOIN users u   ON  v.user_id = u.user_id   AND v.motion_id = :motion_id Results would look something like this (3 of 5 users have voted)
    users | votes | passed   5       3        0 Or this (5 of 5 users have voted)
    users | votes | passed   5       5        1
  10. Psycho's post in substitute array keys was marked as the answer   
    Change
    echo "$row<br>"; To
    echo "{$d[$row][0]}<br>";
  11. Psycho's post in Math From Filesize was marked as the answer   
    Here's a class to get the duration of an MP3 file from the header information.
     
    http://www.zedwood.com/article/php-calculate-duration-of-mp3
  12. Psycho's post in input select field not working was marked as the answer   
    What "problem" are you having - exactly. What IS getting saved in the database? Or, are you getting errors? If so, what are they?
     
    Here are a few things you should verify:
     
    1. Do a View Source on the form page and inspect the Select Options are properly formatted and that their values are the IDs that you expect.
     
    2. Run this in the code the handles the form submission to verify the complete and correct data is being submitted
     
    echo "<pre>".print_r($_POST, 1)."</pre>";  
    3. echo the query tot he page to ensure it is correct. Also, you can copy/paste the derived query into your database management console (e.g. PHPMyAdmin) to verify it is valid and see if there are any errors. Pro tip: Create and test your queries in a management console first (with hard coded data). Once you have them working as you want - then put them in your code replacing with the dynamic values.
     
     
    NOTE 1: Your code is wide open to SQL injection. You should be using prepared statements.
     
    NOTE 2: Who are you to say what characters may be in a person's name? What about a person with a hyphentated name "Julie Brown-Smith" or what about someone with diacritic characters in their name: "Robert Muñoz"
  13. Psycho's post in Trying to add days to a date, failing miserably.. was marked as the answer   
    I don't think this will work:
    $del_tim_holder_1[count($del_tim_holder_1)] Assuming a zero based index, an array with a count of '3' would have indexes of '0', '1', & '2'. There would be no value with an index of '3'. You could instead use array_pop or, instead of having to use split/explode first to create an array, just use string functions (see example below).
     
    Also, rather than only put in the logic for the interval in the function, I would suggest just passing the $del_tim_holder_0 value and have the function do all the logic to return the applicable date string.
    private function calculateDate($intervalStr) { //Get value following last ':' and ensure a number     $inervalWeeks = intval(substr(strrchr($intervalStr, ":"), 1)); //Convert number to weeks     $intervalDays = $inervalWeeks * 7; //Create a date intervale     $interval     = new DateInterval("P{$intervalDays}D"); //Create current date object     $currDate     = new DateTime(date("d.m.Y")); //Apply the interval and convert to string     $newDate      = $currDate->add($interval)->format('d.m.Y');     return $newDate; }   $del_tim_holder_0 = "15:18:21"; $this->date = $this->calculateDate($del_tim_holder_0); // $this->date = '13.07.2017'
  14. Psycho's post in Form Validation not working was marked as the answer   
    I'll just say that what you are doing is probably not needed and (if you don't have similar validation on the back end) completely useless.
     
    However, your problem is that your current "test" is trying to see if the value contains the entire string of "!\"·$%&/()=?¿@#¬". You need to create a regular expression patter to look for any character.
     
    Plus, I suspect one of your other lines in the failure scenario is failing, probably this one
     
    document.signup.char_name.focus();  
    You should pass the form element by reference to the function instead of using getElementById()
     
    Also, you should use the onchange event - otherwise the logic will get caught in an infinite loop. When the alert is displayed, the act of the user clicking the OK will initiate another onblur event.
     
     
    function checkInput(inputObj) {         var user_input = inputObj.value; var notgood = /[!"·$%&\/()=?¿@#¬]/;   if ( !notgood.test(user_input) ) {         document.getElementById('submitlink').removeAttribute('disabled');         document.getElementById('badInput').innerHTML = '';         return true;     }     else     {         document.getElementById('submitlink').setAttribute('disabled','disabled');         document.getElementById('badInput').innerHTML = 'Bad Input';         alert('Cannot use that character');         inputObj.focus();         return false;     }         }  
     
    <input type="text" name="char_name" value="" id="char_name" required=""  onchange="checkInput(this);"/>
  15. Psycho's post in Change background color based off value returned was marked as the answer   
    Create classes for the different colors you want. Then have the logic determine which class to use. Or, you can make this much easier by just creating styles named for the brands and then use the dynamic name in defining the class to use. No additional coding needed to set the color:
    <?php //Test values $row_rsStockDynoFk['vs_brand'] = "Honda"; $row_rsStockDynoFk['vs_yrmodsize'] = "Crx";   ?> <html> <head> <style> .brandHonda { background-color: #FFD9D5; } .brandHusky { background-color: #FED6F5; } .brandKawasaki { background-color: #D6F5D3; } .brandKTM { background-color: #FFE4CA; } .brandSuzuki { background-color: #FFFFD5; } .brandTM { background-color: #D5FFFF; } .brandYamaha { background-color: #DFDFFF; } </style> </head> <body>   <div class="lvl1-4-5 brand<?php echo $row_rsStockDynoFk['vs_brand']?>"><?php echo $row_rsStockDynoFk['vs_brand']; ?></div> <div class="lvl1-4-6"><?php echo $row_rsStockDynoFk['vs_yrmodsize']; ?></div>   </body> </html>
  16. Psycho's post in Error when checkbox is checked. was marked as the answer   
    You need to give your form fields meaningful names. "checkbox" is not a good name for a form field.
     
    One glaring problem is that you have multiple fields with the same name
     
     
  17. Psycho's post in get 10 records from each category was marked as the answer   
    I did say that code was not tested. I don't have your database or other required files to run that code. I expect you to check for any typos I made and fix them or provide the errors and I can assist.
     
     
     
     
    Well, your current query is sorting by p.id. If you want things to be grouped by category then you need to put logic in place to do that. The logic in the code I provided previously would do that. But, even once we get that working, you have another issue. If you want all the categories to be returned with only 10 products per category, you are going to need a somewhat more complex query. Give me some time. If you can provide a dump of the relevant tables, then I could actually test the code I provide.
  18. Psycho's post in Pictures rotating 90 degrees was marked as the answer   
    Have you tried displaying BOTH the original image and the resized images? My guess is that the original image will display with the correct orientation, but the resized image will not because the original image has the required EXIF data that the browser is applying while the resized image does not. The user manual for imagecreatefromjpeg() has the following user contributed note:
     
     
    Even though an image displays correctly on the iPhone does not mean it is really saved that way. The camera has a specific orientation and I suspect all images are saved with that default orientation. All the rotation implementation is likely just software based.
     
    For a PHP application, I would not rely upon EXIF information to determine how an image is displayed. I would instead convert the image (as the example with that note would do) so it does not depend on rotation. The reason is if you need to do any logic on the size of the image it would be more complicated. For example, if you will create the output differently based on the width of an image you would have to first check the EXIF data to determine if you should check the "width" or the "height" of the image based on what is the real width when displayed
     
    Since you already have a process to resize the original image go ahead and rotate the new image accordingly. If you also save the original image, then you should replace it with one that is not rotated as well.
  19. Psycho's post in Second onchange event was marked as the answer   
    Here's some revised code. Note that I created a new onchange process for the select list. The onchange is hard-coded to that specific select list, but the code is written to be adaptable to other select lists (which I assume you might have for different radio button options). If that is the case, change the identifier for the onchange event to apply to all of the select lists that you may want the same functionality for.
     
    Also, I made the first option in the select field enabled as it may have been the cause of part of your problem depending on the browser. I would either enable the "instruction" option or remove it. It was working for me when disabled (it would default to 1 when first clicking the radio button option), but I could see where there could be a browser specific issue.
     
     
    <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>   <script>   //Displaying select box when type radio button is clicked $(document).ready(function() { $("input[name=vertical]").on( "change", function() { var fieldGroupName = $(this).val(); var fieldGroupObj = $("#"+fieldGroupName); var selectListObj = $("#"+fieldGroupName+"_select"); fieldGroupObj.show(); $('#Pricelist_select').trigger("change"); } );   $("select[name=Pricelist]").on( "change", function() {    var selectID = $(this).attr('id'); var selectValue = $(this).val(); if(selectValue != "") { $.cookie(selectID, selectValue); } } );   });   </script>   <style>   #Pricelist { display: none; }   </style>   </head> <body> <div class="row">   <div class="col-md-6">     <div class="radio clip-radio radio-primary">         <input type="radio" id="radio3" name="vertical" value="Pricelist" />         <label for="radio3">Pricelist</label>     </div>     <div id="Pricelist" class="desc">       <div class="form-group">         <select class="cs-select cs-skin-elastic" name="Pricelist" id="Pricelist_select">           <option value="" select="selected">Select pricelist</option>           <option value="1">1</option>           <option value="2">2</option>         </select>       </div>     </div>     </div> </div>   </body> </html>
  20. Psycho's post in array messed up was marked as the answer   
    So, what's the problem? That is correct JSON format. If your issue is with the empty fields (lat & lng) those were already empty in your previous output, so converting to JSON will not put values there. Either the fields (event_lat & event_lng) are empty in those records or those are not the correct field names.
     
    Here's that same data in a more readable format
     
    [   {     "lat":"",     "lng":"",     "name":"Lobster Louie's Truck",     "address":"300 Pine, San Francisco, CA 94104",     "place":"300 Pine",     "hours":"8:00am - 10:00am",     "location":"Located at the corner of pine and 3rd."   },   {     "lat":"",     "lng":"",     "name":"Lobster Louie's Truck",     "address":"Terry Francois Blvd, San Francisco, CA",     "place":"The Yard at Mission Rock",     "hours":"11:00am - 3:00pm",     "location":"Located at the Yard"   } ]
  21. Psycho's post in How to pass PHP variable with ajax? was marked as the answer   
    OK, there are two problems with this line
    data: $('form').serialize, As requinix said, serialize is a function not a property. Function are called with parens: e.g. serialize().
     
    Also, you cannot call 'form' since you have three forms on your page. Even if you correct the serialize function it will always pick the last form (i.e. the 2 value). Fortunately, jquery gives you a way to use the data of the form that called the function. And, requinix gave the the proper way to call it in step #1 of his first response.
  22. Psycho's post in newbie question regarding inline form validation was marked as the answer   
    You should create functions (or classes) rather than putting everything in-line.
     
     
    function showForm($dbConnection) {     //Get list of authors     try     {         $result = $dbConnection->query('SELECT id, name FROM author');     }     catch (PDOException $e)     {         $error = 'Error fetching list of authors.' . '<br />' . $e -> getMessage();         include '../includes/error.php';         exit();     }     //Put values into array     foreach ($result as $row)     {         $authors_in_db[] = $row;     }     //Call the form script     include 'form.php';     exit(); }  
    Now, wherever you need to include the form call the function above.
  23. Psycho's post in How to transfer the contents from the webpage to a text file was marked as the answer   
    Here's a tutorial: http://www.tizag.com/phpT/filewrite.php
  24. Psycho's post in Regular Expression for ISBN number was marked as the answer   
    This should match any input that starts with 1 or more numbers with an optional letter at the end:
     
    preg_match_all('/\d+([a-zA-Z])?/')
  25. Psycho's post in order item status problem was marked as the answer   
    Ideally, I would have a separate table with the status descriptions and join it on the orders when querying those records. But, do do it in the code I can think of a couple other solutions in addition to lovephp's response:
     
     
    1. Use a switch statement
    switch($record["rstatus"]) {     case 0:         $status = 'waiting';         break;     case 1:         $status = 'shipping';         break;     case 2:         $status = 'delivered';         break; } 2. Use an array. Define the array at the top of the script such as thi
    $statusText = array(     0 => 'waiting',     1 => 'shipping',     2 => 'delivered' ); Then in the code to create the output, use something like this
    $status = $statusText[$record["rstatus"]];
×
×
  • 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.