I would like to add a search box by date.to my table using mysql php

I have a table associated with a database mysql , All I want is to add a search box by date ,Although I have tried many methods, but unfortunately all of them did not work for me as I should This is my code :

    <form action="" method="GET"">
<input type="date" name="search" class="form-control" placeholder="Start"  >
<button type="submit" class="btn btn-primary">Search</button>
</form>


    function getRecords($params) {
            $rp = isset($params['rowCount']) ? $params['rowCount'] : 10;
            
            if (isset($params['current'])) { $page  = $params['current']; } else { $page=1; };  
            $start_from = ($page-1) * $rp;
            
            $sql = $sqlRec = $sqlTot = $where = '';
            
            if( !empty($params['searchPhrase']) ) {   
                $where .=" WHERE ";
                $where .=" ( fullname LIKE '".$params['searchPhrase']."%' ";    
                $where .=" OR email LIKE '".$params['searchPhrase']."%' ";

                $where .=" OR phone LIKE '".$params['searchPhrase']."%' )";
                
            
                
           }
           if( !empty($params['sort']) ) {  
                $where .=" ORDER By ".key($params['sort']) .' '.current($params['sort'])." ";
            }
           // getting total number records without any search
            $sql = "SELECT * FROM `api` where  DATE_FORMAT(created_at, '%Y-%m-%d') = DATE_SUB(CURRENT_DATE(),INTERVAL 1 DAY)";
            $sqlTot .= $sql;
            $sqlRec .= $sql;
            
            //concatenate search sql if value exist
            if(isset($where) && $where != '') {

                $sqlTot .= $where;
                $sqlRec .= $where;
            }
            if ($rp!=-1)
            $sqlRec .= " LIMIT ". $start_from .",".$rp;
            
        

How do you handling floating point arithmetic when using the ParseObject.increment() function

In javascript, we know that some floating point arithmetic will result in values that contain a very small remainder. for example if I open my console and do this math I get this result as seen here

enter image description here

Typically one must know to round after doing these operations. When using parse, and using the increment function. If I have a column called Quantity in my DB and it currently has a value of 6.5 and I call myobject.increment("Quantity", -4.1) we end up with an unrounded value in the DB. the use of increment is required here as many entities may be adjusting this column at or near the same time, so race conditions are a concern.

since the arithmetic happens under the hood, how does parse expect one to handle cases like I mentioned above.

How to check the URL of a page using JavaScript

How would I make a script that detects the current URL of the page? Here is what I want it to do:

When the script is on example.com it lets the page load normally.

When the script is on coolsite.com it replaces the content of the page with a note showing a link to example.com

How would I do that? Is there a function that detects the location of the window? I can put it in a <script> element or a separate JavaScript file.

Thank you for any help!

How to fix a slide position using Slick Slider

I’m trying to make a slider based on Slick Slider plugin (http://kenwheeler.github.io/slick/)

The main point is that I have to fix a position of a slide on click. For example, if I click on slide 3, it will be stucked on its position and every other slide will go through it in an order.

For instance: if slide 3 is clicked, it turns yellow, it is on the third position. We click “Next”, the 3rd slide stay fixed, but all the others have moved one position, i.e. visible order of numbers: 2 4 3 5 6… Thus, it always stands motionless “in its place”, regardless of the slider paging. The fixation is removed by a second click, the slide remains in the same place and moves with everyone.

I have only the solution when the slide changes its place but I have to do the logic described above. Here’s the code I have now: https://jsfiddle.net/tomavl/4mgLrs5t/10/

<div class="slider">
  <div class="slide">1</div>
  <div class="slide">2</div>
  <div class="slide">3</div>
  <div class="slide">4</div>
  <div class="slide">5</div>
  <div class="slide">6</div>
  <div class="slide">7</div>
  <div class="slide">8</div>
  <div class="slide">9</div>
</div>

body {
  background: #FFF;
  padding: 20px;
  font-family: Helvetica;
}

.slider {
  color: #333;
  padding: 0 0 30px;
}

.slide {
  font-size: 90px;
  width: 150px;
  padding: 10px 0;
  margin: 0;
  text-align: center;
  border: 1px solid #999;
}
.slide.locked { 
  background: rgba(255,255,0,0.5); 
}

.slick-prev, .slick-next {
  position: absolute;
  bottom:0;
}
.slick-next { left:80px; }

let currentFocus, nextFocus, prevFocus;

$(document).ready(function(){

  $('.slider').slick({
    dots: false,
    infinite: false,
    speed: 300,
    slidesToShow: 5,
    slidesToScroll: 1,
     responsive: [
      {
        breakpoint: 1024,
        settings: {
          slidesToShow: 3,
        }
      },
      {
        breakpoint: 600,
        settings: {
          slidesToShow: 2,
        }
      },
      {
        breakpoint: 480,
        settings: {
          slidesToShow: 1,
        }
      }
    ]
  });

    function setForFocus() {
      nextFocus = currentFocus.next();
    prevFocus = currentFocus.prev();
    if (prevFocus.length == 0)
            prevFocus = null; 
    if (nextFocus.length == 0)
            nextFocus = null; 
  }

  $('.slide').on('click', function() {   
    if ($(this).hasClass('locked')) {
        $(this).toggleClass('locked');
        currentFocus = nextFocus = prevFocus = null;
    } else {
        if (typeof currentFocus !== "undefined" &&
        currentFocus !== null)
            currentFocus.toggleClass('locked');
        $(this).toggleClass('locked');
        currentFocus = $(this);
        setForFocus();      
    }
    
  });

    $('.slick-next').on('click', function() {
    if (typeof currentFocus !== "undefined" &&
        currentFocus !== null && 
      typeof nextFocus !== "undefined" &&   
      nextFocus !== null) {
          let next_text = Number(nextFocus.text());
          let cur_text = Number(currentFocus.text());
              currentFocus.text(next_text);
          nextFocus.text(cur_text);
          currentFocus.toggleClass('locked');
          nextFocus.toggleClass('locked');
          currentFocus = nextFocus;
          setForFocus();  
      }
  });

    $('.slick-prev').on('click', function() {
    if (typeof currentFocus !== "undefined" &&
        currentFocus !== null && 
      typeof prevFocus !== "undefined" &&   
      prevFocus !== null) {
          let prev_text = Number(prevFocus.text());
          let cur_text = Number(currentFocus.text());
              currentFocus.text(prev_text);
          prevFocus.text(cur_text);
          currentFocus.toggleClass('locked');
          prevFocus.toggleClass('locked');
          currentFocus = prevFocus;
          setForFocus();  
      }
  });
});```

ReferenceError: process is not defined after upgrading to Next.js 12 from 11.x.x

Getting this issue after upgrading to latest version 12 from 11.x.x

Unhandled Runtime Error:
ReferenceError: process is not defined

Here is my package.json:

{
  "name": "tnhc-fe",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@hookform/resolvers": "^2.8.2",
    "axios": "^0.23.0",
    "jwt-decode": "^3.1.2",
    "local-storage": "^2.0.0",
    "moment": "^2.29.1",
    "next": "12",
    "next-i18next": "^8.9.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-hook-form": "^7.17.4",
    "yup": "^0.32.11",
    "zustand": "^3.5.13"
  },
  "devDependencies": {
    "@types/jest": "^27.0.3",
    "@types/node": "^16.11.0",
    "@types/react": "17.0.30",
    "autoprefixer": "^10.3.7",
    "eslint": "8.0.1",
    "eslint-config-next": "11.1.2",
    "jest": "^27.4.3",
    "postcss": "^8.3.9",
    "tailwindcss": "^2.2.17",
    "typescript": "4.4.4"
  }
}

How can I call unscoped functions in eval without using “this”

This works:

import isValidDocument from './isValidDocument'

class Test {
  constructor() {
    Object.assign(this, { isValidDocument})
  }

  execute(person) {
    const evalResult = eval('this.isValidDocument(person)')
    console.log("Eval Result:", evalResult)
  }
}

but this doesn’t:

// ...
execute(person) {
  const evalResult = eval('isValidDocument(person)')
  console.log("Eval Result:", evalResult)
}
// ...

Basically, i want to be able to call the functions without using the this keyword.

How can I achieve that?


If you want context

I have rules (js expressions) stored in a database and i need it to execute them dinamically, the functions are fixed but the expressions can change.

Expression example: isValidDocument(person) && person.age > 18

The user will be able to change the expressions.

Yeah, i know about the security issue and i also accept suggestions to isolate the env. Currently, the expressions are made using blocks on the frontend and then the backend converts them to actual javascript statements, but the plan is to allow the user to create his own expressions directly.

how can i show image from json file to html

Hi i want to take the image from the json file and put it into my html table. right now it gives me the error: GET c:fakepathFULLSCALE.jpeg net::ERR_UNKNOWN_URL_SCHEME. i want to show the image beside the pris. look at the image attached to see how it looks nowhtml page
Please help me, it’s an exam project

this is my code:

varer.js

document.addEventListener("DOMContentLoaded", (event) => {
  document.getElementById("form").addEventListener("submit", (event) => {
    event.preventDefault();

    const varer = document.getElementById("varer").value;
    const pris = document.getElementById("pris").value;
    const billede = document.getElementById("billede").value

    const opretVare = {
      varer: varer,
      pris: pris,
      billede: billede
    };

    fetch("http://localhost:8200/varer/createvarer", {
        method: "POST",
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(opretVare),
      })
      //converter det til Json
      .then((response) => response.json())
      .catch(() => {
        window.alert("Der skete en fejl");
      });
  });
});


async function getGoods() {
  const response = await fetch("http://localhost:8200/varer/getproducts")
  const result = await response.json()
  return result
}

async function deleteGoods(id) {
  const response = await fetch("http://localhost:8200/varer/delete" + id, { 
    method: 'DELETE'
  })
  const result = await response.json()
  return result
}

function renderTable(goods) {
    const table = document.getElementById('varerTable');
    let tableHtml = `
      <tr>
        <th>Varekategori</th>
        <th>Pris</th>
        <th>Billede</th>
      </tr>`;
    for (const row of goods){
      tableHtml += `
        <tr>
          <td>${row.varer}</td>
          <td>${row.pris}</td>
          <td><img src="${row.billede}" style="height:100px;width000px;"</td>
          <td><button onclick = "handleDelete"(${row.id})"> Delete </button></td>
          <td><button onclick ="toDo"> Edit </button></td>
        </tr>
      `;
    }
    table.innerHTML = tableHtml;
}

async function handleDelete(id) {
  try {
    await deleteGoods(id)
    const goods = await getGoods()
    renderTable(goods)
  } catch(err) {
    console.error(err)
  }  
}

async function handleLoad() {
  try {
    const goods = await getGoods()
    renderTable(goods)
  } catch(err) {
    console.error(err)
  }  
} 
document.getElementById("clickMe").addEventListener('click', handleLoad);


//vis alle varene på siden
  router.get("/getproducts", (req, res) =>{
    res.status(200).json(products)
    console.log(products)
   })

varer.json

[{"varer":"mælk","pris":"10","billede":"C:\fakepath\FULLSCALE.jpeg"}]

“FindMany” is picked up as undefined in prisma query

I want to do a query on this table called SRCMembers using the following code

const members = await db.sRCMembers.findMany()

i’m importing Prisma through the db file as such

import db from "db"

and this exact syntax is working on auto generated models such as ‘user’

const members = await db.user.findMany()

but when I run that code I get and error that says

‘TypeError: Cannot read properties of undefined (reading ‘findMany’)’

the following is the schema.prisma model

model SRCMembers {
  id            Int     @id @default(autoincrement())
  studentNumber String
  name          String
  surname       String
  age           String
  branch        String  @default("1st year")
  email         String
  course        String?
  year          String?

}

the code editor picks up the ‘findMany’ and even gives hints on it.
but when executed it is then undefined.

when I log SRCMembers I get this

{
  findUnique: [Function (anonymous)],
  findFirst: [Function (anonymous)],
  findMany: [Function (anonymous)],
  create: [Function (anonymous)],
  createMany: [Function (anonymous)],
  delete: [Function (anonymous)],
  update: [Function (anonymous)],
  deleteMany: [Function (anonymous)],
  updateMany: [Function (anonymous)],
  upsert: [Function (anonymous)],
  count: [Function (anonymous)],
  aggregate: [Function (anonymous)],
  groupBy: [Function (anonymous)]
}

along with prisma as the ORM I am making use of BlitzJS

why is the findMany undefined and what can I do about it?

Why does defining URL separately cause this seemingly unrelated error?

Webpack v5 has built-in support for web workers, initialized in the following format:

const worker = new Worker(new URL("./worker.js", import.meta.url));

While working on a Next.js (with webpack v5) project, I noticed that a slight variation of the above breaks down:

const url = new URL("./worker.js", import.meta.url);
const worker = new Worker(url);

This leads to the following error on the browser console:

SyntaxError: import declarations may only appear at top level of a module

which occurs because (and only when) I’m importing something in the worker file.

Here’s a minimal reproduction of the above. Instructions to run and the lines to look at are in the README.

Why does this happen? How does defining the worker URL in a separate variable change things?

router.push with query parameters leads to localhost:8080/?categoryId=2. Why is there a slash before the query parameter?

I am using the router like this:

router.push({ name: 'home', query: { categoryId: category.id } })

And my route looks like this:

{
    path: '/',
    name: 'Home',
    component: Home
},

Is it normal for the URL to have a slash before the query parameter? Even if it doesn’t matter functionality wise, I feel like localhost:8080?categoryId=2 looks better than localhost:8080/?categoryId=2 and was wondering if I could somehow remove the slash?

Tampermonkey run script every 10s

I’m trying to build a script that runs every 10seconds and sends a GM_notification. But I dont receive any notification. What’s wrong?

// ==UserScript==
// @name        _Notification test
// @grant       GM_notification
// @require     http://code.jquery.com/jquery-1.12.4.min.js
// ==/UserScript==

setTimeout(function() {

GM_notification ( {title: 'foo', text: '42'} );

}, 1000);

reorganizing data columns Snowflake using stored procedure

Using stored procdeure in Snowflake I am trying to change the columns order for a part of the data table.

Here is my table

column1 column2 column3 column4    column5
---------------------------------------------
Year   Country  Name    City
2020    US      Briand   NY
2021    US      John     LA
2021    UK      Mark     London

City   Name    Year      Country      Age
Paris  Jacques  2017      FR          55
Madrid Juan     2015      ES          25
Dublin Steven   2018      IE          37

So there is 5 differents structures in the same table.
All 5 structures doesn’t have the same number of columns but the column name can be match and missing column can be fill with null values. Moreover there is a blank row between each different data structure.
The output should be :

Year      Country     City     Name          Age
-------------------------------------------------
2020        US        NY        Briand       Null
2021        US        LA        John         Null
2021        UK        London    Mark         Null
2017        FR        Paris     Jacques      55
2015        ES        Madrid    Juan         25
2018        IE        Dublin    Steven       37

So I thought that the only way is to do a stored procedure but I have no idea how it works and if it is possible to resolve my problem this way.

CREATE OR REPLACE PROCEDURE proc_columns_matching()
returns string
language javascript
as
$$
var sql = "select * from countries_pp";
var statement1 = snowflake.createStatement( {sqlText: pp} );
var result_set1 = statement1.execute();

while(result_set1.next() != ''){
var column1= result_set1.getColumnValue(1)
}

return column1;
$$
;

CALL proc_smart_impulse();

So I tried to identify the blank cell to split the table but I am stuck here.

why does useReducer run twice?

i have a problem.
im creating a shop cart using react js.
i have a component called Header and a component for contextProvider. in contextProvider i have a useReducer.
my problem is with these two components. when i click on a product, it normally add just one product to cart. it is ok and i want this. but the problem is here that when i click on cart icon, a modal card will be on screen and if i close that modal card them add a product to cart, the product will be added to cart two times!! i know what line of code cause this error but i dont know why it happens! the problem is with the state in Header component. if i remove and add that in context component, it will work normally. but why?? if you need anything else with my codes, tell me. here is my codes:
my context:

        import React, { useReducer, useState } from "react";

const Context = React.createContext({
  allAddedToCart: 0,
  productsList: [],
  addToCart: () => {},
  initializeProductList: (product) => {},
/*   open: false,
  setOpen: (open) => {}, */
});

export const ContextProvider = (props) => {
/* const [open, setOpen] = useState(false); */
  const [productsState, dispatchProducts] = useReducer(
    (prevState, action) => {
      if (action.type === "add_to_cart") {
        prevState.products_list.forEach((element, index) => {
          console.log(index);
          if (element.id === action.id) {
            element.number++;
            element.allPrice += element.price;
            console.log("finished");
          }
        });
        return {
          allAddedToCart: prevState.allAddedToCart + 1,
          products_list: prevState.products_list,
        };
      } else if (action.type === "initialize_list") {
        return {
          allAddedToCart: prevState.allAddedToCart,
          products_list: [...prevState.products_list, action.product],
        };
      }
    },
    {
      allAddedToCart: 0,
      products_list: [],
    }
  );
  return (
    <Context.Provider
      value={{
        allAddedToCart: productsState.allAddedToCart,
        productsList: productsState.products_list,
        addToCart: (id) => {
          console.log("add me to the cart");
          dispatchProducts({ type: "add_to_cart", id: id });
        },
        initializeProductList: (product) => {
          dispatchProducts({ type: "initialize_list", product: product });
        },
/*         open: open,
        setOpen: (open) => {
          setOpen(open);
        } */
      }}
    >
      {props.children}
    </Context.Provider>
  );
};

export default Context;

my Header component:

import { useContext, useState } from "react";
import ReactDOM from "react-dom";
import Context from "../context/context";
import styles from "../styles/Header.module.css";
import CartModal from "./CartModal";

const Header = (props) => {
    const ctx = useContext(Context)
    const [open, setOpen] = useState(false);

  return (
    <header className={styles.header}>
      {open ? ReactDOM.createPortal(<CartModal close={() => {setOpen(false)}} />, document.getElementById("modal_place")) : ""}
      <h1 className={styles.title}>a react shopping cart project</h1>
      <a href="/" onClick={(e) => {e.preventDefault(); setOpen(true)}}>
        <i className={`fas fa-shopping-cart ${styles.cart}`}></i>
        <span className={styles.added_products_number}>{ctx.allAddedToCart}</span>
      </a>
    </header>
  );
};

export default Header;

thanks for helping 🙂