Jump to content

soycharliente

Members
  • Posts

    1,416
  • Joined

  • Last visited

Posts posted by soycharliente

  1. I don't need help anymore. I spent the last 30-45 minutes painstakingly laying out my problem only to figure it out just before hitting submit while reading it over one final time. So, thank you for continuing to offer this forum as a resource online so I could do some rubber duck debugging.

    I haven't been active on here in quite a while, so I am glad to be doing some programming again so I can start contributing content/answers more.

    Solution: I copied some code from the PHP manual and forgot to change the variable being referenced by mysqli_commit from the example variable to my database connection reference. (And didn't notice over the course of ~2 hours.) When borrowing code, don't forget to use your variables everywhere!

    I cannot figure out why my mysqli prepared statement is not inserting into the database. I am not showing any errors anywhere. AUTO_INCREMENT is advancing by 1 each time which is strange. I can't view the prepared statement, but a manual INSERT in phpMyAdmin with what I believe is a valid query works fine. I am completely stuck and have no idea which way to go.

    Any help is much appreciated.

    PHP version: 7.4.19
    MySQL version: 5.6.48-88.0

    index.php

    database.php

    phpMyAdmin SQL dump

  2. Am I correct in thinking that my regex is returning the format error because encoding the input is creating a longer string behind the scenes? I cannot figure out why a string of less than 64 characters is throwing an error. I am using htmlentities() to make sure that the presence of a double quote doesn't break my HTML code. When I check the source code of the submitted form, things like & is converted to & and " to " as I would expect.

    <?
    $errors = FALSE;
    $e_name_e = FALSE; // error name empty
    $e_name_f = FALSE; // error name format
    
    if ( isset($_POST['submit']) && !empty($_POST['submit']) && $_POST['submit'] == "Add" )
    {
      $link = db();
      $raceName = mysqli_real_escape_string($link, htmlentities(trim($_POST['raceName'])));
      if ( empty($raceName) ) { $e_name_e = TRUE; $errors = TRUE; }
      if ( !preg_match('/^[a-zA-Z0-9 ~!@#$%^&*()+`{}|[\]\\\\:";\'<>?,.\/=_-]{1,64}$/', $raceName) ) { $e_name_f = TRUE; $errors = TRUE; }
      mysqli_close($link);
    }
    ?>
    <input type="text" value="<? echo ($errors) ? stripslashes($raceName) : '';?>" class="form-control" id="raceName" name="raceName" placeholder="Name of the race." maxlength="64" aria-labelledby="label_raceName" aria-describedby="help_raceName" />
    <? echo ($e_name_f) ? getFormError('help_raceName','Bad form.') : ''; ?>
    
    // In an included file
    function getFormError($id, $message, $html='')
    {
    	$html .= "<span class=\"fa fa-times fa-fw form-control-feedback\" aria-hidden=\"true\"></span>";
    	$html .= "<span id=\"{$id}\" class=\"help-block\">{$message}</span>".PHP_EOL;
    	return $html;
    }

    I hate pasting huge blocks of text. Let me know if I trimmed too much and a few more lines would help diagnose.

     

    If I am correct, I'm unable to figure out the best way to limit to 64 characters but also handle any special characters. Should I switch the {1,64} to + in the regex and just let the HTML maxlength attribute do all the talking?

     

    If I'm not correct, I would appreciate any direction. It's 1am local and I'm unable to move forward on this and need some sleep.

     

    I feel like there's a better way to do this altogether. Maybe with some prepared statements to accept input from a form? I will be writing the information to the database eventually. But right now I'm only having problems with the regex.

  3. I don't think you're showing enough code for us to really be able to help you. I'm going to make a HUGE assumption since I see a single quote at the very end of your HTML. Is all of this HTML output a single string with your PHP variables referenced inside?

    If that's the case, your syntax for referencing variables inside of quotes is incorrect.

    $output = 'My name is: ' . $name;
    $output = "My name is: " . $name;
    $output = "My name is: {$name}";

    If you're using single quotes, you must concatenate the variable. If you're using double quotes, you can either concatenate or wrap the variable inside of braces. There are more/other options when you include concepts like heredoc and nowdoc syntax.
     
    If this doesn't help, you're probably going to need to show more code. It may help you to read over the manual page for strings since it references how to call variables.

  4. TBH, and maybe it's me, since I don't do a lot of programming (it's a hobby not a career), small issues like trying to use/reference a variable I haven't defined yet tend to pop up more than I would like.

     

    Thanks for the help tracking down why the errors were showing up.

  5. Thanks all. Work and family life hasn't left much time for me to revisit this. I'm finally able to circle back.

     

    ^^^ while this may not have anything to do with what's going on, is the included file functions.php or is it lib.php? if it's lib.php, what else is in lib.php?

     

    I made a mistake when posting in that not only did I rename my files, but I also copy/pasted a bad version because I had made a copy of the file in order to pull out sensitive data to get help. The filename is lib.php and it's being referenced correctly.

     

    what html output do you get if you comment out the first call to the getAlert() function or make the first $html line just an assignment statement? if you get the correct result, with no fatal run-time error, i would say you have found a php bug, because there's no way the contents of your function, with or without concatenation/an undefined variable error, should have an effect on the simple html dom class.

     

    If I comment out the first getAlert() or make the $html line just an assignment statement, the result is the correct HTML and no errors/warnings.

     

    if php's error_reporting was listed as having no value, where/how were you 'seeing' the fatal run-time error at the start of this thread?

     

    The error was showing on my HTML page when the page loaded and tried to run the PHP code for generating output. It was just right there where the table should have been.

     

    to try and rule out a php bug, use a different variable name, $result, inside your function definition.

     

    Tested and everything functions the same in terms of errors when doing just a variable assignment and using the concatenating assignment operator.

     

    actually, i think i just found the problem. the simple html dom class is using error_get_last(), in the load_file() method, to check for errors, without checking what triggered the error. since your code is producing an error, this trips up the simplistic use of error_get_last() in the code.

     

    short-answer: always write code that DOESN'T throw any errors during normal execution, the undefined variable error in this case, and use proper application error handling logic, by actually testing values returned by function/method calls, rather than to blindly use error_get_last().

     

    So basically whoever authored the library didn't do a good job with the error reporting/checking? I feel like I've used the concatenating assignment operator before without the PHP Simple HTML DOM Parser, but I don't have an example to share. Seems like this is not a bug, I should define my variable before using it, and move on?

     

    Thanks!

  6. Hey mac_gyver, thanks for the reply.
     

    For the first version of the getAlert() function definition, you should be getting an undefined variable error - Notice: Undefined variable: html in your_file on line xxxx.

    Sorry if I wasn't more clear. The error is immediately after the function runs. getAlert() completes and echoes fine. I think it is originating in the for loop, but only happens when using the concatenating assignment operator inside of getAlert(). I added an echo statement at the top of the for loop to print an HTML comment and included that in the HTML output generated.
     

    if you are not seeing this error and it's not present in the 'view source' of the page either, either you don't have php's error_reporting set to E_ALL or you have something going on with error handling or output, such as a custom error handler or custom gzip/output buffer handler that's hiding what's really going on. make sure that php is reporting and displaying all errors. you should also turn off php's output_buffering setting (the default is on, in the php.ini.)

    I don't actually know where the php.ini file on my host is. When I do a phpinfo() dump into the browser, the error related fields are as follows for both Local Value and Master Value:
    error_append_string - no value
    error_log - syslog
    error_prepend_string - no value
    error_reporting - no value


    I put error_reporting(E_ALL); in the top of my functions.php file and it now shows:

    Notice: Undefined variable: html in /path/to/functions.php on line 40

    Line 40 is the first time we see $html in the getAlert() function. (I will highlight it below.) Strangely the block of code for getAlert() still executes and moves on.
     

    next, is your full actual code doing any header() redirects to that same page? often, unusual symptoms like this are due to a page getting requested twice, either by the browser or by the code itself, and you are seeing the result of the second request, which won't necessarily have any input data.  also, if your page is doing a header() redirect, does it have an exit; statement after the header() to stop program execution?

    Nope. I know it's a reflex question and I'm pretty happy to say that because of this forum it's one of the first things I check when I'm doing redirects.
     

    lastly, where are $pause and $array coming from in the posted code? you could have some code which you haven't shown us that is the actual cause of the problem.

    Both $pause and $array and hardcoded variables near the top of my index.php file. I didn't think the full-blown code would be very useful so my apologies again. Let me show more.

    functions.php

    <?php
    error_reporting(E_ALL);
    session_start();
    date_default_timezone_set('America/New_York');
    
    function db()
    {
      $hostname = 'localhost';
      $username = 'username';
      $password = 'hunter2';
      $database = 'database';
      
      $link = mysqli_connect($hostname, $username, $password, $database);
      if ( !$link ) {
        echo "Error: Unable to connect to MySQL." . PHP_EOL;
        echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
        echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
        exit;
      }
      return $link;
    }
    
    function mksf($link, $string)
    {
      $s = get_magic_quotes_gpc() ? stripslashes($string) : $string;
      return mysqli_real_escape_string($link, $s);
    }
    
    /**
     * Get HTML for alert.
     * @param string $type
     * @param int $dismissable
     * @param string $message
     * @return string $html
     */
    function getAlert($type,$dismissable,$message)
    {
      $dismiss = ($dismissable) ? ' alert-dismissible': '';
      $html .= "<div class=\"alert alert-{$type}{$dismiss}\" role=\"alert\">"; // Line 40
      $html .= ($dismissable) ? "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">×</span></button>" : '';
      $html .= $message;
      $html .= "</div>";
      return $html;
    }
    
    /**
     * Format swim, bike, run, and transition times.
     * @param string $text
     * @param string $tags
     * @param boolean $invert
     * @return string $text
     */
    function formatTime($time)
    {
      $pieces = explode(':',$time);
      if ( count($pieces) == 2 )
      {
        array_unshift($pieces,'00');
      }
      return sprintf('%02d:%02d:%02d',$pieces[0],$pieces[1],$pieces[2]);
    }
    
    /**
     * Strip all HTML tags and their content.
     * @param string $text
     * @param string $tags
     * @param boolean $invert
     * @return string $text
     */
    function stripTagsContent($text,$tags='',$invert=FALSE)
    {
      preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si',trim($tags),$tags);
      $tags = array_unique($tags[1]);
      if ( is_array($tags) AND count($tags) > 0 )
      {
        if ( $invert == FALSE )
        {
          return preg_replace('@<(?!(?:'.implode('|',$tags).')\b)(\w+)\b.*?>.*?</\1>@si','',$text);
        }
        else
        {
          return preg_replace('@<('.implode('|',$tags).')\b.*?>.*?</\1>@si','',$text);
        }
      }
      elseif ( $invert == FALSE )
      {
        return preg_replace('@<(\w+)\b.*?>.*?</\1>@si','',$text);
      }
      return $text;
    }
    
    ?>
    

    index.php



    <?php
    include_once('lib.php');
    include_once('simple_html_dom.php');
    
    $pause		= FALSE;
    $showComments	= FALSE;
    
    $rLink		= 'http://www.example.com/page.php';
    $rid		= '1234567890';
    $rshort		= 'example';
    $rlong		= 'Example Title';
    $bibs		= array(552, 874, 1767, 2507, 1618, 566);
    $results	= array();
    $swimTimes	= array();
    $t1Times	= array();
    $bikeTimes	= array();
    $t2Times	= array();
    $runTimes	= array();
    $totalTimes	= array();
    ?>
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="utf-8"/>
      <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
      <meta name="viewport" content="width=device-width, initial-scale=1"/>
      <title></title>
      <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css"/>
      <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" type="text/css"/>
      <link rel="stylesheet" href="style.css" type="text/css"/>
      <!--[if lt IE 9]>
        <script src="//oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
        <script src="//oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
      <![endif]-->
      <script src="//code.jquery.com/jquery-2.2.3.min.js" type="text/javascript"></script>
      <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" type="text/javascript"></script>
      <script src="jquery.numeric.min.js" type="text/javascript"></script>
      <script src="script.js" type="text/javascript"></script>
    </head>
    <body>
    
    <div class="container-fluid">
    <div class="row">
    <div id="results" class="col-xs-12">
    <?php
    if ( !$pause )
    {
      echo getAlert('info',1,'Trying to gather the data.').PHP_EOL;
      
      if ( !empty($bibs) )
      {
        foreach ( $bibs as $bib )
        {
          echo '<!-- For loop. -->'; // Added to see where error might be coming from.
          $html = new simple_html_dom();
          $html->load_file("{$rLink}?rid={$rid}&r={$rshort}&bib={$bib}");
          
          $header = $html->find("header",0);
          $name = trim(stripTagsContent($header->find("h1",0)->innertext));
          
          $overallRank = trim(stripTagsContent($header->find("div[id=div-rank]",0)->innertext));
          $divisionRank = trim(stripTagsContent($header->find("div[id=rank]",0)->innertext));
          
          $resultsTableWhite = $html->find("div[class=results-table-white]",0);
          $generalInfo = $resultsTableWhite->find("table[id=general-info]",0);
          $division = trim($generalInfo->find("td",4)->innertext);
          
          $atheleteDetails = $resultsTableWhite->find("table[id=athelete-details]",0);
          $swimTime = formatTime(trim($atheleteDetails->find("td",2)->innertext));
          $bikeTime = formatTime(trim($atheleteDetails->find("td",4)->innertext));
          $runTime = formatTime(trim($atheleteDetails->find("td",6)->innertext));
          $totalTime = formatTime(trim($atheleteDetails->find("td",->innertext));
          
          $atheleteTableDetails = $html->find("div[class=athlete-table-details]",0);
          $swimRank = trim(explode(":",$atheleteTableDetails->find("p",0)->innertext)[1]);
          $bikeRank = trim(explode(":",$atheleteTableDetails->find("p",1)->innertext)[1]);
          $runRank = trim(explode(":",$atheleteTableDetails->find("p",2)->innertext)[1]);
          $t1Time = formatTime(trim($atheleteTableDetails->find("table",3)->find("td",1)->innertext));
          $t2Time = formatTime(trim($atheleteTableDetails->find("table",3)->find("td",3)->innertext));
          
          $results[] = array(
            'name'		=> $name
            ,'bib'		=> $bib
            ,'division'	=> $division
            ,'swimTime'	=> $swimTime
            ,'t1Time'	=> $t1Time
            ,'bikeTime'	=> $bikeTime
            ,'t2Time'	=> $t2Time
            ,'runTime'	=> $runTime
            ,'totalTime'	=> $totalTime
            ,'overallRank'	=> $overallRank
            ,'divisionRank'	=> $divisionRank
            ,'swimRank'	=> $swimRank
            ,'bikeRank'	=> $bikeRank
            ,'runRank'	=> $runRank
          );
          
          if ( !in_array($swimTime,$swimTimes) ) { $swimTimes[] = $swimTime; }
          if ( !in_array($t1Time,$t1Times) ) { $t1Times[] = $t1Time; }
          if ( !in_array($bikeTime,$bikeTimes) ) { $bikeTimes[] = $bikeTime; }
          if ( !in_array($t2Time,$t2Times) ) { $t2Times[] = $t2Time; }
          if ( !in_array($runTime,$runTimes) ) { $runTimes[] = $runTime; }
          if ( !in_array($totalTime,$totalTimes) ) { $totalTimes[] = $totalTime; }
        }
        
        echo getAlert('success',1,'Results data gathered.').PHP_EOL;
        
        if ( !empty($results) )
        {
          sort($swimTimes);
          sort($t1Times);
          sort($bikeTimes);
          sort($t2Times);
          sort($runTimes);
          sort($totalTimes);
          
          echo "<table class=\"table table-hover table-condensed\">".PHP_EOL;
          echo getTableHeadFoot(array('Name','Division','OA Rank','Div Rank','SBR Ranks','Swim','T1','Bike','T2','Run','Total')).PHP_EOL;
          echo "<tbody>".PHP_EOL;
          foreach ( $results as $result )
          {
            switch ( $result['swimTime'] )
            {
              case $swimTimes[0]: $swimClass = ' gold'; break;
              case $swimTimes[1]: $swimClass = ' silver'; break;
              case $swimTimes[2]: $swimClass = ' bronze'; break;
              default: $swimClass = '';
            }
            switch ( $result['t1Time'] )
            {
              case $t1Times[0]: $t1Class = ' gold'; break;
              case $t1Times[1]: $t1Class = ' silver'; break;
              case $t1Times[2]: $t1Class = ' bronze'; break;
              default: $t1Class = '';
            }
            switch ( $result['bikeTime'] )
            {
              case $bikeTimes[0]: $bikeClass = ' gold'; break;
              case $bikeTimes[1]: $bikeClass = ' silver'; break;
              case $bikeTimes[2]: $bikeClass = ' bronze'; break;
              default: $bikeClass = '';
            }
            switch ( $result['t2Time'] )
            {
              case $t2Times[0]: $t2Class = ' gold'; break;
              case $t2Times[1]: $t2Class = ' silver'; break;
              case $t2Times[2]: $t2Class = ' bronze'; break;
              default: $t2Class = '';
            }
            switch ( $result['runTime'] )
            {
              case $runTimes[0]: $runClass = ' gold'; break;
              case $runTimes[1]: $runClass = ' silver'; break;
              case $runTimes[2]: $runClass = ' bronze'; break;
              default: $runClass = '';
            }
            switch ( $result['totalTime'] )
            {
              case $totalTimes[0]: $totalClass = ' gold'; break;
              case $totalTimes[1]: $totalClass = ' silver'; break;
              case $totalTimes[2]: $totalClass = ' bronze'; break;
              default: $totalClass = '';
            }
            $trophyIcon = ($result['divisionRank'] <= 5) ? " <span class=\"fa fa-trophy\"></span></td>" : '';
            
            echo "<tr>".PHP_EOL;
            echo "<td class=\"col-xs-2\">{$result['name']}</td>".PHP_EOL;
            echo "<td class=\"col-xs-1\">{$result['division']}</td>".PHP_EOL;
            echo "<td class=\"col-xs-1\">{$result['overallRank']}</td>".PHP_EOL;
            echo "<td class=\"col-xs-1\">{$result['divisionRank']}{$trophyIcon}</td>".PHP_EOL;
            echo "<td class=\"col-xs-1\">{$result['swimRank']}->{$result['bikeRank']}->{$result['runRank']}</td>".PHP_EOL;
            echo "<td class=\"col-xs-1{$swimClass}\">{$result['swimTime']}</td>".PHP_EOL;
            echo "<td class=\"col-xs-1{$t1Class}\">{$result['t1Time']}</td>".PHP_EOL;
            echo "<td class=\"col-xs-1{$bikeClass}\">{$result['bikeTime']}</td>".PHP_EOL;
            echo "<td class=\"col-xs-1{$t2Class}\">{$result['t2Time']}</td>".PHP_EOL;
            echo "<td class=\"col-xs-1{$runClass}\">{$result['runTime']}</td>".PHP_EOL;
            echo "<td class=\"col-xs-1{$totalClass}\">{$result['totalTime']}</td>".PHP_EOL;
            echo "</tr>".PHP_EOL;
          }
          echo "</tbody>".PHP_EOL;
          echo "</table>".PHP_EOL;
        }
        else
        {
          echo getAlert('danger',0,'Array is empty.').PHP_EOL;
        }
      }
      else
      {
        echo getAlert('danger',0,'No bibs.').PHP_EOL;
      }
    }
    else
    {
        echo getAlert('warning',0,'Data gather paused.').PHP_EOL;
    }
    ?>
    
    </div> <!-- /#results -->
    </div> <!-- /row -->
    </div> <!-- /container -->
    
    </body>
    </html>
    

    HTML output at the errors:



    <div class="row">
    <div id="results" class="col-xs-12">
    <br />
    <b>Notice</b>:  Undefined variable: html in <b>/path/to/functions.php</b> on line <b>40</b><br />
    <div class="alert alert-info alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>Trying to gather the data.</div>
    <!-- For loop. --><br />
    <b>Fatal error</b>:  Call to a member function find() on null in <b>/path/to/simple_html_dom.php</b> on line <b>1129</b><br />
    

    Thanks.

  7. Looking at the JavaScript version of the calculation:

    function calc()
    {
      var de = document.getElementById("l").value ;
      var nu = document.getElementById("n").value ;
      var pay = document.getElementById("p").value ;
      
      var n = nu * 12;
      var q1 = Math.log(1 + parseFloat(1/n));
      var q2 = Math.log(2);
      var q = parseFloat(q1/q2);
      
      var amt;
      var amt1 = Math.pow((1 + parseFloat(pay/de)),1/q).toFixed(4);
      var amt2 = parseFloat( Math.pow(amt1-1,q)).toFixed(4);
      
      amt = parseFloat(1200 * (amt2 - 1)).toFixed(2); 
      
      document.getElementById("op").value  = amt;  
    }
    

    Try something like this to get started:

    function calc($total_loan_amount, $total_number_of_payments, $payment_amount)
    {
      $p = $payment_amount;
      $a = $total_loan_amount;
      $n = $total_number_of_payments;
      
      $q = log(1 + (1/$n)) / log(2);
      
      $i = pow(pow(1 + ($p/$a), 1/$q) - 1, $q) - 1;
      
      return $i;
    }
    

    Absolutely no attention paid to data types, decimals, etc for the numbers.

  8. Does anyone have any information about why initial variable creation/assignment with the concatenating assignment operator causes errors?

    Fatal error: Call to a member function find() on null in /path/to/simple_html_dom.php on line ####.

    The reference to find() is a reference to PHP Simple HTML DOM Parser.

     

    Throws error after:

    function getAlert($type,$message)
    {
      $html .= "<div class=\"alert alert-{$type}\" role=\"alert\">";
      $html .= $message;
      $html .= "</div>";
      return $html;
    }

    Does not throw error after:

    function getAlert($type,$message)
    {
      $html = "<div class=\"alert alert-{$type}\" role=\"alert\">";
      $html .= $message;
      $html .= "</div>";
      return $html;
    }

    I've narrowed the problem down to when I initialize $html using the concatenating assignment operator as opposed to traditional variable assignment. Certainly I could return the string on a single line or move forward with traditional variable assignment. I think mostly my curiosity as to why I would be getting a null reference from a block of code that was working perfectly a few moments earlier is why I am posting this.

     

    My truncated code, which I feel is probably irrelevant, in case there's more to it than I imagine:

    <?php
    include_once('simple_html_dom.php');
    include_once('functions.php');
    ?>
    
    <!DOCTYPE html>
    <html lang="en">
    <body>
    <?php
    if ( !$pause )
    {
      echo getAlert('info','Trying to gather the data.');
      
      if ( !empty($array) )
      {
        foreach ( $array as $value )
        {
          $html = new simple_html_dom();
          $html->load_file("http://www.example.com?id={$value}");
          
          $header = $html->find("header",0);
          $name = trim($header->find("h1",0)->innertext);
          
          // More code
        }
      }
      else
      {
        // Empty array.
      }
    }
    else
    {
      // Paused.
    }
    ?>
    
    </body>
    </html>
    

    Please excuse my code. I took a programming sabbatical and I'm trying to get back in.

  9. for your multiple attribute to be able to send the multiple selections, the name needs to be an array - name ='selectDivision[]'

     

    That color-coding is clutch. I've never thought about highlighting the needed addition in that way. Thanks!

  10. I started out trying to do that, but when I click submit the URL comes back like this: index.php?Apply=Apply. "Apply" is the name and value of my submit button. Maybe that means my form is malformed. I took out all the options so it wasn't as long, but here's my form if you think it might help:

    <form class="form-horizontal" action="index.php" method="get">
    	<div class="container-fluid">
    		<div class="row">
    			<div class="col-xs-12 col-md-3">
    				<div class="form-group">
    					<label for="selectDivision" class="control-label sr-only">Division</label>
    					<select id="selectDivision" class="form-control" multiple>
    						<option value="25-29">25-29</option>
    						<option value="30-34">30-34</option>
    						<option value="35-39">35-39</option>
    					</select>
    				</div>
    			</div>
    			<div class="col-xs-12 col-md-3">
    				<div class="form-group">
    					<label for="selectGender" class="control-label sr-only">Gender</label>
    					<select id="selectGender" class="form-control" multiple>
    						<option value="M">M</option>
    						<option value="F">F</option>
    					</select>
    				</div>
    			</div>
    			<div class="col-xs-12 col-md-3">
    				<div class="form-group">
    					<label for="selectCountry" class="control-label sr-only">Country</label>
    					<select id="selectCountry" class="form-control" multiple>
    						<option value="CAN">CAN</option>
    						<option value="USA">USA</option>
    					</select>
    				</div>
    			</div>
    			<div class="col-xs-12 col-md-3">
    				<div class="form-group">
    					<input type="submit" class="btn btn-default btn-block" name="Apply" value="Apply"/>
    				</div>
    			</div>
    		</div>
    	</div>
    </form>
    
  11. Well old friends. We meet again. It's been over 2 years since my last post. Things look a little different around here... in a good way. Life has really crazy with work, school, home, etc. and I've finally gotten some time to work on a silly project in my free time. And of course I can't remember for the life of me how to write PHP code. Ha!

     

    I have an HTML table of (tabular) data displaying very well on a page. I would like to add some filters so that you can filter out data based on whatever criteria I decide is worth filtering on. I would like to apply the filters via URL parameters so I can hot-link to pre-filtered tables instead of forcing them to load the entire table and then filter every time.

     

    I'm having a bit of trouble making the leap from building the form with all the options (three <select multiple> elements each with a various number of options) to getting the choices into the URL.

     

    The only thing I've figured so far is to POST the data to a form handler page and then redirect back to the table page with some URL parameters. I would build the URL on the form handler page and run the query that generates the table based on what I can GET from the URL. I wasn't sure if this was the best way to go about it or not.

     

    Thanks for any tips/advice.

  12. $regexK = "\[\[(start|end)\$keep)\]\]"
    $regexR = "\[\[start:(?!$keep\])[^\]]+\]\](.*?)\[\[end:(?!$keep\])[^\]]+\]\]"

    Taking both of those pieces of advice, this seems to be getting the job done very well. I run the top one first to remove tags for what is kept and then the bottom one to remove all over pieces of information (including tags) for what doesn't match.

  13. The added \] after $keep is so that $keep=123 will not prevent [[start:1234]] from matching.

    I would not have thought about that edge case. Thanks!

     

    The easier way, is to first remove the tags around the content you want the user to keep. Then, remove everything you don't want the user to keep.

    This makes a lot of sense. Thanks!
  14. I'm working on a site that will make use of some custom tags. The idea is that depending on the visitor type, anything with tags wrapped around it will be hidden unless the type matches their type. The tags will help personalize content based on the visitor type. The tags will be structured like this: [[start:TYPE]]Content here.[[end:TYPE]]

     

    This works great for stripping out content that shouldn't be displayed for them:

    \[\[start\$remove)\]\](.*?)\[\[end\$remove)\]\]

     

    And this works great for preserving content that should be displayed for them:

    \[\[(start|end)\$keep)\]\]

     

    The problem that I'm having is that I have to formally list each type that I want to remove. I would prefer to simply remove all of the tags that have a type that is not their type. I cannot for the life of me apply the ^ flag which I thought would mean "not type" listed.

     

    \[\[start\^$keep)\]\](.*?)\[\[end\^$keep)\]\]

     

    Can someone help me understand why this doesn't work and what I need to look into for how to get this small tweak going?

     

    I'm working with the flavor of regex that Java uses. Thanks!

  15. Was this code you sent me correct?

     

    Apologies for not being more clear. When I said "Something like this will get you close" I was providing you with some pseudo code. I did not take time to load up a database with some sample data and write the code for you.

     

    Was this code you sent me correct? For example, is this literal: foreach ( $parts as $part )?

     

    Are you asking if that's how a foreach loop is structured?

     

    Did you "echo out the entire string at the end to see what it reads like and make sure that it's built correctly" before just adding the code and running it?

     

    What does the query look like? What are you wanting it to look like? What exactly looks out of order?

  16. I'm not 100% on the vocabulary to articulate what I need, so please bear with me.

     

    I inherited a server at work. I login through SSH and as soon as I get done typing in the password, it displays the last login date/time and a large ASCII drawing. I have tried looking in a number of places, but I cannot for the life of me figure out where this drawing is being pulled from. Reading around online leads me to looking at directories/files such as /etc/profile, /etc/profile.d, and ~/.bash_profile. I don't see anything related to this drawing.

     

    Anyone up for helping me through finding where this comes from?

  17. If I understand correctly what you're trying to do, what you get from getEscaped() is the search. So explode the string into multiple parts and create a separate LIKE statement for each word in the search.

     

    Something like will get you close. I would echo out the entire string at the end to see what it reads like and make sure that it's built correctly.

     

    $escaped = $this->_db->getEscaped($filter,true);
    $parts = explode(' ', $escaped); // Array of words
    foreach ( $parts as $part )
    {
    $search .= " LOWER(a.ad_headline) LIKE '%{$part}%' OR LOWER(a.ad_text) LIKE '%{$part}%'";
    }

     

    I'll also point out there you're running some code multiple times. I would abstract it out into variables.

     

    intval($filter) is being called twice.

    $filter = JString::strtolower($filter); is also being called twice.

    LOWER(a.ad_headline) is being referenced twice.

    $this->_db->getEscaped($filter,true) is being called FOUR times.

    And more than half your $search query is exactly the same.

     

    I can't see the rest of your switch, so I'm not 100% if it makes sense to pull them out, but I have a feeling it might.

     

    Are you working in Joomla? I tried to find what the getEscaped() function does and all I could find was Joomla documentation. As an FYI, there is a separate lobby for PHP Applications if you ever run into anything Joomla specific.

  18. Could you suggest any resources that are handy in learning PHP, as opposed to just pulling apart Wordpress? It seems like a pretty powerful tool to have in your toolbox :)

     

    Honestly just the manual. For me, I learned what PHP I know just by imagining websites and them trying to build them.

     

    What got me most of my knowledge, and this is no joke, was when I created a website exactly like Foursquare (except I did it 3 years before). Relational databases, login, sessions, statistics on database information, Google Maps, Google Charts, CSS, XHTML, image upload, and the list goes on.

     

    At work we have a pretty cool perk, which is a free account on lynda.com. They've got some good tutorials, but honestly just picking a scenario you don't know anything about and reinventing it is the best way to learn. You RTM, look through blog posts, and research how other people are doing it.

     

    It blew my mind 100 fold how complicated doing login can be. Password hash, password reset, expiring the hash, locked accounts, verifying email, thwarting attempted logins from "hackers" and the list goes on.

     

    TL;DR Imagine a scenario, RTM, and find other people doing it so you can ask questions. Books are ok, but hands on experience wins out for me.

×
×
  • 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.