Jump to content

Barand

Moderators
  • Posts

    24,551
  • Joined

  • Last visited

  • Days Won

    821

Community Answers

  1. Barand's post in Display only the current user's details using PHP and MySQL was marked as the answer   
    How do you know which user is logged in? You have called session_start() but I see no references to any $_SESSION variables.
     
    You should be storing the ID of the user on login then using that id in your queries. (... WHERE ID = $_SESSION['userid'] ) or, better yet, use a prepared query passing the id as a parameter.
     
    You will be expecting only a single profile result so why have the while() loop? A single fetch is all you need.
     
    The first mention of username in that query is a column name and should NOT be in quotes. Your syntax following LIKE is also wrong.
     
    Don't use a nastyfrisk (SELECT * ) in your queries - specify the columns you need.
     
    As for your error messages - if your $result contains a boolean (false) value then the query didn't work.
  2. Barand's post in Filter array by KEY was marked as the answer   
    Rather than hardcoding the date as I did above
     
    $sunday = (new DateTime('last sunday'))->format('Y-m-d');                                             $arr = array_filter($arr, function($v) use ($sunday) { return $v < $sunday;}, ARRAY_FILTER_USE_KEY);
  3. Barand's post in PHP dropdown menu to fetch columnar data was marked as the answer   
    You are missing an all-important line
    $sql = "SELECT `$mySelect` as mySelect FROM employees"; $result = mysqli_query($link, $sql);                      //          add this line to query the database  If still not working, post the code you now have.                                      
  4. Barand's post in Load canvas after ajax call was marked as the answer   
    In your printme.php, build the <canvas>...</canvas> element as a string then output the string.
     
    I have never used canvas, but here is an example using SVG, which is fairly similar.
     
    SAMPLE.HTML
     
    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Sample SVG with AJAX</title> <style type='text/css'> div {     width: 40%;     height: 150px;     margin: 20px;     padding: 20px;     border: 1px solid gray;     float: left; } </style> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type='text/javascript'>     function draw()     {         var color = $("#colorselect").val();         var sides = $("#sideselect").val();                  $.get (             "sample_svg.php",             { "color" : color ,               "sides" : sides             },             function(resp) {                 $("#graphics").html(resp);             }         )     }          $().ready( function() {                  $("#colorselect").change( function() { draw(); })         $("#sideselect").change( function() { draw(); })     }) </script> </head> <body> <div>     Color: <select id='colorselect'>                <option value='0'>- choose -</option>                <option value='red'>Red</option>                <option value='blue'>Blue</option>                <option value='green'>Green</option>             </select>     <br><br>     Sides: <select id='sideselect'>                <option value='0'>- choose -</option>                <option value='3'>Three</option>                <option value='4'>Four</option>                <option value='5'>Five</option>                <option value='6'>Six</option>                <option value='7'>Seven</option>                <option value='8'>Eight</option>             </select> </div>   <div id="graphics">     <!-- graphic goes here --> </div>   </body> </html>  
    SAMPLE_SVG.PHP (called via ajax)
     
    <?php $color = isset($_GET['color']) ? $_GET['color'] : '#888'; $sides = isset($_GET['sides']) ? $_GET['sides'] : 0; exit( writeSVG($color, $sides) );            //output the SVG code function writeSVG($color, $sides) {     $svg = "<svg width='100' height='100' viewBox='0 0 100 100'>         <rect x='0' y='0' width='100' height='100' fill='#CCC'/>\n";     if ($sides < 3 || $sides >   {         $svg .= "<circle cx='50' cy='50' r='50' stroke='black' fill='$color'/>\n";     }     else {         $path = "M 100 50 ";         $theta = 2 * M_PI / $sides;         $svg .= "<circle cx='50' cy='50' r='50' stroke='black' fill='none'/>\n";         for ($i=1; $i<$sides; $i++) {             $x = 50 + 50 * cos($i * $theta);             $y = 50 - 50 * sin($i * $theta);             $path .= "L $x $y ";         }         $path .= "z ";         $svg .= "<path d='$path' fill='$color' />\n";     }         $svg .= "</svg>\n";     return $svg; } ?>
  5. Barand's post in Database of Show Times was marked as the answer   
    This was a problem that piqued my interest. I started out comparing start and end times, looking for overlaps and so on. I was doing quite well with my test scenario until I got to the final regular show that was interrupted twice by special shows. It was there my algorithm collapsed in a heap.
     
    At tat point I embarked on a brute force solution, splitting the day into timeslots (15 minute slots to accomodate my data times). These slots were then filled with priority special shows and remaining empty slots filled by the regualr schedule.
     
    Data and Results
     
    mysql> select * from regular_show;                                   mysql> select * from special_show; +--------+-----------+---------------------+---------------------+   +--------+-----------+---------------------+---------------------+ | idshow | title     | start_time          | end_time            |   | idshow | title     | start_time          | end_time            | +--------+-----------+---------------------+---------------------+   +--------+-----------+---------------------+---------------------+ |      1 | Regular 1 | 2018-04-03 09:00:00 | 2018-04-03 11:00:00 |   |      1 | Special 1 | 2018-04-03 08:00:00 | 2018-04-03 10:00:00 | |      2 | Regular 2 | 2018-04-03 11:00:00 | 2018-04-03 12:00:00 |   |      2 | Special 2 | 2018-04-03 11:00:00 | 2018-04-03 12:00:00 | |      3 | Regular 3 | 2018-04-03 12:00:00 | 2018-04-03 15:00:00 |   |      3 | Special 3 | 2018-04-03 14:00:00 | 2018-04-03 16:00:00 | |      4 | Regular 4 | 2018-04-03 15:00:00 | 2018-04-03 16:00:00 |   |      4 | Special 4 | 2018-04-03 19:00:00 | 2018-04-03 20:00:00 | |      5 | Regular 5 | 2018-04-03 16:00:00 | 2018-04-03 18:00:00 |   |      5 | Special 5 | 2018-04-03 20:30:00 | 2018-04-03 21:00:00 | |      6 | Regular 6 | 2018-04-03 18:00:00 | 2018-04-03 20:00:00 |   |      6 | Special 6 | 2018-04-03 21:15:00 | 2018-04-03 21:30:00 | |      7 | Regular 7 | 2018-04-03 20:00:00 | 2018-04-03 23:00:00 |   +--------+-----------+---------------------+---------------------+ +--------+-----------+---------------------+---------------------+ ** RESULTS           Special 1                8:00am to 10:00am            Regular 1               10:00am to 11:00am            Special 2               11:00am to 12:00pm            Regular 3               12:00pm to 2:00pm             Special 3                2:00pm to 4:00pm             Regular 5                4:00pm to 6:00pm             Regular 6                6:00pm to 7:00pm             Special 4                7:00pm to 8:00pm             Regular 7                8:00pm to 8:30pm             Special 5                8:30pm to 9:00pm             Regular 7                9:00pm to 9:15pm             Special 6                9:15pm to 9:30pm             Regular 7                9:30pm to 11:00pm      
    My code
     
    function publish($show, $start, $end) {     $s = (new DateTime($start))->format('g:ia');     $e = (new DateTime($end))->modify('+15 minutes')->format('g:ia');     printf('%-20s %10s to %-10s<br>', $show, $s, $e ); } // *************************************** // Shortest interval used is 15 min, // so create array of 15 min // timeslots for the day // *************************************** $schedule_date = '2018-04-03'; $dt1 = new DateTime($schedule_date.'07:00'); $dt2 = new DateTime($schedule_date.'23:59'); $di =  new DateInterval('PT15M'); $dp =  new DatePeriod($dt1, $di, $dt2); $timeslots = []; foreach ($dp as $t) {     $time = $t->format('H:i');     $timeslots[$time] = ''; } // ******************************************* // get al1 shows, placing special shows first // to give them priority placement // ******************************************* $res = $db->prepare("SELECT *                     FROM                         (                         SELECT r.title                              , r.start_time                              , r.end_time                              , 2 as priority                         FROM regular_show r                         UNION                         SELECT s.title                              , s.start_time                              , s.end_time                              , 1 as priority                         FROM special_show s                         ORDER BY  priority, start_time, end_time                         ) shows                     WHERE DATE(start_time) = ?"); $res->execute( [$schedule_date] ); // ****************************************************** // place shows in their respective timeslots // only placing shows if the timeslot // is still empty // ****************************************************** foreach ($res as $r) {     $st = date('H:i', strtotime($r['start_time']));     $et = date('H:i', strtotime($r['end_time']));     foreach ($timeslots as $hm => $v) {         if ($hm >= $st && $hm < $et) {             if (empty($v)) {                 $timeslots[$hm] = $r['title'];             }         }     } } // **************************************************** // find the start and end of each show and // publish the times // **************************************************** $schedule = []; $prev = ''; foreach ($timeslots as $hm => $show) {     if (!$show) continue;     if ($show != $prev) {         $title = $show;         $st = $hm;         $prev = $show;     }     $schedule[$st] = [ $title, $hm ]; } foreach ($schedule as $st => $show) {     publish($show[0], $st, $show[1]); }
  6. Barand's post in convert sql check to if statement was marked as the answer   
    The conversion works OK then.
     
    In php you would do something like this
     
    $expire = '2018-03-20'; $ship = '2018-01-19'; $date1 = new DateTime($expire); $date2 = (new DateTime($ship))->add(new DateInterval('P7D')); if ($date1 <= $date2) {     // do whatever if expired } else {     // do whatever if not expired }  
    However, Psycho's method of doing the test in the query looks a lot better. It then becomes
     
    if ($row['expired']) {     // do this } else {     // do that }
  7. Barand's post in PHP Scheduler/Calender - Take 2! was marked as the answer   
    I think you should re-read the manual
  8. Barand's post in Flatten a 2D array to only contain values contained in all 2D was marked as the answer   
    Use array_intersect to check for common values
     
    $data = [   [28, 6],  [6], [61,6,28]  ];          $result = []; foreach ($data as $arr) {     $result = empty($result) ? $arr : array_intersect($result, $arr); } // view result echo '<pre>', print_r($result, 1), '</pre>';
  9. Barand's post in summing 2 columns data in single table with different condition was marked as the answer   
    Grouping by sku would also give the totals you expect but the values for po_no, date and vendor would be of no particular meaning as they could come from any arbitrary record in each of the groups.
  10. Barand's post in Database Schema was marked as the answer   
    A basic rule of relational database design is "do not store derived data such as counts or totals". You get them when required with a query.
  11. Barand's post in Linking Users To Correct Videos was marked as the answer   
    Pass the id of the video in the link and then retrieve the one with that id.
     
    At the moment, if more than one video in the query results you are left with values from the last row in $video and $title
  12. Barand's post in If and elseif order of processing was marked as the answer   
    What happens when you run it?
     
    Whatever happens, that what it does - simple.
     
    (It will stop look at other conditions as soon as it encounters a condition that evaluates as "true")
  13. Barand's post in Hi, i'm new to php and mysql so any helps will be greatly appreciated. I have the the code below but it looks like it's not working. I need the data i was marked as the answer   
    Because I gave SUM() the alias "sales" you should reference that value with $row['sales'].
     
    Is the technician that appears the only one with any sales? The JOIN will only result in rows where there are matching records in both tables. If you want all technicians even if they have no sales then we need to switch to a LEFT JOIN

    SELECT t.id , t.firstname . t.lastname , SUM(s.sale) as sales FROM technician t LEFT JOIN everyday_sale s ON s.technician_id = t.id GROUP BY t.id
  14. Barand's post in Go back to search result was marked as the answer   
    You should be passing parameters to a search page via GET and not using POST
  15. Barand's post in New to PHP - Issue with processing a form was marked as the answer   
    I am surprised either one works as they are .HTML files and not .PHP (unless your server is unusually configured)
     
    If you want the form to call the same page you can just leave the action blank(action="").
  16. Barand's post in Group by chronology... was marked as the answer   
    You should not be storing names and schools in both tables, they belong in the player table only along with a unique id for each player. It is that id that should be in the review table and that is what you should then join on.
     
    You were told before about about those concats in your where clause (so I guess telling you anything is a waste of time). It is also completely unnecessary in the group by - just
    ... GROUP BY apr.nameFirst, apr.nameLastDo not use "SELECT *", Specify the columns you need. This is particularly wasteful when joining tables as there will always be duplicate (matching) column values. 
    As or your problem stated, try
    ... ORDER BY MAX(time) DESC LIMIT 10
  17. Barand's post in Form is submitting to page was marked as the answer   
    In your form tag you have

    method"POST" which is missing the "=" sign. 
    As the default method is GET, the values are passed in the url instead of being POSTed.
  18. Barand's post in How save a multiarray so that it may be reloaded and used. was marked as the answer   
    You could use json_encode then save it to a text file. Then use json_decode after reading it back to recreate the array.
  19. Barand's post in another table to the query was marked as the answer   
    You will get "ambiguous field" error when you reference fields with the same name in two different tables. Prefix the column names with the table names (tablename1.colA , tablename2.colA) or aliases to avoid the ambiguity.
     
    If you still have a problem, post the query.
     
    Best wishes for 2018.
  20. Barand's post in Message -- Warning: file_get_contents -- was marked as the answer   
    You really don't see a problem?
  21. Barand's post in Starting numbers in for loop in php with 00 characters was marked as the answer   
    sprintf()
     
    EG

    for ($i=1; $i<=10; $i++) { echo sprintf("%03d.jpg", $i) . '<br>'; }
  22. Barand's post in How to write a function that replaces text was marked as the answer   
    Use an associative array and strtr()
    EG

    $links = [ 'dogs' => '<a href="link1">dogs</a>', 'red dogs' => '<a href="link2">red dogs</a>', 'big red dogs' => '<a href="link3">big red dogs</a>' ]; $description = "the dogs and the red dogs were being chased by big red dogs"; $newdesc = strtr($description, $links);
  23. Barand's post in How to echo column name when max — Find highest value was marked as the answer   
    If yu have to create a view then this query can be used to replicate the table in my example

    SELECT IDevent , 1 as cavch , cavch1 as amount FROM avdcav UNION SELECT IDevent , 2 as cavch , cavch2 as amount FROM avdcav UNION SELECT IDevent , 3 as cavch , cavch3 as amount FROM avdcav ORDER BY IDevent, cavch
  24. Barand's post in format date inside query was marked as the answer   
    I assume when you say "timestamp" you are referring to a unix timestamp (integer) and not a mysql timestamp (yyyy-mm-dd hh:ii:ss).
     
    In which casa you need to first convert to mysql datetime format before you can use date_format(). Store date/time info in a database using DATE, DATETIME or TIMESTAMP type columns, not integer. They are readable and wor with the functions.

    ,,, DATE_FORMAT(FROM_UNIXTIME(date), '%m/%d/%Y') as orderdate
  25. Barand's post in How to only get one object for each row was marked as the answer   
    Use a table subquery which has the min price and name of each item then join to this matching on name and price.

    SELECT s.name , s.price , s.quantity FROM shop s JOIN ( SELECT name , MIN(price) as price FROM shop GROUP BY name ) mins USING (name, price)
×
×
  • 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.