Dev Shed Forums - PHP Development http://forums.devshed.com/ PHP Development forum discussing coding practices, tips on PHP, and other PHP-related topics. PHP is an open source scripting language that has taken the web development industry by storm. en Sat, 21 Apr 2018 02:15:00 GMT vBulletin 60 http://forums.devshed.com/images/misc/rss.png Dev Shed Forums - PHP Development http://forums.devshed.com/ Universal table build http://forums.devshed.com/php-development/980490-universal-table-build-new-post.html Fri, 20 Apr 2018 15:13:10 GMT This function is the one to create the TBODY rows. Overall, the idea is an IF EXISTS type thing, since only certain items will exist depending on which page is being viewed. *array_key_exists()* is in relation to the items returned by the MySQL query. The query I have is if there are any other suggestions to build/define $format or $display. PHP: --------- function insert_rows($keys,... This function is the one to create the TBODY rows. Overall, the idea is an IF EXISTS type thing, since only certain items will exist depending on which page is being viewed. array_key_exists() is in relation to the items returned by the MySQL query.

The query I have is if there are any other suggestions to build/define $format or $display.
PHP Code:

function insert_rows($keys$values) {

  unset(
$values['month']);

  
$currency0 = new NumberFormatter('en_US'NumberFormatter::CURRENCY);
  
$currency0->setAttribute(NumberFormatter::FRACTION_DIGITS0);
  
$currency2 = new NumberFormatter('en_US'NumberFormatter::CURRENCY);
  
$currency2->setAttribute(NumberFormatter::FRACTION_DIGITS2);

  
// check/define our values
  
$total 0;
  
$format = function($row) use ($currency0$currency2, &$total) {
    
$total += array_key_exists('value'$row) ? $row['value'] : 0;
    
$row['active'] = array_key_exists('active'$row) ? ($row['active'] == 'Active' 'Inactive') : 'RemoveThisElement';
    
$row['paid'] = array_key_exists('paid'$row) ? ($row['paid'] == 'X' '') : 'RemoveThisElement';
    
$row['comment'] = array_key_exists('comment'$row) ? ' (' $row['comment'] . ')' 'RemoveThisElement';
    
$row['comments'] = array_key_exists('comments'$row) ? $row['comments'] : 'RemoveThisElement';
    
$row['value'] = array_key_exists('value'$row) ? (strlen($row['value']) > $currency2->formatCurrency($row['value'], 'USD') : '') : 'RemoveThisElement';
    
$row['adj_value'] = array_key_exists('adj_value'$row) ? (strlen($row['adj_value']) > $currency2->formatCurrency($row['adj_value'], 'USD') : '') : 'RemoveThisElement';
    
$row['limit'] = array_key_exists('limit'$row) ? (strlen($row['limit']) > '/' $currency0->formatCurrency($row['limit'], 'USD') : '') : 'RemoveThisElement';
    
$row['date'] = array_key_exists('date'$row) ? date_create($row['date'])->format('m/d/Y') : 'RemoveThisElement';
    return 
$row;
  };
  
// process a row
  
$values array_map($format$values);
  
// remove useless items
  
foreach(array_keys($values'RemoveThisElement') as $key) {
    unset(
$array[$key]);
  }

  
// format for display
  
$display = array(
    
// header => function($row) { return displayable value; }
    
'Status' => function($row) { return $row['active']; },
    
'Paid' => function($row) { return $row['paid']; },
    
'Due Date' => function($row) { return $row['date']; },
    
'Amount' => function($row) { return $row['value']; },
    
'Account (Comment)' => function($row) { return $row['name'] . $row['comment']; },
    
'Account Name' => function($row) { return $row['name']; },
    
'Adj. Amount' => function($row) { return $row['adj_value']; },
    
'Comments' => function($row) { return $row['comments']; },
    
'Total Due / Limit' => function($row) { return $row['value'] . $row['limit']; },
    
'As Of...' => function($row) { return $row['date']; }
  );

  
$display array_intersect_key($displayarray_flip($keys));

  
$rows NULL;
  foreach(
$values as $value) {
    
$rows .= '        <TR>';
    foreach(
$display as $header => $formatter) {
      
$rows .= '<TD>' $formatter($value) . '</TD>';
    }
    
$rows .= '</TR>' "\n";
  }

  return 
$rows;



The following code is the simple call of the previous function:
PHP Code:

    foreach($tables as $rows) {
      
$table .= '      <TABLE>
. (isset($rows['month']) ? '<TR><TH>' $rows['month'] . '</TH></TR>' NULL) . '
insert_headers($values['headers']) . '
insert_rows($values['headers'], $rows) . '
      </TABLE>' 
"\n";
    } 

The foreach() simply runs more than once in the occasion there are multiple tables, such as a yearly page holding multiple months. ]]>
PHP Development Triple_Nothing http://forums.devshed.com/php-development-5/universal-table-build-980490.html
Using Database Fields in a User-Defined Email http://forums.devshed.com/php-development/980489-using-database-fields-user-defined-email-new-post.html Fri, 20 Apr 2018 10:52:28 GMT Hi: I developed a system in PHP/MySQL which has an email blast system so users can login and send emails to their customers. The system uses the SendGrid API to actually send the emails but the boss of the email is composed by the user in a form field which uses the CKEditor (ckeditor.js) script on a PHP page. Does anyone know a good way that I could allow the user to incorporate data... Hi:

I developed a system in PHP/MySQL which has an email blast system so users can login and send emails to their customers. The system uses the SendGrid API to actually send the emails but the boss of the email is composed by the user in a form field which uses the CKEditor (ckeditor.js) script on a PHP page.

Does anyone know a good way that I could allow the user to incorporate data fields from the MySQL database in the body of his text? i.e. he would be able to say "Dear <<customer>>...." and select a predefined data field to incorporate into the text.

Any comments greatly appreciated. ]]>
PHP Development SeanF http://forums.devshed.com/php-development-5/using-database-fields-user-defined-email-980489.html
Insert a variable along with results from a select http://forums.devshed.com/php-development/980461-insert-variable-results-select-new-post.html Sun, 15 Apr 2018 06:48:25 GMT Hi,

I am using PDO and have a query that is insert and select. The insert, inserts values form the subsequent select statement,
however I want to add a value that is not in the select statement. Off this example what would be the most effective way of inserting the date
variable along with the other two from the select?

PHP Code:

$date "4/14/2018";

  
$test1 $DB_con->prepare("INSERT INTO test_table (name, address)
                 SELECT DISTINCT(users.name), file.address FROM user_details as users 
INNER JOIN file_details as file ON users.name = file.name where etc etc 

]]>
PHP Development genista http://forums.devshed.com/php-development-5/insert-variable-results-select-980461.html
MySQL search http://forums.devshed.com/php-development/980460-mysql-search-new-post.html Sat, 14 Apr 2018 03:21:20 GMT I have day of the week (int) hour (int) and minute (int) as three different columns. How can I search for records using each of these as time and day of week (not a specific date)? I have day of the week (int) hour (int) and minute (int) as three different columns.

How can I search for records using each of these as time and day of week (not a specific date)? ]]>
PHP Development NZ_kiwis http://forums.devshed.com/php-development-5/mysql-search-980460.html
Adding Rows to a Google Timeline Chart http://forums.devshed.com/php-development/980459-adding-rows-google-timeline-chart-new-post.html Fri, 13 Apr 2018 21:05:04 GMT ISSUE
I need to know if I need to add extra rows.

WHAT AND WHY
Essentially i'm using a Google Timeline chart as a visual schedule.

My chart is set up Monday-Sunday

I know i'll have $X vehicles which are all used 24 hours a day, this number of vehicles is a variable and changes when vehicles enter or exit the fleet.

HOW I'M DOING IT
Each trip is saved in a DB. I'm looping through result on a database search and adding data to my google timeline chart as I go.

The database has the following format (All columns are Int)
RowNum
DepDay
DepHour
DepMin
ArrDay
ArrHour
ArrMin

So, Monday row 1, 7am run for 1 hours looks like

RowNum: 1
DepDay: 1
DepHour: 7
DepMin: 0
ArrDay: 1
ArrHour: 8
ArrMin:0

and Sunday 2 hour trip at 11pm

RowNum: 1
DepDay: 7
DepHour: 23
DepMin: 0
ArrDay: 1
ArrHour: 1
ArrMin:0

When adding this to my chart, I'm cutting this one in half. Finishing the trip at midnight, adding the remainder onto RowNum +1.
So if I had these two stored, I'd see 2 rows which two trips. It works fine.

ISSUE
Let's say $X = 3, I actually want to show a third and blank row now, the reason being as it shows my fleet utilization is poor.

How can I show this. Any DB query show's 1 row is required by logic but I've created two so need one more not two.

If Sunday trip was done on a Saturday, it wouldn't go into a new week and I'd need two new blank rows.

Hopefully this makes sense. ]]>
PHP Development NZ_kiwis http://forums.devshed.com/php-development-5/adding-rows-google-timeline-chart-980459.html
Issue converting JSON to PHP http://forums.devshed.com/php-development/980458-issue-converting-json-php-new-post.html Fri, 13 Apr 2018 13:53:47 GMT Im trying to convert a JSON feed into PHP but coming up against an issue:

This is the feed:

Code:

{"consumer_reviews_api": {"reviews": [{"value_rating": "5.0", "found_trader_on_trustatrader": false, "punctuality_rating": "5.0", "trader_reply": "", "would_recommend": true, "date_of_work": "29th March 2018", "comments": "Utility pros have worked with us on various projects over the last 4 months  whilst we are undertaking renovations and have been nothing short of EXCELLENT. Despite having new 'items' added almost on a weekly basis they have undertaken every task with professionalism and a willingness to get the job done. I would strongly recommend this company for efficient, friendly and professional service", "quality_rating": "5.0", "average_rating": "5.00", "reviewer_name": "Martin Chick", "initial_impression_rating": "5.0", "cleanliness_rating": "5.0", "id": 279103, "overall_rating": "5.0"}, {"value_rating": "5.0", "found_trader_on_trustatrader": false, "punctuality_rating": "5.0", "trader_reply": "", "would_recommend": true, "date_of_work": "26th March 2018", "comments": "Haven\u2019t had the bill yet but previous work fairly priced. Feel very confident in his work", "quality_rating": "5.0", "average_rating": "5.00", "reviewer_name": "Eurem Matthews", "initial_impression_rating": "5.0", "cleanliness_rating": "5.0", "id": 278800, "overall_rating": "5.0"}, {"value_rating": "5.0", "found_trader_on_trustatrader": true, "punctuality_rating": "5.0", "trader_reply": "", "would_recommend": true, "date_of_work": "14th March 2018", "comments": "Ian was great, arrived on time, carried out work neatly, swiftly and cleanly and even kindly did a little extra that I only briefed in when he arrived.  Ian fitted two new sink wastes, removed and refitted a radiator and resealed a wet area for me. Good value, I'll use him again and would definitely recommend.", "quality_rating": "5.0", "average_rating": "5.00", "reviewer_name": "E Lowndes", "initial_impression_rating": "5.0", "cleanliness_rating": "5.0", "id": 279725, "overall_rating": "5.0"}, {"value_rating": "5.0", "found_trader_on_trustatrader": false, "punctuality_rating": "5.0", "trader_reply": "", "would_recommend": true, "date_of_work": "8th March 2018", "comments": "This is the second time we have used Utility Pros and would highly recommend Ian. He carried out a routine service of our gas boiler and was very thorough and helpful; he even fixed a problem with one of the radiators for us while he was here. Everywhere was left really tidy afterwards and the boiler was noticeably quieter after the service.", "quality_rating": "5.0", "average_rating": "5.00", "reviewer_name": "Charlie  Hamilton ", "initial_impression_rating": "5.0", "cleanliness_rating": "5.0", "id": 278705, "overall_rating": "5.0"}, {"value_rating": "4.0", "found_trader_on_trustatrader": true, "punctuality_rating": "5.0", "trader_reply": "", "would_recommend": true, "date_of_work": "5th March 2018", "comments": "Utility Pros completed the installation of new Grant Oil Boiler, replacement of two radiators and fine tuning the radiators balancing. In summary Ian always arrived at the agreed time and worked long hours to ensure the job was completed to schedule. He is polite, professional and very tidy in his work. Of particular note Ian is responsive to any follow-up work required after the initial installation to ensure the system is working as it should be. Client satisfaction is at the core of his business and I have no hesitation in recommending Ian (Utility Pro\u2019s) for all heating related work.", "quality_rating": "5.0", "average_rating": "4.83", "reviewer_name": "Vaughn Sadler", "initial_impression_rating": "5.0", "cleanliness_rating": "5.0", "id": 279727, "overall_rating": "5.0"}], "trader": {"total_page_count": 7, "average_rating": "4.93", "company_name": "Utility Pros UK Limited", "total_review_count": 35}, "params": {"username": "UTILITYPROS01", "page": 1, "reviews_per_page": 5}}}
This is the PHP code:

PHP Code:

                                             foreach ($characters as $character) {
                                                      
$rating $character->overall_rating;
                                                      
$name $character->reviewer_name;
                                                      
$comments $character->comments;
                                                      
$date $character->date_of_work;
                                                      

                                              
$reviewNum++;
                                        } 


The problem im having is with the first part of the JSON feed:

{"consumer_reviews_api": {"reviews":

When this part isnt included in the feed, all the above works fine. But this is part of the feed (unfortunatly) and I dont understand how to modify the PHP code to see past this. ]]>
PHP Development saltdigital http://forums.devshed.com/php-development-5/issue-converting-json-php-980458.html
Replace 1 with A and A with 1 http://forums.devshed.com/php-development/980456-replace-1-1-a-new-post.html Thu, 12 Apr 2018 21:55:43 GMT I have a dynamic number of "rows".

I want to replace the numbering of each row to be A, B , C etc etc.

So how can I change 1 to be A, 26 to be Z and visa versa.

To complicate things, how can I do 27 = AA? ]]>
PHP Development NZ_kiwis http://forums.devshed.com/php-development-5/replace-1-1-a-980456.html
<![CDATA[strtotime('now') Vs strtotime(date('Y-m-d'))]]> http://forums.devshed.com/php-development/980448-strtotime-vs-strtotime-date-new-post.html Wed, 11 Apr 2018 15:04:48 GMT Hello;

I wanna see if $date is today or future.

The fact that I have to check if($date==date('Y-m-d')) is not good.

PHP Code:

public function is_date_in_future($date)
              {
                if(
$date==date('Y-m-d'))
                  {
                    return 
true;
                  }
                if(
strtotime($date) >= strtotime('now')) 
                  {
                    return 
true;
                  }
              } 

Why strtotime('now') and strtotime(date('Y-m-d')) return diff things? ]]>
PHP Development English Breakfast Tea http://forums.devshed.com/php-development-5/strtotime-vs-strtotime-date-980448.html
Regexers... Is this reliable url validation? http://forums.devshed.com/php-development/980440-regexers-reliable-url-validation-new-post.html Tue, 10 Apr 2018 20:06:16 GMT Is this reliable url validation? PHP: --------- public function valid_url($str) { if (empty($str)) { return FALSE; } Is this reliable url validation?
PHP Code:

    public function valid_url($str)
    {
        if (empty(
$str))
        {
            return 
FALSE;
        }
        elseif (
preg_match('/^(?:([^:]*)\:)?\/\/(.+)$/'$str$matches))
        {
            if (empty(
$matches[2]))
            {
                return 
FALSE;
            }
            elseif ( ! 
in_array(strtolower($matches[1]), array('http''https'), TRUE))
            {
                return 
FALSE;
            }

            
$str $matches[2];
        }

        
// PHP 7 accepts IPv6 addresses within square brackets as hostnames,
        // but it appears that the PR that came in with https://bugs.php.net/bug.php?id=68039
        // was never merged into a PHP 5 branch ... https://3v4l.org/8PsSN
        
if (preg_match('/^\[([^\]]+)\]/'$str$matches) && ! is_php('7') && filter_var($matches[1], FILTER_VALIDATE_IPFILTER_FLAG_IPV6) !== FALSE)
        {
            
$str 'ipv6.host'.substr($strstrlen($matches[1]) + 2);
        }

        return (
filter_var('http://'.$strFILTER_VALIDATE_URL) !== FALSE);
    } 

It returns true for almost anything. The writer says "anything" could be a valid url on local host. ]]>
PHP Development English Breakfast Tea http://forums.devshed.com/php-development-5/regexers-reliable-url-validation-980440.html
How To Grab Mysql Tbl Column Names ? http://forums.devshed.com/php-development/980439-grab-mysql-tbl-column-names-new-post.html Tue, 10 Apr 2018 19:58:46 GMT Folks,

I'm trying to grab the column names. How to do this ?
Ok, as a beginner, let me think like a pro.
Imagine I suddenly change tbl column names. Now, in the php script, gonna have to manually update those lines where the column names are referenced or mentioned. Can't be doing all this on hundreds of lines and so best write a script so it will do all the grabbing and updating on the appropriate lines (so to speak) via the function's value.
Here's my nasty nasty attempt:
PHP Code:

<?php 

    $sql 
"SHOW COLUMNS FROM users";
    
$result mysqli_query($conn,$sql);
    while(
$row mysqli_fetch_array($result)){
    ${
$row['Field']} = $_SESSION["{$row['Field']}"]."<br>";
    echo ${
$row['Field']}."<br>";
    echo 
$_SESSION["{$row['Field']}"]."<br>";
    }
    
/*
    $sql = "SHOW COLUMNS FROM users";
    $result = mysqli_query($conn,$sql);
    while($row = mysqli_fetch_array($result)){
    $row = $_SESSION["{$row['Field']}"]."<br>";
    }
    
    $_SESSION["name"] =  "Niklesh";
    $row = ["Field"=>"name"];
    ${$row['Field']} = $_SESSION["{$row['Field']}"]."<br>";
    echo $name;
    */
    
?>

Look at the 2 commented parts to get an idea how many other ways I attempted. None are working. The code I have now really should have worked. Anyway, I tried my best. Let's see what you got up your sleeves! ;)

Thanks! ]]>
PHP Development UniqueIdeaMan http://forums.devshed.com/php-development-5/grab-mysql-tbl-column-names-980439.html
Converting Text Block to an Array http://forums.devshed.com/php-development/980437-converting-text-block-array-new-post.html Tue, 10 Apr 2018 11:04:47 GMT client->suppression()->blocks()->get(null, $query_params); $records =...]]> I am using an API for an email system called SendGrid. I am trying to get all of the send errors from emails that have been sent.

The syntax of the API call is:
PHP Code:

$query_params json_decode('{"start_time": $start_time, "limit": 3, "end_time": $end_time, "offset": 1}');
$response $sg->client->suppression()->blocks()->get(null$query_params);
$records $response->body(); 

This returns block of text which I can successfully print to the screen using:
PHP Code:

echo "<br/><br/>Response Body:<br/> $records"

which returns something like the following:
Quote:

Response Body records
[{"created":1523202634,"email":"jaxxxxer@watxxxxa.gov","reason":"550 5.4.317 Message expired, cannot connect to remote server","status":"5.4.317"},{"created":1523198214,"email":"xxxxller@xxxx.com","reason":"550 5.4.317 Message expired, cannot connect to remote server","status":"5.4.317"}, ....
originally, I thought this was an array but since I can print it using "echo" it must be plain text.

What's the best way to convert this to a multidimensional array so I can search on / report out the discrete elements? ]]>
PHP Development SeanF http://forums.devshed.com/php-development-5/converting-text-block-array-980437.html
Setting timezone With Codeigniter http://forums.devshed.com/php-development/980430-setting-timezone-codeigniter-new-post.html Mon, 09 Apr 2018 01:24:26 GMT Hi;

I read in a couple places to set the timezone in CI, use config file like
PHP Code:

date_default_timezone_set('America/New_York'); 


However, I get users to set the timezone in their account like this


PHP Code:

$this->data['timezones'] = DateTimeZone::listIdentifiers(DateTimeZone::ALL); 

Code:

<form class="form-inline" action = "<?php echo base_url('account/update');?>" method = "post">
  <select name = "timezones" class="form-control">
    <?php
      foreach($timezones as $tz=>$val)
        {
        ?><option value="<?php echo $val;?>"
          <?php
          if($details['timezone']==$val)
            {
              ?> selected = "selected" <?php
            }
            ?>
            ><?php echo $val;?></option><?php
        }?>
  </select> &nbsp;&nbsp;<input type="submit" class="btn btn-danger btn-sm" value="Update Timezone >>">
 </form>


I am pretty sure it's not right to access the database before loading the config file.

So how can I load the timeszone from database before loading config?

Tanx ]]>
PHP Development English Breakfast Tea http://forums.devshed.com/php-development-5/setting-timezone-codeigniter-980430.html
<![CDATA[Why can't we assign properties in Codeigniters construct?]]> http://forums.devshed.com/php-development/980429-cant-assign-properties-codeigniters-construct-new-post.html Mon, 09 Apr 2018 01:05:31 GMT login_library->is_logged(); $this->data['timezones'] = DateTimeZone::listIdentifiers(DateTimeZone::ALL);]]> Why can't we assign properties in Codeigniters construct?

PHP Code:

public function __construct()
        {
            
parent::__construct();
            
$this->login_library->is_logged();
            
$this->data['timezones'] = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
        } 


Can't access $timezones in views. But if I do
PHP Code:

public function index()
        {
            
parent::__construct();
            
$this->login_library->is_logged();
            
$this->data['timezones'] = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
        } 

Then I can.

How come and what's the logic behind it? ]]>
PHP Development English Breakfast Tea http://forums.devshed.com/php-development-5/cant-assign-properties-codeigniters-construct-980429.html
What happened to PHP market in early 2013? http://forums.devshed.com/php-development/980425-happened-php-market-2013-a-new-post.html Sun, 08 Apr 2018 17:34:15 GMT Just curious... Any idea why this (http://prntscr.com/j2jxwb) happened to Codeigniter in early 2014? Just curious...

Any idea why this happened to Codeigniter in early 2014? ]]>
PHP Development English Breakfast Tea http://forums.devshed.com/php-development-5/happened-php-market-2013-a-980425.html
Easiest way to validate mysql date format in php? http://forums.devshed.com/php-development/980424-easiest-validate-mysql-date-format-php-new-post.html Sun, 08 Apr 2018 16:11:45 GMT Hi; how come there are a million different solutions for is_valid_mysql_date and none of them are the same? PHP: --------- if(is_valid_mysql_date($date)) { //return true if format is YYYY-MM-DD } Hi;

how come there are a million different solutions for is_valid_mysql_date and none of them are the same?
PHP Code:

if(is_valid_mysql_date($date))
{
  
//return true if format is YYYY-MM-DD


What's the best way to do this painlessly?

If I wanna use "checkdate " then I have to explode($query->result_array()[0]['date_added']);

If it's not a string then I get another error on exploding.

PHP Code:

$date explode("-"$query->result_array()[0]['date_added']);
                        if(isset(
$date[1]) && isset($date[2]) && isset($date[0]) )
                        {
                            if(
checkdate($date[1], $date[2], $date[0]))
                              {
                                
$datediff time() - strtotime($query->result_array()[0]['date_added']);
                                return 
floor($datediff / (60 60 24));
                              }
                            else 
                              {
                                echo 
"Invalid launch add date";exit();
                              }
                        }
                        else 
                          {
                            echo 
"Invalid launch add date!";exit();
                          } 

I wanna quick fix for this one. ]]>
PHP Development English Breakfast Tea http://forums.devshed.com/php-development-5/easiest-validate-mysql-date-format-php-980424.html