Jump to content

Search the Community

Showing results for tags 'mysql'.

  • 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. Ok - I have a working query to which I wanted to add one more item from a new table. Thought it was easy but I must be having a bad day. I will post the original working query (now commented out) and the new query with the added item 'driver_num': /* $q = "select a.race_winner, w.wins, substr(a.race_winner, instr(a.race_winner,' ')+1) as last_name, a.race_name, date_format(a.race_date, '%m/%d') as race_date from trk_races a left outer join (select race_winner, count(race_date) as wins from trk_races where race_winner > '' and Season='$selyr' group by race_winner) w on w.race_winner = a.race_winner where a.race_winner > '' and a.Season='$selyr' order by $orderby"; */ $q = "select a.race_winner, w.wins, substr(a.race_winner, instr(a.race_winner,' ')+1) as last_name, a.race_name, date_format(a.race_date, '%m/%d') as race_date, d.driver_num from trk_races a, drivers d left outer join (select race_winner, count(race_date) as wins from trk_races where race_winner > '' and Season='$selyr' group by race_winner) w on w.race_winner = a.race_winner where a.race_winner > '' and a.Season = '$selyr' and d.driver_season = a.Season and a.race_winner = d.driver_name order by $orderby"; The only addition is the "drivers d" in the from clause of the first select along with the additions to the ending where clause that connects the "drivers" table to the "trk_races" table in that select. Here is the error I am getting from this change: Fatal error: Uncaught PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'a.race_winner' in 'on clause' in /home/albany/public_html/homejg/nascar/nas_show_drivers.php:129 Stack trace: #0 /home/albany/public_html/homejg/nascar/nas_show_drivers.php(129): PDO->query('select a.race_w...') ..... The error column is already being used elsewhere in the query so I can't figure out why I am getting this error.
  2. For the life of me I can not figure out the syntax error. I was thinking it was related to DateTime field. The data comes over as a string from the api, but converting to time doesn't work. The field in the database is DateTime. Any suggestions would be appreciated. The data from the api for reference. array(1) { [0]=> array(3) { ["macAddress"]=> string(17) "FA:F5:C2:98:6F:29" ["lastData"]=> array(27) { ["dateutc"]=> int(1642622880000) ["tempinf"]=> float(77.9) ["humidityin"]=> int(38) ["baromrelin"]=> float(29.956) ["baromabsin"]=> float(29.132) ["tempf"]=> float(77.2) ["battout"]=> int(1) ["humidity"]=> int(47) ["winddir"]=> int(247) ["windspeedmph"]=> float(5.6) ["windgustmph"]=> float(8.1) ["maxdailygust"]=> float(15.9) ["hourlyrainin"]=> int(0) ["eventrainin"]=> int(0) ["dailyrainin"]=> int(0) ["weeklyrainin"]=> int(0) ["monthlyrainin"]=> float(0.52) ["totalrainin"]=> float(48.862) ["solarradiation"]=> float(196.47) ["uv"]=> int(1) ["feelsLike"]=> float(76.83) ["dewPoint"]=> float(55.39) ["feelsLikein"]=> float(77.2) ["dewPointin"]=> float(50.2) ["lastRain"]=> string(24) "2022-01-12T02:50:00.000Z" ["tz"]=> string(15) "America/Chicago" ["date"]=> string(24) "2022-01-19T20:08:00.000Z" } ["info"]=> array(2) { ["name"]=> string(18) "My Weather Station" ["coords"]=> array(5) { ["coords"]=> array(2) { ["lon"]=> float(-197.65635809999999) ["lat"]=> float(38.6587316) } ["address"]=> string(44) "100 Main Street, Anytown, FL 08226, USA" ["location"]=> string(10) "Anytown" ["elevation"]=> float(214.7066497802734) ["geo"]=> array(2) { ["type"]=> string(5) "Point" ["coordinates"]=> array(2) { [0]=> float(-97.65635809999999) [1]=> float(30.6587316) } } } } } } I take the data from the array and assign it to variables. Notice the unsuccessful attempts to convert string to DateTime. <?php $_DateTime = $data[0]['lastData']['date']; //$_OldDateTime = $data[0]['lastData']['date']; //$_dateTime = strtotime($_OldDateTime); $_tempf = $data[0]['lastData']['tempf']; $_feelsLike = $data[0]['lastData']['feelsLike']; $_stationbarometer = $data[0]['lastData']['baromrelin']; $_sealevelbarometer = $data[0]['lastData']['baromabsin']; $_dewpoint = $data[0]['lastData']['dewPoint']; $_humidity = $data[0]['lastData']['humidity']; $_winddir = $data[0]['lastData']['winddir']; $_windspeed = $data[0]['lastData']['windspeedmph']; $_gust = $data[0]['lastData']['windgustmph']; $_maxdailygust = $data[0]['lastData']['maxdailygust']; $_hourlyrainrate = $data[0]['lastData']['hourlyrainin']; $_dailyrain = $data[0]['lastData']['dailyrainin']; $_weeklyrain = $data[0]['lastData']['weeklyrainin']; $_monthlyrain = $data[0]['lastData']['monthlyrainin']; $_totalrain = $data[0]['lastData']['totalrainin']; $_lastRain = $data[0]['lastData']['lastRain']; //$_OldlastRain = $data[0]['lastData']['lastRain']; //$_lastRain = strtotime($_OldlastRain); $_solar = $data[0]['lastData']['solarradiation']; $_battout = $data[0]['lastData']['battout']; // this is where we insert into the database $sql = "INSERT INTO weather_data (datetime, tempf, feelslike, stationbarometer, sealevelbarometer, dewpoint, humidity, winddir, windspeed, gust, maxdailygust, hourlyrainrate, dailyrain, weeklyrain, monthlyrain, totalrain, lastrain, solar, battout) VALUES ( $_DateTime, $_tempf, $_feelsLike, $_stationbarometer, $_sealevelbarometer, $_dewpoint, $_humidity, $_winddir, $_windspeed, $_gust, $_maxdailygust, $_hourlyrainrate, $_dailyrain, $_weeklyrain, $_monthlyrain, $_totalrain, $_lastRain, $_solar, $_battout )"; //mysqli_query($conn, $sql); if (mysqli_query($conn, $sql)) { echo "Success!"; //json_encode(array("statusCode"=>200)); } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?> Error message: Error: INSERT INTO weather_data (datetime, tempf, feelslike, stationbarometer, sealevelbarometer, dewpoint, humidity, winddir, windspeed, gust, maxdailygust, hourlyrainrate, dailyrain, weeklyrain, monthlyrain, totalrain, lastrain, solar, battout) VALUES ( 2022-01-24T15:40:00.000Z, 47.7, 47.7, 30.048, 29.224, 45.49, 92, 314, 1.3, 2.2, 8.1, 0, 0.161, 0.161, 0.681, 49.024, 2022-01-24T15:34:00.000Z, 29.48, 1 ) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':40:00.000Z, 47.7, 47.7, 30.048, 29.224, 45.49, 92, 314, ' at line 6
  3. I have created a form to edit fields in a database table. This is basically what it does sale_stamp : <input type="text" name="sale_stamp" value="<?php echo $sale_stamp;?>" > $sale_stamp = $_POST['sale_stamp']; $sql = "UPDATE mytable SET sale_stamp = :sale_stamp WHERE id = :id"; $stmt=$db->prepare($sql); $stmt->execute(array( ':id' => $id, ':sale_stamp' => $sale_stamp); This works provided there are values entered but some fields may be blank and this fails for numeric fields. The generated sql is UPDATE asset set sale_stamp = '' WHERE id = '17' The table definition allows null, but when I leave the field blank in the table the generated sql has an empty string rather than null. How do I overcome this?
  4. In my DB schema, there are 4 tables and its relationship as shown in the below attached image. My question is how many schools are there according to the data in the school table and how many of those schools belong to provinces, districts and zones, is it possible in one mysql query? Currently I am using 4 separate queries for this and the relevant code is as follows. $sql = "SELECT count(school_id) as schtot FROM sn_school"; $stmt = $pdo->query($sql); $schtot = $stmt->fetchColumn(); $schtot = str_pad($schtot , 3, 0, STR_PAD_LEFT); $sql = "SELECT count(zone_id) as zonetot FROM sn_school GROUP BY zone_id"; $stmt = $pdo->query($sql); $zonetot = $stmt->rowCount(); $zonetot = str_pad($zonetot , 3, 0, STR_PAD_LEFT); $sql = "SELECT COUNT(d.district_id) as districtTot FROM sn_school s JOIN zone z USING(zone_id) JOIN district d ON d.district_id = z.district_id GROUP BY d.district_id"; $stmt = $pdo->query($sql); $districtTot = $stmt->rowCount(); $districtTot = str_pad($districtTot , 3, 0, STR_PAD_LEFT); $sql = "SELECT COUNT(p.province_id) as ptot FROM sn_school s JOIN zone z USING(zone_id) JOIN district d ON d.district_id = z.district_id JOIN district p ON p.province_id = d.province_id GROUP BY p.province_id"; $stmt = $pdo->query($sql); $ptot = $stmt->rowCount(); $ptot = str_pad($ptot , 3, 0, STR_PAD_LEFT);
  5. 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.
  6. 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>
  7. Here is the dbfiddle for better understanding, refer this when reading question: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=0919cacb5d117450168cdc917433a45e I have 2 tables called listings and logs table. The listings table holds a products reference number and it's current status. So suppose if it's status was Publish currently and it's sold later, the status updates to Sold. Here the refno. in this table is unique since the status can change for 1 product. Now I have another table called Logs table, this table records all the status changes that have happened for a particular product(referenced by refno) in a particular timeframe. The initial entry in the listings table is not recorded here, but once it's status is changed, that entry is shown here. Suppose I have the following Listings table('D' => 'Draft', 'A' => 'Action', 'Y' => 'Publish', 'S' => 'Sold', 'N' => 'Let'): INSERT INTO listings VALUES (3, 'Y','2021-05-02','2021-10-02','LP01'), (4, 'A','2021-05-01','2021-05-01','LP02'), (5, 'S','2020-10-01','2020-10-01','LP03'), (6, 'N','2021-05-01','2021-10-06','LP06'), (10, 'D','2021-10-06','2021-10-06','LP05'), (11, 'D','2021-01-01','2021-01-01','LP04'); Here as of now the total count under every status would give: |status_1|c| |:---:|:--:| |Publish|1| |Action|1| |Sold|1| |Left|1| |Draft|2| But if I wanted only the count for entries made in 2020-10-01 it'll show 0 under all statuses except sold, where it'll show 1. Now in this timeframe between 2020-10-01 and today, there have been values entered in listings table as shown above and also for some, the statuses have changed. Status table: INSERT INTO logs VALUES (1, 'Let','Action','2021-06-01','LP01'), (2, 'Action','Draft','2021-10-01','LP01'), (3, 'Draft','Publish','2021-10-02','LP01'), (4, 'Action','Let','2021-10-06','LP06'); What is being shown right now in my listings table is the values after the status change has been made. So now to get the total count on a particular day, I'm having my statement reference the dates from the logs table and respectively subtract the status_to, and add the status_from. Query for this is in the dbfiddle provided above. Here I made it to return data that happened on or before 2021-10-01 and it does not give the right output. Another problem with this query is I cannot return the data for the entries that had initially taken place. For example like I mentioned above the value for the data on 2020-10-01 should show 1 under sold, while 0 under everything else(desired output), but it does not do this since there are no logs made in logs table for when a new entry in initially added. So basically what I want here is to get the initial entries as well with the same entry. If you want an easier explanation for what I'm trying to achieve, please refer to this:
  8. Currently I have 2 tables, the first table shows a count of statuses, refno. and agent_id(person in charge of the refno.) and the second table has an id and agent_name. So to refer a particular agent next to the refno. in table 1, you can reference it via the id of the agent table. Dbfiddle: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=d0e8222a1e49774bcfbcfa30cec75732 Now I have found out that some of my listings have the agent_id as 0 and null, which doesn't have a reference in my agents table. So here I'm using COALESCE to add an extra row called Unassigned and inserting all variables with agent_id 0 or null inside this column. I've tried this same in my codeigniter model: function get_totalagentstatus(){ $this->db->select("SUM(CASE WHEN t.status = 'D' THEN 1 END) AS draft, SUM(CASE WHEN t.status = 'N' THEN 1 END) AS unpublish, SUM(CASE WHEN t.status = 'Y' THEN 1 END) AS publish, SUM(CASE WHEN t.status = 'U' THEN 1 END) AS action, SUM(CASE WHEN t.status = 'L' THEN 1 END) AS unlisted, SUM(CASE WHEN t.status = 'S' THEN 1 END) AS sold, SUM(CASE WHEN t.status = 'T' THEN 1 END) AS let, COALESCE(c.display_name,'Unassigned'), SUM(t.status = 'D') +SUM(t.status = 'N') + SUM(t.status = 'Y') + SUM(t.status = 'U') + SUM(t.status = 'L' ) + SUM(t.status = 'S' )+ SUM(t.status = 'T' ) AS total, t.agent_id, c.display_name"); $this->db->from('crm_listings t'); $this->db->join('crm_clients_users c','t.agent_id = c.id'); $this->db->where('archive="N"'); $this->db->group_by('COALESCE(c.display_name,"Unassigned")'); $results = $this->db->get(); return $results; } Controller Class: $content['total_agent_status'] = $this->leads_model->get_totalagentstatus()->result(); View Class: <?php foreach($total_agent_status 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; $total = $row->total ? $row->total : 0; ?> <tr> <td><?= $row->display_name ?></td> <td><?= $draft ?></td> <td><?= $unpublish ?></td> <td><?= $publish ?></td> <td><?= $action ?></td> <td><?= $unlisted ?></td> <td><?= $sold ?></td> <td><?= $let ?></td> <td><?= $total ?></td> </tr> Now this returns everything except the Unassigned row which I want. I've also input this in my phpmyadmin to see the result and it does not return it there either, instead it shows the output with these headers and Unassigned is not there in any of the entries here:
  9. 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.
  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. 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
  12. I have some sales data as below: SELECT bv.sale_time , amount_due , round(sum(amount_paid), 2) as paid , m.payment_method_id , m.method , bt.payment_status FROM basket_amount_due bv JOIN basket bt USING(basket_id) LEFT JOIN basket_payment p USING (basket_id) JOIN payment_method m USING(payment_method_id) GROUP BY bv.basket_id; +---------------------+------------+---------+-------------------+-------------------+----------------+ | sale_time | amount_due | paid | payment_method_id | method | payment_status | +---------------------+------------+---------+-------------------+-------------------+----------------+ | 2021-09-18 12:19:04 | 1170.00 | 1170.00 | 1 | CASH | paid | | 2021-09-18 12:19:39 | 756.60 | 0.00 | 1 | CASH | due | | 2021-09-18 12:20:22 | 1115.50 | 1000.00 | 1 | CASH | partial | | 2021-09-18 12:21:47 | 990.00 | 990.00 | 4 | Cash on Delivery | paid | | 2021-09-18 12:23:33 | 698.40 | 0.00 | 4 | Cash on Delivery | due | | 2021-09-18 12:29:45 | 2070.00 | 2070.00 | 2 | Credit/Debit Card | paid | +---------------------+------------+---------+-------------------+-------------------+----------------+ 6 rows in set (0.004 sec) My question is, Now I need to get total sales by payment method and payment status. That mean I want, total cash sales (= cash(paid) + Card (paid) + Cash on Delivery (paid)) total credit sales (= cash(due) + cash(partial) + Cash on Delivery (due)) total cash on delivery sales (= Cash on Delivery (paid) + Cash on Delivery (due)) total card sales This is the query I have so far.. SELECT DATE(bv.sale_time) , CASE p.payment_method_id WHEN (1 AND 2) THEN sum(amount_due) ELSE 0 END AS total_cash_sales , CASE p.payment_method_id WHEN 4 THEN sum(amount_due) ELSE 0 END AS total_credit_sales FROM basket_amount_due bv JOIN basket bt USING(basket_id) LEFT JOIN basket_payment p USING (basket_id) JOIN payment_method m USING(payment_method_id) WHERE DATE(bv.sale_time) >= CURDATE() AND DATE(bv.sale_time) < CURDATE() + INTERVAL 1 DAY GROUP BY bv.sale_time; Hope somebody may help me out to figure this out.
  13. Hi, Phreaks, I'm stuck on something that maybe someone can help with on trying to send a user information to phpmyadmin I get this error -> There's 2 problems here, as you can see. 1) I've got an invalid datetime format. 2) is obviously the incorrect string value on my salt value. here is the corresponding code -> <?php if($validation->passed()) { $user = new User(); $salt = Hash::salt(32); try { $user->create(array( "username" => Input::get("usernane"), "password" => Hash::make(Input::get("password"), $salt), "email" => Input::get("email"), "salt" => $salt, "signup_date" => date_create('now')->format('Y-m-d H:i:s'), "role" => 2, )); $sent = true; } catch(Exception $e) { die($e->getMessage()); } } else { $errors = $validation->errors(); } It can be seen how I did both of them here. Additionally the Hash::salt method is here -> <?php public static function salt($length) { return random_bytes($length); } the column 'signup_date' is in my database as a datetime not null with 'none' as default. The column 'salt' is a VARCHAR(32) not null, 'none' as default Can anyone help me out with what I've done wrong, please. TIA
  14. Hello, I have the following code that should select all strings that start with "rog" (like rogers, etc). SELECT user_id, first_name AS name, gender FROM user_details WHERE MATCH (first_name) AGAINST('rog*') The problme it's that shows me zero results. In first_name column I have a lot of words with "rogers". first_name column have Fulltext assign. If I use just "...AGAINST ('rogers')" it return corect data. It's something wrong with my sentence? Thank you
  15. 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 ๐Ÿ™‚
  16. 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.
  17. Data from category table: +-------------+-----------+---------------------+-------------+ | category_id | parent_id | name | description | +-------------+-----------+---------------------+-------------+ | 1 | NULL | Products | NULL | | 2 | 1 | Computers | NULL | | 3 | 2 | Laptops | NULL | | 4 | 2 | Desktop Computers | NULL | | 5 | 2 | Tab PCs | NULL | | 6 | 2 | CRT Monitors | NULL | | 7 | 2 | LCD Monitors | NULL | | 8 | 2 | LED Monitors | NULL | | 9 | 1 | Mobile Phones | NULL | | 10 | 9 | LG Phone | NULL | | 11 | 9 | Anroid Phone | NULL | | 12 | 9 | Windows Mobile | NULL | | 13 | 9 | iPad | NULL | | 14 | 9 | Samsung Galaxy | NULL | | 15 | 1 | Digital Cameras | NULL | | 16 | 1 | Printers and Toners | NULL | | 17 | 14 | Galaxy S Series | NULL | | 18 | 14 | Galaxy Note Series | NULL | | 19 | 14 | Galaxy Z Fold2 5G | NULL | | 20 | 17 | Phone 1 | NULL | | 21 | 17 | Phone 2 | NULL | +-------------+-----------+---------------------+-------------+ Just think, I hava an array of category ids for delete like this: ids = [9,17,20]; Now I want to delete the category related to the above array and update the relevant child category. According to this example, the parent_id of the category_id 10,11,12,13,14 should be 1 The parent_id in category 21 should be updated to 14. In another case, suppose I delete category 9, 18 then all the relevant sub and sub sub categories should be updated as parant category. I hope somebody may help me out. Thank you
  18. I am having trouble adding sub-topics to my home made blog system running under PHP-Fusion CMS with PHPver7.4.16 with cgi/fcgi interface and MySQL5.7.34-log. Here are 2 images: Here is the module that produces the output. <?php echo "<div class='col-sm-12'>\n"; echo "<table width='100%' border='0'><tr><td><span class='hdspan2'><b>".$locale['gb_810']."</b></span></td></tr></table>\n"; echo "<table align='center' width='80%' border='0'>\n"; $result = dbquery("SELECT * FROM ".DB_GRIMS_BLOG_TOPICS." ORDER BY topic_order ASC"); if (dbrows($result)) { $cnt = 0; while($data = dbarray($result)) { $id = $data['topic_id']; $title = $data['topic_title']; $sub = $data['topic_sub']; $result1 = dbquery("SELECT * FROM ".DB_GRIMS_BLOG_POST." WHERE topic_id='$id'"); $num_rows = dbrows($result1); if ($sub == '1') { echo "<tr><td width='15'></td><td><a class='lnk-side' href='".BASEDIR."grims_blog/topics_page.php?topic_id=".$id."'>$title</a><span style='font-size:11px;color:white;'>&nbsp;[$num_rows posts]</span></td></tr>\n"; } else { echo "<tr><td colspan='2'><a class='lnk-side' href='".BASEDIR."grims_blog/topics_page.php?topic_id=".$id."'>$title</a><span style='font-size:11px;color:white;'>&nbsp;[$num_rows posts]</span></td></tr>\n"; } } $cnt++; } echo "</table><p></div>\n"; ?> The topic_order field is a new field I added to get the desired output but it's not standard procedure and is in fact not really workable in a live setting because I would have to use php_myadmin to modify it everytime I added or deleted a topic or sub-topic. So the bottom line is that I can't figure out anyway to code the script to always show the sub-topic right under the associated main topic and all in order. If I add a sub-topic to one of the upper main topics it shows up at the bottom; hence the addition of the topic_order field. So right now it's basically a mess and I can't figure out how to code everything to work correctly. I have searched the forums here as well as several other sites and cannot get any clues.
  19. Hi All, I have the following, and when i run it the ifnull() is returning null rather than 0 as shown in the attached. Any help on this would be greatly appreciated. select * from ( SELECT ptsl_ptd_id, SUBSTRING(ptsl_date,1,10) as ptsl_date, ptsl_z_id, z_rfid, ptsl_limit FROM `prs_ptsl` inner join prs_z on ptsl_z_id=z_id where ptsl_ptd_id='7' ) as limits left join ( SELECT pr_ptd_id, za_sdate, za_z_id, za_z_rfid, IFNULL(count(za_pr_id), 0) as used FROM `prs_za` inner join prs_pr on za_pr_id=pr_id where prs_pr.pr_status = 'Approved' or prs_pr.pr_status = 'Submitted' group by za_sdate, za_z_id, za_z_rfid ) as used on limits.ptsl_ptd_id=used.pr_ptd_id and limits.ptsl_date=used.za_sdate and ptsl_z_id=za_z_id where ptsl_date = '2021-06-12' and (ptsl_limit - IFNULL(used, 0) >= 0) limit 100
  20. Hello everyone. I'm a self learner that is very new to programming. Three tables are given: table `worker` (worker) with data - id (worker id), first_name (name), last_name (last name) table `child` (child) with data - worker_id (worker id), name (child name) table `car` (machine) with data - worker_id (worker id), model (car model) Table structure: CREATE TABLE `worker` ( `id` int(11) NOT NULL, `first_name` varchar(100) NOT NULL, `last_name` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; CREATE TABLE `car` ( `user_id` int(11) NOT NULL, `model` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `child` ( `user_id` int(11) NOT NULL, `name` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; It is necessary to write one SQL query that returns: names and surnames of all employees, a list of their children separated by commas and a car brand. You need to select only those workers who have or had a car (if there was a car and then it was gone, then the model field becomes null).
  21. //my controller <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; class homeController extends Controller { public function index() { $employee = DB::table('employee')->orderBy('id','desc')->get(); $department = DB::table('department')->orderBy('id','desc')->get(); return view('index', ['employee' => $employee , 'department' => $department]); } } //my routes Route::get('index','homeController@index'); //my view using blade temmplating engine @foreach($employee as $emp) <div class="employee"> <b>{{ $emp->name }} </b> <a href="employee/{{ $emp->id }}"> <p class="intro">{{ substr($emp->intro ,0, 50) }}...</p> </a> </div> @endforeach @foreach($department as $dep) <div class="department"> <b>{{ $dep->name }} </b> <a href="department/{{ $dep->id }}"> <p class="desc">{{ substr($dep->description ,0, 100) }}...</p> </a> </div> @endforeach I want to fetch using ajax, how can i do it, teach/help me
  22. Good day I have three tables - receiving - shipping and stock movement. everyday i transfer into stock movent the sum of receining with date - havein a stock movent entry per day - I also at end of day update with shipping for that day, in stock table I calculate ne stock level. my problem is that when three days bac i stil have stock i need to start subtracting from oldest entry first till it reaches 0 the move over to second eldest? i have no idea where to start or how to achieve this
  23. Hi - I want to add to a php form a button which will open a pop-up window with records (names of people) and associated radio buttons. On click on respective name's radio button and SUBMIT, parent form textbox is populated. (list of names will be dynamically be selected fro MySQL table). Any suggestions? Many thanks! IB.
  24. I wrote this really nice posting system for a site I'm working on. Problem is, I messed it up somehow, and now I can retrieve $_POST variables so I can post stuff to a MySQL database. I'm really new to PHP, and I have no idea what I did wrong. HTML code: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="The PPC Planet software archive."> <meta name="author" content="JohnS and VP44"> <title>PPC Planet Public Archive</title> <link rel="canonical" href="https://getbootstrap.comhttps://getbootstrap.com/docs/4.5/examples/jumbotron/"> <!-- Bootstrap core CSS --> <link href="https://getbootstrap.com/docs/4.5/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <!-- Favicons --> <link rel="apple-touch-icon" href="images/ppc.png" sizes="180x180"> <link rel="icon" href="images/ppc.png" sizes="32x32" type="image/png"> <link rel="icon" href="images/ppc.png" sizes="16x16" type="image/png"> <meta name="theme-color" content="#28A745"> <style> .bd-placeholder-img { font-size: 1.125rem; text-anchor: middle; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } @media (min-width: 768px) { .bd-placeholder-img-lg { font-size: 3.5rem; } } .cover { background-image: url("images/earth.jpg"); background-size: cover; background-color: rgba(0, 0, 0, .8); background-blend-mode: multiply; } </style> <link href="stylesheets/2kstyle.css" rel="stylesheet" type="text/css"> <link href="stylesheets/archivestyle.css" rel="stylesheet" type="text/css"> <link href="stylesheets/posts.css" rel="stylesheet" type="text/css"> </head> <body style="background-color: black; color: white;"> <nav class="navbar navbar-dark fixed-top green"> <a class="navbar-brand" href="index.html"><b>PPC</b>Planet</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample09" aria-controls="navbarsExample09" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarsExample09"> <ul class="navbar-nav mr-auto "> <li class="nav-item"> <a class="nav-link" href="index.html">Home</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="archive.html">Archive <span class="sr-only">(current)</a> </li> <li class="nav-item"> <a class="nav-link" href="news.html">News</a> </li> <li class="nav-item"> <a class="nav-link" href="contact.html">Contact</a> </li> <li class="nav-item"> <a class="nav-link" href="about.html">About</a> </li> </ul> </div> </nav> <br><br><br><br> <script src="https://www.google.com/recaptcha/api.js"></script> <div class="content home"> <h2 style="color: white;"><b>PPC Planet Public Archive</b></h2> <br> <div id="backDiv"> <a href="deletepost.php"><b>(๐Ÿ—‘) Delete or (๐Ÿšฉ) report a post</b></a> <br><br> <button id="backDiv" class="greenBtn" onclick="back()">ยซ back</button> <br><br><br> </div> <div id="postsDiv" class="posts content home"></div> <div id="captcha"> <p>To prevent spam and unwanted submissions, we require that you complete the CAPTCHA below.</p> <br> <div class="g-recaptcha brochure__form__captcha" data-sitekey="6Ldku8QZAAAAABQJVhyfOnVljIoUoihUuBUfaFJn" required></div> <br><br><br> <input type="checkbox" id="findCheck" onchange="findToggle()"> <label for="findCheck">Filter Listings</label> <br> <div style="display: none;" id="searchDiv"> <!--text input--> <input type="radio" id="textsearch" name="filters" value="textsearch"> <label for="textsearch">Search by text</label> &nbsp;&nbsp;&nbsp; <input style="width: 75%;" placeholder="Show results that contain inputted text..." type="text" id="searchTxt" /> <br><br> <!--type picker--> <input type="radio" id="typesearch" name="filters" value="typesearch"> <label for="typesearch">Search by type</label> &nbsp;&nbsp;&nbsp; <select name="typeselect" id="typeselect"> <option value="freeware">Freeware</option> <option value="abandonware">Abandonware</option> <option value="self-made">I wrote it myself</option> </select> <br><br> <!--category picker--> <input type="radio" id="categorysearch" name="filters" value="categorysearch"> <label for="categorysearch">Search by category</label> &nbsp;&nbsp;&nbsp; <select name="categoryselect" id="categoryselect"> <option value="app">App</option> <option value="game">Game</option> <option value="driver">Driver</option> <option value="manual">Manual</option> <option value="setup">Setup</option> <option value="ROM">ROM</option> <option value="other">Other</option> </select> </div> <br><br> <button class="greenBtn" onclick="callValidation()">Visit Archive</button> </div> </div> <br><br><br><br> <script> document.getElementById("postsDiv").style.display = "none"; document.getElementById("captcha").style.display = "block"; document.getElementById("searchDiv").style.display = "none"; document.getElementById("backDiv").style.display = "none"; function callValidation() { if (grecaptcha.getResponse().length == 0) { //if CAPTCHA not complete alert('Please complete the CAPTCHA.'); } else { //reset reCAPTCHA and show + hide stuff grecaptcha.reset() document.getElementById("postsDiv").style.display = "block"; document.getElementById("backDiv").style.display = "block"; document.getElementById("captcha").style.display = "none"; //show posts if (document.getElementById("findCheck").checked == true && document.getElementById("typesearch").checked == true) { document.getElementById("searchTxt").value = document.getElementById("typeselect").value; } else if (document.getElementById("findCheck").checked == true && document.getElementById("categorysearch").checked == true) { document.getElementById("searchTxt").value = document.getElementById("categoryselect").value; } //fetch posts from database var posts_search_query = document.getElementById("searchTxt").value; fetch("posts.php?search_query=" + posts_search_query).then(response => response.text()).then(data => { document.querySelector(".posts").innerHTML = data; document.querySelectorAll(".posts .write_post_btn, .posts .reply_post_btn").forEach(element => { element.onclick = event => { event.preventDefault(); document.querySelectorAll(".posts .write_post").forEach(element => element.style.display = 'none'); document.querySelector("div[data-post-id='" + element.getAttribute("data-post-id") + "']").style.display = 'block'; document.querySelector("div[data-post-id='" + element.getAttribute("data-post-id") + "'] input[name='name']").focus(); }; }); document.querySelectorAll(".posts .write_post form").forEach(element => { element.onsubmit = event => { event.preventDefault(); fetch("posts.php?search_query=" + posts_search_query, { method: 'POST', body: new FormData(element) }).then(response => response.text()).then(data => { element.parentElement.innerHTML = data; }); }; }); }); } } function back() { document.getElementById("backDiv").style.display = "none"; document.getElementById("postsDiv").style.display = "none"; document.getElementById("captcha").style.display = "block"; document.getElementById("searchTxt").value = ""; } //when filter toggle changed function findToggle() { if (document.getElementById("findCheck").checked == true) { //when checked document.getElementById("searchDiv").style.display = "block"; document.getElementById("searchTxt").style.display = "block"; document.getElementById("categoryselect").style.display = "block"; document.getElementById("typeselect").style.display = "block"; document.getElementById("textsearch").checked = true; } else { //when unchecked document.getElementById("searchDiv").style.display = "none"; } } </script> <footer class="container center white "> <p>&copy; PPC Planet Team 2020</p> <br> </footer> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js " integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj " crossorigin="anonymous "></script> <script> window.jQuery || document.write('<script src="https://getbootstrap.com/docs/4.5/assets/js/vendor/jquery.slim.min.js "><\/script>') </script> <script src="https://getbootstrap.com/docs/4.5/dist/js/bootstrap.bundle.min.js " integrity="sha384-LtrjvnR4Twt/qOuYxE721u19sVFLVSA4hf/rRt6PrZTmiPltdZcI7q7PXQBYTKyf " crossorigin="anonymous "></script> </body> </html> PHP code: <?php include('mysqlconnect.php'); error_reporting(E_ALL); try { $pdo = new PDO('mysql:host=' . $DATABASE_HOST . ';dbname=' . $DATABASE_NAME . ';charset=utf8', $DATABASE_USER, $DATABASE_PASS); } catch (PDOException $exception) { // If there is an error with the connection, stop the script and display the error exit('Failed to connect to database!' . $exception); } // Below function will convert datetime to time elapsed string function time_elapsed_string($datetime, $full = false) { $now = new DateTime; $ago = new DateTime($datetime); $diff = $now->diff($ago); $diff->w = floor($diff->d / 7); $diff->d -= $diff->w * 7; $string = array('y' => 'year', 'm' => 'month', 'w' => 'week', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second'); foreach ($string as $k => &$v) { if ($diff->$k) { $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : ''); } else { unset($string[$k]); } } if (!$full) $string = array_slice($string, 0, 1); return $string ? implode(', ', $string) . ' ago' : 'just now'; } // This function will populate the posts and posts replies using a loop function show_posts($posts, $parent_id = -1) { $html = ''; if ($parent_id != -1) { // If the posts are replies sort them by the "submit_date" column array_multisort(array_column($posts, 'submit_date'), SORT_ASC, $posts); } $resultCount = 0; // Iterate the posts using the foreach loop foreach ($posts as $post) { if (($_GET['search_query']) != "") { if ($post['parent_id'] == $parent_id) { if (strpos(implode($post), $_GET['search_query'])) { $resultCount++; //check if optional variables are not set $screenshot = $post['screenshot']; if ($screenshot.trim() == "") { $screenshot = "https://ppcplanet.org/images/noscreenshot.png"; } $serial = $post['serial']; if ($serial.trim() == "") { $serial = "n/a"; } $source = $post['source']; if ($source.trim() == "") { $source = "n/a"; } $html .= ' <div class="post"> <br><br> <div> <h3 style="color: white;" class="name"><b>By ' . htmlspecialchars($post['postauthor'], ENT_QUOTES) . '</b></h3> <span class="date">' . time_elapsed_string($post['submit_date']) . '</span> </div> <br> <img class="image" style="width: 256px; height: 256px; overflow: hidden; object-fit: cover;" src=' . nl2br(htmlspecialchars($screenshot, ENT_QUOTES)) . ' alt="Screenshot"/> <br><br> <h2 class="content"><b><a href=' . nl2br(htmlspecialchars($post['url'], ENT_QUOTES)) . ' target="_blank">' . nl2br(htmlspecialchars($post['name'], ENT_QUOTES)) . '</a></b></h2> <br> <p class="content"><b>Description: </b>' . nl2br(htmlspecialchars($post['content'], ENT_QUOTES)) . '</p> <p class="content"><b>Serial: </b>' . nl2br(htmlspecialchars($serial, ENT_QUOTES)) . ' </p> <p class="content"><b>Original Source: </b> <a href =' . nl2br(htmlspecialchars($source, ENT_QUOTES)) . ' target="_blank">' . nl2br(htmlspecialchars($post['source'], ENT_QUOTES)) .'</a></p> <p class="content"><b>Type: </b>' . nl2br(htmlspecialchars($post['type'], ENT_QUOTES)) . ' </p> <p class="content"><b>Category: </b>' . nl2br(htmlspecialchars($post['category'], ENT_QUOTES)) . ' </p> <a class="reply_post_btn" href="#" data-post-id="' . $post['id'] . '">Add on... (ex. another version, manual, etc.)</a> ' . show_write_post_form($post['id']) . ' <div class="replies"> ' . show_posts($posts, $post['id']) . ' </div> </div> <br><br><br> '; ob_clean(); echo(strval($resultCount) . ' result(s) found for "' . $_GET['search_query'] . '"'); //display number of results } } } else { //add each post to HTML variable if ($post['parent_id'] == $parent_id) { //check if optional variables are not set $screenshot = $post['screenshot']; if ($screenshot.trim() == "") { $screenshot = "https://ppcplanet.org/images/noscreenshot.png"; } $serial = $post['serial']; if ($serial.trim() == "") { $serial = "n/a"; } $source = $post['source']; if ($source.trim() == "") { $source = "n/a"; } $html .= ' <div class="post"> <h2></h2> <br><br> <div> <h3 style="color: white;" class="name"><b>By ' . htmlspecialchars($post['postauthor'], ENT_QUOTES) . '</b></h3> <span class="date">' . time_elapsed_string($post['submit_date']) . '</span> </div> <br> <img class="image" style="width: 256px; height: 256px; overflow: hidden; object-fit: cover;" src=' . nl2br(htmlspecialchars($screenshot, ENT_QUOTES)) . ' alt="Screenshot"/> <br><br> <h2 class="content"><b><a href=' . nl2br(htmlspecialchars($post['url'], ENT_QUOTES)) . ' target="_blank">' . nl2br(htmlspecialchars($post['name'], ENT_QUOTES)) . '</a></b></h2> <br> <p class="content"><b>Description: </b>' . nl2br(htmlspecialchars($post['content'], ENT_QUOTES)) . '</p> <p class="content"><b>Serial: </b>' . nl2br(htmlspecialchars($serial, ENT_QUOTES)) . ' </p> <p class="content"><b>Original Source: </b> <a href =' . nl2br(htmlspecialchars($source, ENT_QUOTES)) . ' target="_blank">' . nl2br(htmlspecialchars($post['source'], ENT_QUOTES)) .'</a></p> <p class="content"><b>Type: </b>' . nl2br(htmlspecialchars($post['type'], ENT_QUOTES)) . ' </p> <p class="content"><b>Category: </b>' . nl2br(htmlspecialchars($post['category'], ENT_QUOTES)) . ' </p> <a class="reply_post_btn" href="#" data-post-id="' . $post['id'] . '">Add on... (ex. another version, manual, etc.)</a> ' . show_write_post_form($post['id']) . ' <div class="replies"> ' . show_posts($posts, $post['id']) . ' </div> </div> <br><br><br> '; } } } return $html; } // This function is the template for the write post form function show_write_post_form($parent_id = -1) { $rand = randomIdentifier(); //generate random identifier string $html = ' <div class="write_post" data-post-id="' . $parent_id . '"> <form method="post"> <h2 style="color: white;">New Post</h2> <br> <input name="parent_id" type="hidden" value="' . $parent_id . '"> <label for="name">Title:</label> <input style="width: 100%;" id="name" name="name" type="text" placeholder="Enter a title..." required> <br><br> <label for="screenshot">Screenshot (if applicable):</label> <input style="width: 100%;" id="screenshot" name="screenshot" type="url" placeholder="Screenshot URL"> <br><br> <label for="type">URL:</label> <input style="width: 100%;" id="url" name="url" type="url" placeholder="Download URL" required> <br><br> <label for="type">Description:</label> <textarea name="content" id="content" placeholder="Write a description..." required></textarea> <br><br> <label for="type">Original Source (if known):</label> <input style="width: 100%;" id="source" name="source" type="url" placeholder="Original Source URL"> <br><br> <label for="type">Serial (if applicable):</label> <input style="width: 100%;" id="serial" name="serial" type="text" placeholder="Serial"> <br><br> <label for="name">Your Name/Nickname:</label> <input style="width: 100%;" id="postauthor" name="postauthor" type="text" placeholder="Enter your name..." required> <br><br> <br> <label for="type">Choose a type:</label> <select name="type" id="type"> <option value="freeware">Freeware</option> <option value="abandonware">Abandonware</option> <option value="self-made">I wrote it myself</option> </select> &nbsp;&nbsp;&nbsp; <label for="category">Category:</label> <select name="category" id="category"> <option value="app">App</option> <option value="game">Game</option> <option value="driver">Driver</option> <option value="manual">Manual</option> <option value="setup">Setup</option> <option value="ROM">ROM</option> <option value="other">Other</option> </select> <br><br> <h2 style="color: white;">Post identifier string</h2> <input name="identifier" id="identifier" style="width: 100%;" readonly="true" type="text"" value="' . $rand . '"> <br> <p style="color: red;">This is your post identifier string. It can be used to delete this post in the future without having to contact an admin. <b>Make sure you do not lose it!</b></p> <br><br> <h2 style="color: white;">Make sure your submission meets the following criteria:</h2> <br> <p>๐Ÿ™‚ This submission is appropriate and doesn\'t have any mature content. - We want PPC Planet to be a safe place for people of all ages. Inappropriate submissions will be removed!</p> <p>๐Ÿ‘ This submission is either freeware, abandonware, or self-made. - No piracy! It\'s not fair to the developer(s).</p> <p>๐Ÿ’ป This submission has been tested, and works as advertised. - We don\'t want to have a bunch of broken software on the archive.</p> <p>๐Ÿงพ This submission is not already on the archive. - Be sure that you are posting something unique!</p> <p>๐Ÿ“ฑ This submission is related to Pocket PCs. - Remember, this is an archive of Pocket PC software.</p> <br> <p><b>By following these rules, we can make the archive a fun (and totally rad) place for everyone!</b></p> <br><br> <p style="color: red; font-size: xx-large; "><b>Make sure you have proofread your post, as you will not be able to edit it once it has been posted. Additionally, make sure you write your down identifier string somewhere if you have not already.</b></p> <br><br> <button type="submit">Create Post</button> <br><br> </form> </div> '; return $html; } if (isset($_GET['search_query'])) { // Check if the submitted form variables exist if (isset($_POST['name'])) { $stmt = $pdo->prepare('INSERT INTO posts (page_id, parent_id, name, screenshot, url, content, serial, type, category, identifier, source, postauthor, submit_date) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,NOW())'); $stmt->execute([ 1, $_POST['parent_id'], $_POST['name'], $_POST['screenshot'], $_POST['url'], $_POST['content'], $_POST['serial'], $_POST['type'], $_POST['category'], $_POST["identifier"], $_POST["source"], $_POST["postauthor"] ]); exit('Your post has been submitted! You can reload the page to see it.'); } // Get all posts by the Page ID ordered by the submit date $stmt = $pdo->prepare('SELECT * FROM posts WHERE page_id = ? ORDER BY submit_date DESC'); $stmt->execute([ 1 ]); $posts = $stmt->fetchAll(PDO::FETCH_ASSOC); // Get the total number of posts $stmt = $pdo->prepare('SELECT COUNT(*) AS total_posts FROM posts WHERE page_id = ?'); $stmt->execute([ 1 ]); $posts_info = $stmt->fetch(PDO::FETCH_ASSOC); } else { exit('No search query specified!'); } function randomIdentifier() { $pass = 0; $complete = false; while (!$complete) { //generate random identifier string until it is unique $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()'; $pass = array(); $alphaLength = strlen($alphabet) - 1; for ($i = 0; $i < 100; $i++) { $n = rand(0, $alphaLength); $pass[] = $alphabet[$n]; } include('mysqlconnect.php'); $pdo = new PDO('mysql:host=' . $DATABASE_HOST . ';dbname=' . $DATABASE_NAME . ';charset=utf8', $DATABASE_USER, $DATABASE_PASS); $data = implode($pass); $stmt = $pdo->prepare( "SELECT identifier FROM posts WHERE identifier =:id" ); $stmt->bindParam(':id', $data, PDO::PARAM_STR); $stmt->execute(); $myIdentifier = $stmt->fetch(); if (!$myIdentifier) { //identifier is unique $complete = true; } } return $data; } ?> <div class="post_header"> <span style="color: white;" class="total"><?=$posts_info['total_posts']?> total post(s)</span> <a style="color: white;" href="#" class="write_post_btn" data-post-id="-1">Create Post</a> </div> <?=show_write_post_form()?> <?=show_posts($posts)?> How can I fix this so posting works again? All help is appreciated!
  25. What is the best table structure when constructing what will be a potentially large multi-user platform? Example- Each user inputs their own individualized information into a table, for recall only to that specific user and to certain other users defined as administrators or half-administrators super users. Would it be better to store this all in a single table, or to give each user their own individual table on formation of the account?
×
×
  • 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.