Jump to content

Search the Community

Showing results for tags 'php'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. I'm currently passing values in my URL that I want to GET and insert in my controller class for filtering. My current URL looks something like this: http://localhost/reports/lists?source=Product1&status=4. Now to get the value of suppose source, I'm using the following code: let searchParams = new URLSearchParams(window.location.search); var status = searchParams.get('source'); Now I want this status variable to go to my controller class so that I can use it as 1 of my parameters for my model class: Full code: View Class: <?php $postd = json_encode(array_filter($post)); ?> <table id="item-list"> <tr> <th>Ref.No#</th> <th>Source</th> </tr> </table> <script> $(document).ready(function() { function sendreq(){ setpostdatas();cleartable();getleads(); } var userrole = "<?php echo $this->session->userdata('clientrole')?>"; var slug = '<?php echo $slug?>'; var postd = '<?php echo $postd; ?>'; if( userrole > 1 && userrole != 5){ $('#item-list').DataTable({ "processing": true, "stateSave": true, "serverSide": true, "ordering": false, "createdRow": function( row, data, dataIndex){ $(row).has( "div.overdueupdate" ).css('background-color','#FFC7CE'); }, "ajax": { url: "<?php echo site_url(); ?>reports/loadLeads", data: {slug: slug, postdata: postd}, type : 'POST', "dataSrc": function ( d ) { d.myKey = "myValue"; if(d.recordsTotal == 0 || d.data == null){ $("#item-list_info").text("No records found"); $("#item-list_processing").css("display","none"); } return d.data; } }, 'columns': [ {"data": "id", "id": "id"}, {"data": "refno", "refno": "refno"}, {"data": "source", "source": "source"}, ] }); } Controller Class: public function loadLeads($p=''){ $leadsource = $this->input->get('status'); if(isset($_POST['postdata'])){ if($_POST['postdata'] != null && $_POST['postdata'] != 'null'){ $post=$_POST['postdata']; } $post = json_decode($post,true); unset($post['slug']); unset($post['page']); $sort = $post['afsort']; if($sort == "asc"){ $sortQ = 'l.updated_date asc,'; }else if ($sort == "desc"){ $sortQ = 'l.updated_date desc,'; } } $offset = (int)$_POST['start'] ; $pstdatas = explode(',', $_POST['postdata']); unset($pstdatas['item-list_length']); if($this->session->userdata('clientrole') == 1 || $this->session->userdata('clientrole') == 5 ){ $content['leads']=$this->leads_model->get_pagination($_POST['length'],$offset,$where,'',false,$sortQ?$sortQ:'l.assign_status =\'Unassigned\' desc,',$all,$leadsource); }else{ $content['leads']=$this->leads_model->get_pagination($_POST['length'],$offset,$where,'',false,$sortQ?$sortQ:'l.assigned_date desc,',$all,$leadsource); } Now here in my controller class I want that AJAX variable to be passed so that I can use it my model query.
  2. I have a table that shows the redirect from and redirect to columns from my database. By default, all the records are shown, but there is a from and to filter I'm using to search by a particular redirect. Now there are a lot of times that after I input the filters, it gives me a Undefined variable: redirects error, but sometimes it works. Here is my code: View Class: <?php if ($redirects): ?> <form name="redirectform" action="admin/redirects" method="post"> <div> <input list="search-from-list" id="search-from" name="search-from" style="width:100%;"/> <datalist id="search-from-list"> <?php foreach ($allredirects as $allredirect){ ?> <option value="<?php echo $allredirect->from; ?>" id="<?php echo $allredirect->id; ?>" /> <?php } ?> </datalist> </div> <input type="hidden" name="linkid" id="linkid" /> <input type="hidden" name="linkidto" id="linkidto" /> <input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>"> </div> <input list="search-to-list" id="search-to" name="search-to" style="width:100%;" /> <datalist id="search-to-list"> <?php foreach ($allredirects as $allredirect){ ?> <option value="<?php echo $allredirect->to; ?>" id="<?php echo $allredirect->id; ?>" /> <?php } ?> </datalist> </div> </form> <table> <?php foreach ($redirects as $redirect): ?> <tr> <td><?php echo $from=str_replace('%', '*', $redirect->from);?></td> <td><?php echo $redirect->to;?></td> </tr> <?php endforeach ?> </table> <?php echo form_close() ?> </div> <?php else: ?> <div class="no_data">No Data</div> <?php endif ?> <script type="text/javascript"> $("#search-from").select(function(e){ var g = $('#search-from').val(); var id = $('#search-from-list').find("option[value='"+g+"']").attr('id'); $('#linkid').val(id); }); $("#search-to").select(function(e){ var g = $('#search-to').val(); var id = $('#search-to-list').find("option[value='"+g+"']").attr('id'); $('#linkidto').val(id); }); </script> Controller Class: public function index() { if(isset($_POST["search-from"]) && !empty($_POST["search-from"])){ if(isset($_POST["linkid"]) && !empty($_POST["linkid"])){ $from_id = $_POST["linkid"]; $this->template->redirects = $this->redirect_m->order_by('`from`')->get_by_id($from_id); } }else if(isset($_POST["search-to"]) && !empty($_POST["search-to"])){ if(isset($_POST["linkidto"]) && !empty($_POST["linkidto"])){ $to_id = $_POST["linkidto"]; $this->template->redirects = $this->redirect_m->order_by('`to`')->get_by_id($to_id); } }else{ $this->template->redirects = $this->redirect_m->order_by('`from`')->limit($this->template->pagination['limit'], $this->template->pagination['offset'])->get_all(); } $this->template->allredirects = $this->redirect_m->order_by('`from`')->get_all(); $this->template->build('admin/index'); } Here basically what I'm doing is that the input with the ids search-from and search-to hold an autocomplete function for the redirect links. I have other 2 input fields linkid and linkidto which are hidden. Now I did some debugging and found out that the reason for my error is because the AJAX call is taking too long. Basically what the ajax call does is convert whatever text that is there in the input field of search-from and fetches the id for that from the database and then returns the value according to that id. So I changed the hidden fields to text and manually inserted the ids for the search fields I entered and it worked everytime. So now what I think the problem is that the AJAX call is taking too long to convert the selected options to their respective ids and this ends up giving me an error. So maybe what I want here is a delay timer to the page until the AJAX call has been made?
  3. I have a query I'm using in my CodeIgniter model to fetch the count of listings of products between particular days. What this query is doing is it's taking status_from from logs where the date is during and after the selected date range and taking added_date from listings where the date falls before the from date range picked by the user and calculates it. Once it has retrieved those records, it checks the table for what variable that status holds and does a sum(case when else 0) to get the total count. function get_report(){ $sql = with Y as ( with recursive D (n, day) as ( select 1 as n, '2021-09-25' my_date union select n+1, day + interval 1 day from D where day + interval 1 day < '2021-10-15' ) select * from D ), X as ( select Y.day, l.*, (select status_from from logs where logs.refno = l.refno and logs.logtime >= Y.day order by logs.logtime limit 1) logstat from listings l, Y where l.added_date <= Y.day ), Z as ( select X.day, ifnull(X.logstat,X.status) stat_day, count(*) cnt from X group by X.day, stat_day ) select Z.day, sum(case when Z.stat_day = 'D' then Z.cnt else 0 end ) Draft, sum(case when Z.stat_day = 'A' then Z.cnt else 0 end ) Action, sum(case when Z.stat_day = 'Y' then Z.cnt else 0 end ) Publish, sum(case when Z.stat_day = 'S' then Z.cnt else 0 end ) Sold, sum(case when Z.stat_day = 'L' then Z.cnt else 0 end ) Let from Z group by Z.day order by Z.day; $query = $this->db->query($sql); return $query; } Dbfiddle: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=6789f0517b194b09d235860dc794ea14 Now here as you can see I'm processing my calculations in the sql statement itself, but I want to do these calculations in my php side, basically iterating everytime it encounters Z.stat_day = 'D' then adding 1 to Draft column and same for the other statuses. Current View Class: <?php foreach($data_total as $row ){ $draft = $row->draft ? $row->draft : 0; $publish = $row->publish ? $row->publish : 0; $action = $row->action ? $row->action : 0; $sold = $row->sold ? $row->sold : 0; $let = $row->let ? $row->let : 0; ?> <tr> <td><?= $row->day?></td> <td><?= $draft ?></td> <td><?= $publish ?></td> <td><?= $action ?></td> <td><?= $sold ?></td> <td><?= $let ?></td> </tr> <?php } ?> Basically I want to refractor my PHP code to do the same thing the Mysql statement is doing, but keeping the query simple and all processing in the PHP side for performance reasons.
  4. Currently I have a table that displays a total count of my data values for each source. I'm getting this value after comparing 2 tables 1 is crm_leads with all my product information and 1 is crm_sources with what sources are the products related to. Now this is the output: Now as you can see the total count is shown under each header next to its source. Now these count values are inside a tags which once clicked go to viewall page. Here basically I want to show the data of the item that I had clicked. So for example, if I clicked the 163 under Hot status, it takes me to the view all page and shows me id, source, enquiry_date for all those under status Hot in a table. So basically it should detect the data for which source and which status is clicked and then accordingly make a statement like this? select * from crm_leads where lead_source = '.$source.' and lead_status = '.$status.'; Model Class: function get_statusreport($fdate='',$tdate='') { $this->db->select("l.lead_status,crm_sources.title,count(*) as leadnum,l.enquiry_date,l.sub_status"); $this->db->from($this->table_name." as l"); if($fdate !='') $this->db->where("date(l.added_date) >=",date('Y-m-d',strtotime($fdate))); if($tdate !='') $this->db->where("date(l.added_date) <=",date('Y-m-d',strtotime($tdate))); $this->db->where("lead_status <>",10); $this->db->join("crm_sources ","crm_sources.id= l.lead_source","left"); $this->db->group_by("l.lead_status,crm_sources.title"); $this->db->order_by("leadnum DESC, crm_sources.title ASC,l.lead_status ASC"); $query = $this->db->get(); $results = $query->result_array(); return $results; } Controller Class(leadstatus holds the view for my current table): public function leadstatus($slug='') { $content=''; $content['groupedleads'] = $this->leads_model->get_statusreport($fdate,$tdate); $this->load->view('crm/main',$main); $this->load->view('crm/reports/leadstatus',$content); } public function viewall($slug='') { $content=''; $this->load->view('crm/main',$main); $this->load->view('crm/reports/viewall',$content); } View class: <?php $ls_arr = array(1=>'Open',8=>'Hot',2=>'Closed',3=>'Transacted',4=>'Dead'); foreach($groupedleads as $grplead){ $statuses[] = $status = $ls_arr[$grplead["lead_status"]]; if($grplead["title"] == NULL || $grplead["title"] == '') $grplead["title"] = "Unknown"; if(isset($grplead["title"])) $titles[] = $title = $grplead["title"]; $leaddata[$status][$title] = $grplead["leadnum"]; } if(count($titles) > 0) $titles = array_unique($titles); if(count($statuses) > 0) $statuses = array_unique($statuses); ?> <table> <tr"> <th id="status">Source</th> <?php if(count($statuses) > 0) foreach($statuses as $status){ ?><th id=<?php echo $status; ?>><?php echo $status; ?></th> <?php } ?> <th>Total</th> </tr> <?php if(is_array($titles)) foreach($titles as $title){ ?> <tr> <?php $total = 0; echo "<td>".$title."</td>"; foreach ($statuses as $status) { $num = $leaddata[$status][$title]; echo "<td><a target='_blank' href='".site_url('reports/viewall')."'>".$num."</a></td>"; $total += $num; $sum[$status] += $num; } echo "<td>".$total."</td>"; $grandtotal += $total; ?> </tr> <?php } ?> </table>
  5. ( ! ) Warning: Creating default object from empty value in C:\wamp64(1)\www\wp-admin\includes\post.php on line 736 Call Stack #Time Memory Function Location 10.000 2412048 {main}( ) ...\post-new.php:0 24.3740 35068232 get_default_post_to_edit( ) ...\post-new.php:66 ( ! ) Warning: Invalid argument supplied for foreach() in C:\wamp64(1)\www\wp-content\plugins\wordpress-seo\admin\metabox\class-metabox.php on line 1091 Call Stack #TimeMemoryFunctionLocation 10.0002412048{main}( )...\post-new.php:0 24.411935106496require( 'C:\wamp64(1)\www\wp-admin\edit-form-blocks.php' )...\post-new.php:72 35.106438351368require_once( 'C:\wamp64(1)\www\wp-admin\admin-header.php' )...\edit-form-blocks.php:289 45.111138354472do_action( )...\admin-header.php:102 55.111138354848WP_Hook->do_action( )...\plugin.php:470 65.111138354848WP_Hook->apply_filters( )...\class-wp-hook.php:327 75.143438608816WPSEO_Metabox->enqueue( )...\class-wp-hook.php:303 85.161838620416WPSEO_Metabox->get_replace_vars( )...\class-metabox.php:873 95.166338625088WPSEO_Metabox->get_custom_replace_vars( )...\class-metabox.php:1003 105.166338625088WPSEO_Metabox->get_custom_fields_replace_vars( )...\class-metabox.php:1038 Can someone please help me solve this bug, on clicking on the 'new page' section of my wordpress dashboard, it keeps showing this. Please, what is wrong?
  6. Here is my code, I am trying to create a function that connects to my local SQL DB using PDO instead of mysqli It looks like I can connect, the issue is that...I can't get my error message to show. "Could not connect to the database" will not come up, when I know that my user name and password are incorrect. I try changing the root name to test to get the error but it doesn't show up ....I can't see my mistake <?php //load test ...un comment exit test db con //exit ('test db con'); } class DB { protected static $con; private function _construct() { try{ self::$con = new PDO( 'mysql: host= localhost; dbname=testdb', 'root', 'password'); self::$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); self::$con->setAttribute( PDO::ATTR_PERSISTENT, false ); } catch (PDOException $e) { echo "Could not connect to database."; exit; } } public static function getConnection(){ //If this instance was not beem started, start it. if(!self::$con){ new DB(); } //Returns Writeable db connection return self::$con; } } ?>
  7. I have here a select query where in I have to get the $den_name and $currDate from a js variable. $disData="SELECT bDate.* FROM (SELECT bDentist.* FROM ( SELECT bBranch.*,concat(px_fname,' ', px_lname) as px_name, concat(px_contact,' / ', px_contact2) as px_connum FROM appointments bBranch WHERE bBranch.brnch_id = '$id') AS bDentist WHERE bDentist.den_name = '$dentistName') AS bDate WHERE bDate.s_date = '$currDate'"; The reason for doing this is so that I can output the records when I clicked a specific date and dentist #1 that matches their values. I tried using ajax here is my code for trying to get the dentist's name // JS Var currDen to PHP Var const den1 = document.querySelector('.D1'); const den2 = document.querySelector('.D2'); const den3 = document.querySelector('.D3'); let currDen = ''; // if 'active' exists if( den1.classList.contains('active')) { currDen = document.getElementById("D1").innerHTML; }else if (den2.classList.contains('active')){ currDen = document.getElementById("D2").innerHTML; }else if (den3.classList.contains('active')){ currDen = document.getElementById("D3").innerHTML; }else{ currDen = 'ë•¡!'; }; console.log(currDen); const xhrDen = new XMLHttpRequest(); jsonStr = JSON.stringify(currDen); console.log (jsonStr); xhrDen.open("POST" , "clickedD.php"); xhrDen.setRequestHeader("Content-type" , "application/json"); xhrDen.send(jsonStr); }); }); this is the clickedD.php where I post it <?php $requestPayload= file_get_contents("php://input"); var_dump($requestPayload); $dentistName = json_decode($requestPayload,true); var_dump($dentistName); echo $dentistName; and in does return this to the network dev tool I also tried checking it if its empty with this if (empty($requestPayload)) { echo "Variable is empty.<br>"; } else { echo $requestPayload; } if (empty($dentistName)) { echo "Variable is empty.<br>"; } and this is what it output what is wrong with my code ? please help me out
  8. Currently I'm using CodeIgniter and Mysql to fetch my data. Here I'm using the following model to get a count of each status from my database: function get_total(){ $this->db->select("SUM(CASE WHEN status_to = 'Draft' THEN 1 END) AS draft, SUM(CASE WHEN status_to = 'Unpublish' THEN 1 END) AS unpublish, SUM(CASE WHEN status_to = 'Publish' THEN 1 END) AS publish, SUM(CASE WHEN status_to = 'Action' THEN 1 END) AS action, SUM(CASE WHEN status_to = 'Unlisted' THEN 1 END) AS unlisted, SUM(CASE WHEN status_to = 'Sold' THEN 1 END) AS sold, SUM(CASE WHEN status_to = 'Let' THEN 1 END) AS let"); $this->db->from('crm_logs'); $results = $this->db->get(); return $results; } Then to get this model I've used the following controller class: public function totallistings($slug='') { $fdate = $this->input->post("fdate"); $tdate = $this->input->post("tdate"); if ($fdate) { $content['fdate'] = $fdate; } else { $content['fdate'] = ''; } if ($tdate) { $content['tdate'] = $tdate; } else { $content['tdate'] = ''; } $content['data_total'] = $this->leads_model->get_total()->result(); $main['content']=$this->load->view('crm/reports/totallistings',$content,true); $this->load->view('crm/main',$main); } And this is my View class: <?php if(isset($data_sum) && count($data_sum) > 0) { foreach($data_sum as $row ){ $draft = $row->draft ? $row->draft : 0; $unpublish = $row->unpublish ? $row->unpublish : 0; $publish = $row->publish ? $row->publish : 0; $action = $row->action ? $row->action : 0; $unlisted = $row->unlisted ? $row->unlisted : 0; $sold = $row->sold ? $row->sold : 0; $let = $row->let ? $row->let : 0; ?> <tr> <td><?= $draft ?></td> <td><?= $unpublish ?></td> <td><?= $publish ?></td> <td><?= $action ?></td> <td><?= $unlisted ?></td> <td><?= $sold ?></td> <td><?= $let ?></td> </tr> <?php } } else { ?> <?php } ?> I now found out that there are more status words other than draft, publish, etc in my database. So I wanted a way to make this `<th>` and `<td>` dynamic but still having the same functionality it is currently having.
  9. What I'm hoping to do is , when an <a> tag is click it will send a text value to php to change whatever name is assigned on the $table variable. To give an example. On the side are all the branches this clinic has. Instead of creating new php file for each of the branch ( with the same design and functionality) and href it accordingly, once click it will send a text to replace the default value of $table. I think AJAX will help do the trick but I'm new to it. Please help me, I'm so lost. Below is my code that displays all the branch, and what it looks like. <div class="BNavcontainer" > <div id="branchnav" class="SideBNav"> <?php /* To display Branch Name from djams_db */ $brnch = $conn->query("SELECT * FROM branches") or die($conn->error); while($row=$brnch->fetch_assoc()): ?> <a data-id='<?php echo $row['brnch_id'] ?>' href="djams_rmc.php?<?php echo $row['brnch_name'] ?>" id="b<?php echo ($row['brnch_id']) +1 ?>" > <?php echo ($row['brnch_name']) ?> </a> <?php endwhile; ?> </div> </div>
  10. Currently I'm using CodeIgniter MVC framework and Mysql to retrieve a count of data within a particular timeframe. My table data looks like this: Where there are different agents who are changing statuses in a particular timeframe. So what I want is to layout all the agents in the table and display what status change they had made in a particular timeframe. To do this I used the following model to get all the agents in the DB: function get_agent(){ $this->db->distinct(); $this->db->select("agent_id"); $this->db->from('crm_logs'); return $this->db->get(); } And this model to get a count of the status changes: function get_agentstatus($fdate,$tdate,$agent_id){ $this->db->select("SUM(CASE WHEN status_to = 'Draft' THEN 1 END) AS draft, SUM(CASE WHEN status_to = 'Unpublish' THEN 1 END) AS unpublish, SUM(CASE WHEN status_to = 'Publish' THEN 1 END) AS publish, SUM(CASE WHEN status_to = 'Action' THEN 1 END) AS action, $this->db->from('crm_logs'); $this->db->where('cast(logtime as date) BETWEEN "' . $fdate . '" AND "' . $tdate . '" AND agent_id="'.$agent_id.'"'); $results = $this->db->get(); return $results; } In my controller class I have used the following code to get the models: public function agentlistings($slug='') { $fdate = $this->input->post("fdate"); $content['tdate'] = $tdate = $this->input->post("tdate"); if(isset($fdate)){ $content['fdate'] =$fdate; }else{ $content['fdate'] = ''; } if(isset($tdate)){ $content['tdate'] =$tdate; }else{ $content['tdate'] =''; } $content['agent'] = $this->leads_model->get_agent()->result_array(); $content['agent_status'] = $this->leads_model->get_agentstatus($fdate,$tdate,$content['agent'])->result_array(); $main['content']=$this->load->view('crm/reports/agentlistings',$content,true); $this->load->view('crm/main',$main); } And the following in my View class: <table id="statustbl" class="table-fill"> <thead> <tr style="height:<?php echo $height; ?>;"> <th>Agent</th> <th>Draft</th> <th>Unpublish</th> <th>Publish</th> <th>Action</th> </tr> </thead> <tbody class="table-hover"> <?php foreach ($agent as $row) { echo '<tr><td>' .$row['agent_id']. '</td></tr>';//column names } ?> </tbody> </table> With this code I'm able to fill up all my distinct agents into the agents column, But I do not know how to show the agent_status with thier respective agent_id. I have tried SELECT SUM(CASE WHEN status_to = 'Draft' THEN 1 END) AS draft, SUM(CASE WHEN status_to = 'Unpublish' THEN 1 END) AS unpublish, SUM(CASE WHEN status_to = 'Publish' THEN 1 END) AS publish, SUM(CASE WHEN status_to = 'Action' THEN 1 END) AS action, agent_id FROM 'crm_logs' WHERE cast(logtime as date) BETWEEN "2021-09-25" AND "2021-10-01" GROUP BY agent_id to get the data in the same query, but this did not return the correct output.
  11. I have a php page tool.php that has a function named "create_event". I want to make a button in a different page (dashboard.php), that when I click on it, it runs the "create_event" function from tool.php and shows the output from the function on dashboard.php page. I'm totally new to ajax and jquery and not sure how to do this. I did google this but not much luck. My site is build with WordPress and this is part of custom plugin that I'm making. Thank you in advance.
  12. In PHP, I am trying to create an array from a CSV file in this way. // CSV file: $csv = array_map('str_getcsv', file("{$uploadPath}/{$myFile}")); Of course it is working for me, but on thing I have to fixed. If I have non-English language characters in my CSV file, then those characters not showing correctly in PHP. That mean its showing question marks instead of showing original characters. This is the output of $csv array: Array ( [0] => Array ( [0] => SISP-0002 [1] => Harpic Floral 500ml [2] => ???????? ??????? 500ml [3] => 4792037107765 ) ) Can anybody tell me what would be the possible workaround to fix this issue.
  13. Howdy folks, I have decided, after a discussion with Barand, to finally hang up the MySQLi shoes and move over to the dark side of PDO. I am trying to Update a profile, for example, but it is not working. No errors or anything. New to PDO so would love some help on figuring out where I am going wrong. Probably everywhere knowing me lol. Here is the dreaded code: if(isset($_POST['submit'])){ $id = trim($_SESSION['id']); //$trn_date = trim($db, date("Y-m-d H:i:s")); //$password = $db->real_escape_string(md5($_POST['password'])); $image = trim($_FILES['image']['name']); $name = trim($_POST['name']); $phone = trim($_POST['phone']); $email = trim($_POST['email']); $address = trim($_POST['address']); $license_number = trim($_POST['license_number']); $position = trim($_POST['position']); $role = trim($_POST['role']); $submittedby = trim($_SESSION["username"]); // image file directory $target = "images/".basename($image); if(!empty($_FILES['image']['name'])) { $sql = "UPDATE users SET name = :name, email = :email, phone = :phone, address = :address, license_number = :license_number, position = :position, role = :role, submittedby = :submittedby, image = :image"; }else{ $sql = "UPDATE users SET name = :name, email = :email, phone = :phone, address = :address, license_number = :license_number, position = :position, role = :role, submittedby = :submittedby"; } $stmt= $db->prepare($sql); if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) { $msg = "Image uploaded successfully"; }else{ $msg = "Failed to upload image"; } if(!$stmt){ if ($stmt->execute()){ $message = ' <i class="fa fa-check text-danger"> Something went wrong please contact the server admin.</i>'; } else{ $message = ' <i class="fa fa-check text-success"> Record Updated!</i>'; } } } Any help folks would be appreciated
  14. Hi folks, Have the following, which is part of a script I am working on to calculate working hours minus break time. However, it's not calculating the correct result. For example, if I worked 12 hours, take away 1 hour break, should be 11 hours. But it will show it as something like 7 hours. Here is the part for Monday: <div class="col-lg-12"> <div class="card"> <div class="card-header"><strong>Add </strong><small>Timesheet <?php if($message = isset($message) ? $message : ''){ printf($message); } ?></small></div> <div class="card-body card-block"> <form role="form" method="post" action=""> <input type="hidden" name="new" value="1" /> <div class="modal-body"> <div class="row form-group"> <div class="col-6"> <label for="driver_name" class=" form-control-label">Driver Name (required)</label> <input type="text" class="form-control" id="driver_name" name="driver_name" placeholder="" value="<?php echo $_SESSION['NAME']; ?>" required > </div> <div class="col-6"> <label for="week_ending" class=" form-control-label">Week Ending (required)</label> <input type="date" class="form-control" id="week_ending" name="week_ending" placeholder="" value="<?php echo isset($_POST['week_ending']) ? $_POST['week_ending'] : '' ?>" required > </div> </div> <hr> <h3>Monday</h3> <div class="row form-group"> <div class="col-4"> <label for="monday_start" class=" form-control-label">Start Time</label> <input type="text" class="form-control" id="monday_start" name="monday_start" placeholder="" value="<?php echo isset($_POST['monday_start']) ? $_POST['monday_start'] : '' ?>" > </div> <div class="col-4"> <label for="monday_start" class=" form-control-label">Break Period</label> <input type="text" class="form-control" id="monday_break" name="monday_break" placeholder="Example: 1:30 = 1hr 30min" value="<?php echo isset($_POST['monday_break']) ? $_POST['monday_break'] : '' ?>" > </div> <div class="col-4"> <label for="monday_finish" class=" form-control-label">Finish Time</label> <input type="text" class="form-control" id="monday_finish" name="monday_finish" placeholder="" value="<?php echo isset($_POST['monday_finish']) ? $_POST['monday_finish'] : '' ?>" > </div> </div> <?php if(isset($_POST['monday_start']) && $_POST['monday_finish'] && $_POST['monday_break'] != "") { $monday_start = new DateTime($_POST['monday_start']); $monday_finish = new DateTime($_POST['monday_finish']); list($h, $m) = explode(":", $_POST['monday_break']); $monday_break = new DateInterval("PT{$h}H{$m}M"); $mondiff = $monday_start->add($monday_break)->diff($monday_finish); ?> <div class="form-group"> <label for="monday" class=" form-control-label">Monday Hours</label> <input type="text" readonly class="form-control" id="monday_hours" name="monday_hours" value="<?php echo $mondiff->format('%H:%I'); ?>"> </div> <?php } ?> Here is the calculating code: <?php if(isset($_POST['calculate']) != ""){ class times_counter { private $hou = 0; private $min = 0; private $sec = 0; private $totaltime = '00:00:00'; public function __construct($times){ if(is_array($times)){ $length = sizeof($times); for($x=0; $x <= $length; $x++){ $split = explode(":", @$times[$x]); $this->hou += (int)$split[0]; $this->min += @$split[1]; $this->sec += @$split[2]; } $seconds = $this->sec % 60; $minutes = $this->sec / 60; $minutes = (integer)$minutes; $minutes += $this->min; $hours = $minutes / 60; $minutes = $minutes % 60; $hours = (integer)$hours; $hours += $this->hou % 24; $this->totaltime = $hours.":".$minutes; } } public function get_total_time(){ return $this->totaltime; } } $times = array( $mondiff->format('%H:%I'), $tuediff->format('%H:%I'), $weddiff->format('%H:%I'), $thurdiff->format('%H:%I'), $fridiff->format('%H:%I'), $satdiff->format('%H:%I'), $sundiff->format('%H:%I'), ); $counter = new times_counter($times); ?> <div class="row form-group"> <div class="col-6"> <div class="form-group"> <label for="total_hours" class=" form-control-label">Total Hours (required)</label> <input name="total_hours" readonly class="form-control" value= "<?php echo $counter->get_total_time(); ?>" /> </div> </div> <?php } ?> Can someone with the geneius knowledge have a look and point me to where I am going wrong? Also, is there a way, to leave a time field blank and not have the above code crack the poops and call an Undefined Array Key on it? TIA
  15. Howdy folks, Getting this error in console when trying to print the contents of a div. get-directions.php:192 Uncaught ReferenceError: printDiv is not defined at HTMLInputElement.onclick Here is the Button for print and the Div wanting to print from: <div id="rightpanel" class="float-right col-md-4"></div> <input type="button" id="print" onclick="printDiv('rightpanel')" value="Print Directions" /> Here is the Script: function printDiv(rightpanel) { var disp_setting="toolbar=yes,location=no,"; disp_setting+="directories=yes,menubar=yes,"; disp_setting+="scrollbars=yes,width=650, height=600, left=100, top=25"; var content_vlue = document.getElementById(rightpanel).innerHTML; var docprint=window.open("","",disp_setting); docprint.document.open(); docprint.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"'); docprint.document.write('"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'); docprint.document.write('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">'); docprint.document.write('<head><title>My Title</title>'); docprint.document.write('<style type="text/css">body{ margin:0px;'); docprint.document.write('font-family:verdana,Arial;color:#000;'); docprint.document.write('font-family:Verdana, Geneva, sans-serif; font-size:12px;}'); docprint.document.write('a{color:#000;text-decoration:none;} </style>'); docprint.document.write('</head><body onLoad="self.print()"><center>'); docprint.document.write(content_vlue); docprint.document.write('</center></body></html>'); docprint.document.close(); docprint.focus(); } Any help would be appreciated. Cheers
  16. I have a general question. Just need to be put on the right direction. I made that little game I put on a server. Now I wish that 2 persons could play against each other online. So I made a signup/login and I can list all the users against which you would like to play. Now how could I know who is actually online and send him/her an alert when it is his/her turn to play? My first idea was to send emails every time it's a player turn to make a move; but there must be something more elegant to do in-game? I'm having a lot of fun coding that thing and any help would be great 🙂
  17. i try this code to rename file when upload , the file name is rename in the folder or physical file .But in the database , it display 'array' not the name of file .How to save file name in the database ? $targetDirg= "folder/pda-semakan/gambar/"; if($_FILES['gambar']['size'] == 0 && $_FILES['gambar']['name'] == ""){ $fileNameg = $gambar; }else{ $fileNameg =explode(".",$_FILES['gambar']['name']); $newfilename= $stIC.'.'.end($fileNameg); $moveg =move_uploaded_file($_FILES["gambar"]["tmp_name"], $targetDirg.$newfilename); }
  18. I'm trying to display some user created content on a page. Everything does what it should except the image (it's always the image). To be clear, I'm not storing the image in the DB only the link to the image, but images are being uploaded into the site file system. The path being stored in the DB (phpmyadmin) is the full image path - /opt/lampp/htdocs/site/news/img/posts/* - The image doesn't display on the page and I get a 404 not found in the console. When I echo the path to the page that it's looking for the image in, it's as above. But the 404 not found in the console says it's looking for it at http://localhost/opt/lampp/htdocs.... So it's obviously got a redundant section (http://localhost). When I try to remove the /opt/lampp/htdocs from the upload path I get a bunch of warnings. But the real issue is that the browser is adding the repeated section. So how do I remedy this so the browser looks in the correct location? TIA
  19. I have Hotel website, naturevilas.com, after updating a PHP version code there is undefined error occur automatic, I don't know why this error occur and I have a big problem because this error can effect my business. I am also going software company in my local area but still I am facing a problem. I don't know how to solve this problem. Error on My Website showing in Font Screen: Bolt Error Back to merchant website link: naturevilas.com Home Page Room Page Select a Room CheckOut Page Error Page What I have tried: I have tried, update my PHP Code or back to old version of PHP Code(Backup file) and Connect with my local area software company, but still facing a problem.
  20. I have to pass the date in one of the step as current date and compare that, but failing to achieve that test case is "And the URL "<>" contains the following: "Measure name","Business description","Technical description","Data Sources",Reports,"Authored by","Last publish date" "First Test Measure","business Lorem Ipsum is simply","technical Lorem Ipsum is",CHRISS,First Test Report,, Here one of the parameter is "Last publish date" so I have to give it as it should be comes up as current date. I am trying to give the date [[now:j F Y], but it is not working. Below is the function written for it, what change I have to do so it can have the date as well. /** * Download a url and verify the contents. * * @throws \Exception * When the file contents don't match. * * @Then the URL :url contains the following: */ public function assertUrlContent(string $url, PyStringNode $content): void { $cookies = $this->getSession()->getDriver()->getWebDriverSession()->getCookie()[0]; $cookie = new SetCookie(); $cookie->setName($cookies['name']); $cookie->setValue($cookies['value']); $cookie->setDomain($cookies['domain']); $jar = new CookieJar(); $jar->setCookie($cookie); $client = new Client(); $res = $client->request('GET', $url, [ 'cookies' => $jar, 'verify' => FALSE, ]); $expected_string = preg_replace('/\r/', '', (string) $content); $actual_string = $res->getBody()->getContents(); if ($expected_string !== $actual_string) { print_r('Expected String: ' . PHP_EOL . $expected_string . PHP_EOL); print_r('Actual String: ' . PHP_EOL . $actual_string); throw new \Exception('Contents of download do not match'); } }
  21. Dear Friends, I am alot before doing the mixed content of php and HTML in single variable in PHP.. I could not get the data even though there is not SYNTAX error.. please look my code and advise $htmlcontent .=" <tr> <td colspan=\"8\">".$details."></td> </tr>"; for($k=0;$k<count($reg_years[$details]);$k++) { $year = (int)($reg_years[$details][$k]); $singlecount[$year] = array_filter($result[$details],function($details1) use ($year){ return ($details1['reg_year'] == $year && $details1['bench_type'] == 1); }); $divisioncount[$year] = array_filter($result[$details],function($details2) use ($year){ return ($details2['reg_year'] == $year && $details2['bench_type'] == 2); }); $fullcount[$year] = array_filter($result[$details],function($details3) use ($year){ return ($details3['reg_year'] == $year && $details3['bench_type'] >= 3); }); $rpcount[$year] = array_filter($result[$details],function($rp) use ($year){ return ($rp['reg_year'] == $year && $rp['bench_type'] == 'RP'); }); $mjccount[$year] = array_filter($result[$details],function($mjc) use ($year){ return ($mjc['reg_year'] == $year && $mjc['bench_type'] == 'MJC'); }); $cocount[$year] = array_filter($result[$details],function($co) use ($year){ return ($co['reg_year'] == $year && $co['bench_type'] == 'X'); }); $total = 0; $total = (int)(count($singlecount[$year])+count($divisioncount[$year])+count($fullcount[$year])+count($rpcount[$year])+count($mjccount[$year])+count($cocount[$year])); $htmlcontent .=" <tr> <td>".$year."</td> <td align=\"center\"> if(count($singlecount[$year])>0) { echo (count($singlecount[$year])); } else { echo "-"; } </td> <td align=\"center\"> if(count($divisioncount[$year])>0) { ".count($divisioncount[$year])." } else { "-" } </td> <td align=\"center\"> if (count($fullcount[$year]) > 0) { echo (count($fullcount[$year])); } else { echo "-"; } </td > < td align =\"center\"> if(count($rpcount[$year])>0) { echo (count($rpcount[$year])); } else { echo " - "; } </td> <td align=\"center\"> if(count($mjccount[$year])>0) { echo (count($mjccount[$year])); } else { echo " - "; } </td> <td align=\"center\"> if(count($cocount[$year])>0) { echo (count($cocount[$year])); } else { echo " - "; } </td> <td align=\"center\"> echo $total; </td> </tr>"; } } $htmlcontent .= "</tbody></table>"; $mpdf = new \Mpdf\Mpdf(); $mpdf->WriteHTML($htmlcontent); $mpdf->Output(); Waiting for FAST reply Thanks Anes
  22. Hi, I am making a shopping cart and I have a problem. My code to remove the items from the cart works except for the first added item; I can delete all but that one. This is the form to remove the items. <form class="col-md-12" method="POST" action="" id="formremove"> <input type="hidden" name="id_prod" value="<?php echo $row['id_producto'] ?>"> <input type="submit" name="btn-remove" class="btn btn-info btn-sm" id="remove" value="X"> </form> And this is the php if ($_POST['btn-remove']) { $id_user=$_SESSION['id_user']; $id_prod = $_POST['id_prod']; $SQLREM = "DELETE FROM `carrito` WHERE id_user='$id_user' and id_producto='$id_prod';"; if (mysqli_query($conn, $SQLREM)) { echo '<script> alert("Ok"); window.location="/CBA/WAUW/cart.php"</script>'; } else { echo '<script> alert("Error"); window.location="/CBA/WAUW/cart.php"</script>'; }; } The connection to the database works fine; as I said before, it deletes everything but the first item added. I would be very grateful for any help.
  23. is there any way to put function compress pdf file size in this code . Because when user upload big file size , it will get error . So , i'm looking code that can auto resize the pdf file in php $targetDir7= "folder/pda-semakan/bm/"; if(isset($_FILES['bmjulai'])){ $fileName7= $_FILES['bmjulai']['name']; $targetFilePath7 = $targetDir7 . $fileName7; $move8=move_uploaded_file($_FILES["bmjulai"]["tmp_name"], $targetFilePath7); }
  24. Hi guys, I am trying to calculate hours a person works by calculating the values of text fields in a form. However, when I load the page I get "Class 'times_counter' not found. Here is the calculation code" if(isset($_POST['calculate']) != ""){ class times_counter { private $hou = 0; private $min = 0; private $sec = 0; private $totaltime = '00:00:00'; public function __construct($times){ if(is_array($times)){ $length = sizeof($times); for($x=0; $x <= $length; $x++){ $split = explode(":", @$times[$x]); $this->hou += @$split[0]; $this->min += @$split[1]; $this->sec += @$split[2]; } $seconds = $this->sec % 60; $minutes = $this->sec / 60; $minutes = (integer)$minutes; $minutes += $this->min; $hours = $minutes / 60; $minutes = $minutes % 60; $hours = (integer)$hours; $hours += $this->hou % 24; $this->totaltime = $hours.":".$minutes; } } public function get_total_time(){ return $this->totaltime; } } $times = array( $mondiff->format('%H:%I'), $tudiff->format('%H:%I'), $weddiff->format('%H:%I'), $thdiff->format('%H:%I'), $fridiff->format('%H:%I'), $satdiff->format('%H:%I'), $sundiff->format('%H:%I'), ); $counter = new times_counter($times); I had this on an old project, which I no longer have but it worked then. Any ideas?
  25. files that upload during insert/submit form was gone , only files upload during the update remain , is the way query for update multiple files is wrong ? $targetDir1= "folder/pda-semakan/ic/"; if(isset($_FILES['ic'])){ $fileName1 = $_FILES['ic']['name']; $targetFilePath1 = $targetDir1 . $fileName1; //$main_tmp2 = $_FILES['ic']['tmp_name']; $move2 =move_uploaded_file($_FILES["ic"]["tmp_name"], $targetFilePath1); } $targetDir2= "folder/pda-semakan/sijil_lahir/"; if(isset($_FILES['sijilkelahiran'])){ $fileName2 = $_FILES['sijilkelahiran']['name']; $targetFilePath2 = $targetDir2 . $fileName2; $move3 =move_uploaded_file($_FILES["sijilkelahiran"]["tmp_name"], $targetFilePath2); } $targetDir3= "folder/pda-semakan/sijil_spm/"; if(isset($_FILES['sijilspm'])){ $fileName3 = $_FILES['sijilspm']['name']; $targetFilePath3 = $targetDir3 . $fileName3; $move4 =move_uploaded_file($_FILES["sijilspm"]["tmp_name"], $targetFilePath3); } $query1=("UPDATE semakan_dokumen set student_id='$noMatrik', email= '$stdEmail', surat_tawaran='$fileName', ic='$fileName1',sijil_lahir='$fileName2',sijil_spm= '$fileName3' where email= '$stdEmail'");
×
×
  • 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.