why is php is sending a null to a localhost mysql?

I am creating a hotel management website and I am trying to insert data into the following columns to a locally hosted phpmyadmin:

  • gname
  • email
  • phone
  • ccn
  • expmonth
  • cvv
  • checkin_date
  • checkout_date
  • cartCost

The php is stored in my htdocs>myproject>checkout.php.

I keep on getting the Fatal error:

Uncaught mysqli_sql_exception: Column ‘gname’ cannot be null in C:xampphtdocsmyprojectcheckout.php:24 Stack trace: #0 C:xampphtdocsmyprojectcheckout.php(24): mysqli_stmt->execute() #1 {main} thrown in C:xampphtdocsmyprojectcheckout.php on line 24:

<?php

$data = json_decode(file_get_contents('php://input'), true);

// Replace the database credentials with your own
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "thelivingroom";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// Insert data into the database
$stmt = $conn->prepare("INSERT INTO guests (gname, email, phone, ccn, expmonth, cvv, checkin_date, checkout_date, cartCost) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");

$stmt->bind_param("sssssssss", $data["gname"], $data["email"], $data["phone"], $data["ccn"], $data["expmonth"], $data["cvv"], $data["checkin_date"], $data["checkout_date"], $data["cartCost"]);

if ($stmt->execute()) {
  echo "Data inserted successfully";
} else {
  echo "Error inserting data: " . $conn->error;
}

$stmt->close();
$conn->close();
?>

Here is the code that submits the data. Even when I hard-code data into the gname column, I am still getting this error. I tried changing the sendData function multiple times but the issue persists. Any thoughts on how I can get this data sent up?

can I pass a 2D from one page to another using JavaScript?

I am new to javascript, and I am wondering if there are any ways to pass specific data when the user clicks on its item from the main page to the product page? – without using PHP or any other programming language other than Javascript.

I used sessionStorage but it dosen’t give me what I need.

For example, I want to pass the data when the user clicks on one of these items first pic
to this page
second page

Here is my code for the first page

/* start of fifth section codes*/
let bestDeals = 
[
  [
    "https://i.pinimg.com/564x/2e/e1/25/2ee125c44f55f9ba271eed224a410d33.jpg",
    "Men, Football kits",
    "Brazil 2022/23 Stadium Home",
    "199$",
    "250$",
  ],
  [
    "https://i.pinimg.com/564x/20/6f/d5/206fd5f2e097717eee5a8e0ae94030c6.jpg",
    "Men, Football kits",
    "Saudi Arabia 2022/23 Away Jersey",
    "110 $",
    "199 $",
  ],
  [
    "https://i.pinimg.com/564x/76/a8/79/76a879179757d3a9ad2c12bc24e7457a.jpg",
    "Men, Football kits",
    "Man City Football Kit",
    "90 $",
    "140 $",
  ],
  [
    "https://i.pinimg.com/564x/b5/15/ad/b515ad05493a2a3686f10d6d82cf6910.jpg",
    "Men, Football kits",
    "Real Madrid 19/20 Home Kit",
    "200 $",
    "300 $",
  ],
  [
    "https://i.pinimg.com/564x/35/06/5d/35065d3b1a55c8dd0ff604849ff4a6df.jpg",
    "Men, Football kits",
    "Real Madrid 19/20 Away Kit",
    "199 $",
    "250 $",
  ],

]

let fifthContainer = document.getElementById("fifth-section-container");

bestDeals.forEach(deal =>{
  fifthContainer.innerHTML = fifthContainer.innerHTML + 
  `
  <div id="fifth-section-card" class="fifth-section-card" >

  <div class="product-details">

      <img id="product-img" src="${deal[0]}" alt="">

      <span id="product-listing">
          ${deal[1]}
      </span>
     
      <h4 id="product-name" > ${deal[2]}</h4>
      <br>
      <div class="price-div">
          <div class="price-content">
              <span id="product-price scale-card">${deal[3]}</span>
              <span id="product-discount">${deal[4]}</span>
          </div>
          <div class="price-icons" >
              <i class="fa-regular fa-heart scale-card" style="color: black;"></i>
              <i class="fa fa-shopping-bag scale-card" style="color:black;"></i>
          </div>
      </div>
  </div>

  </div>
  `
})
let fifthCard = document.getElementsByClassName("fifth-section-card");
let isClicked = true;

document.querySelectorAll(".fifth-section-container .fifth-section-card").forEach(item =>{
  
  item.onclick = () =>{

    sessionStorage.setItem('img', bestDeals[item])
    window.open("productInfo.html" ,"_self") 
  }
})

I don’t have any codes in the second page as of right now.

How to Change attribute name in react js with map

I have a code like this
I want to change the attribute name starting with <all.

{services.map((item) => (
        <div className="space-x-[8px] py-[8px] flex ">
        <div className="flex flex-col text-center relative px-[8px] py-[8px] items-center active:bg-[#f5f5f5]  cursor-pointer">
          <All.${item}
            sx={{ fontSize: "40px" }}
            className="text-[#6B84DD] w-[64px] h-[p64x] text-3xl"
          />
          <span className=" font-merrisans text-[14px] font-semibold">
            {item}
          </span>
        </div>
      </div>
      ))}

I tried like this

{services.map((item) => (
        <div className="space-x-[8px] py-[8px] flex ">
        <div className="flex flex-col text-center relative px-[8px] py-[8px] items-center active:bg-[#f5f5f5]  cursor-pointer">
          {(`{<All.${item}
            sx={{ fontSize: "40px" }}
            className="text-[#6B84DD] w-[64px] h-[p64x] text-3xl"
          />`)}
          <span className=" font-merrisans text-[14px] font-semibold">
            {item}
          </span>
        </div>
      </div>
      ))}

but it didn’t worked
it showing

how to insert background images in nuxt generate

I’m sorry if it’s obvious

I’m creating several thousand pages using nuxt generate like this

<template>
    <div>
        <div class="main-picture">
           <span>{{landing.name}}<span>
        </div>
    </div>
<template>
<script>
import { landingshs } from '~/db/landingshs'
export default {
    data() {
        return {
            link: "https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_November_2010-1a.jpg"
        }
    },
    asyncData({ params }) {
    const landing = landingshs.find(l => l.id === params.id)
    
    return {landing}

 },

</script>

now I’m trying to set a picture like this

<style>
.main-picture {
    width: 1000px;
    height: 1000px;
    background-image: v-bind("`url(${link})`");
}
</style>

I also tried to do it this way but without success

 mounted() {
  setTimeout(() =>{
    document.querySelector('.main-picture').style.backgroundImage = "url(" + this.link + ")";
      }, 5000);
     
    },

When creating a regular page (not _id.vue) everything works fine

nuxt generate itself works well, inserts the necessary data

The loop in this code seems to not incrementing, and not entering ajax

if (typeof(EventSource) !== "undefined") {
  var evntid = document.getElementById('evntid').value;
  var source = new EventSource("collectdataDirect.php?evid=" + evntid); // this code shud check all the existing files inside the event folder and create one line each of data to be sent in proper format
  //var source = new EventSource("data.txt"); 
  source.onmessage = function(event) {
    if (str !== event.data) {
      str = event.data;

      var att = str.split('|&|');
      alert(JSON.stringify(att.length));
      let i = 0;
      var table = "<table> <th>Attendee ID</th> <th>Attendee Name</th> <th>Attendee Type</th> <th>Position</th> <th>Company</th> <th>Client ID</th>";
      while (i < att.length) {
        alert(JSON.stringify(i));
        var details = att[i].split('||');
        alert(JSON.stringify(details));
        table = table + "<tr><td>" + details[0] + "</td>" + "<td>" + details[1] + "</td>" + "<td>" + details[2] + "</td>" + "<td>" + details[3] + "</td>" + "<td>" + details[4] + "</td>" + "<td>" + details[5] + "</td></tr>";
        document.getElementById("result").innerHTML = table + "</table>";
        i++;
        $.ajax({
          type: "GET",
          data: {
            ' attid': details[0],
            'attname': details[1],
            'atttype': details[2],
            'position': details[3],
            'company': details[4],
            'client_id': details[5]
          },
          url: "http://127.0.0.1:500/printonsite/printDirectCert.php",
          cache: false,
          dataType: "text",
          success: function(data) {
            alert("All ok" + data);
          },
          error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("error===" + XMLHttpRequest.responseText);
            //alert("status====="+textStatus);
          }
        });
      }
      document.getElementById("result").innerHTML = table + "</table>";

      //alert(audiogreeting);
    };
  }
}

Was trying to display the data as a table bt the loop is not working as expected, what could be the problem?

Using promise all to fetch multiple APIs and then assigning API responses to variables using useState

const[api1, setAp1] = useState({});
const[api2, setAp2] = useState({})
const[api3, setAp3] = useState({})
const[api4, setAp4] = useState([])
const[api5, setAp5] = useState([])

useEffect(() => {
 let Ap1 = fetch('url1')
 let Ap2 = fetch('url2')
 let Ap3 = fetch('url3')
 let Ap4 = fetch('url4')
 let Ap5 = fetch('url5')
 let Ap6 = fetch('url6')
 let Ap7 = fetch('url7')
 Promise.all([Ap1, Ap2, Ap3, Ap4, Ap5, Ap6, Ap7])
 .then((data) => {
   setAp5(Ap4)
}   


return(
api5.length>0 && api5.map((data)=>{
<div>{data.value}</div>
})
)  

the above code is an example. I am using promise all to resolve the fetch. The problem I am facing is sometimes it is showing list but some time doesn’t. I also to check the response in Network it fetches the data but doesn’t assign in api5 useState variable

How to make liking a button that is linked to a database via http req fast

So on the inital load , the app request all the data from a database using next.js serverside props,and then pass the upvotes in a state.
const [localeUpvotes,setLocaleUpvotes] = useState(upvotes)

And on the front end i display the number of upvotes on a button.

when the user clicks on the upvote button , the app PATCH the changes to my datbase, and then retreives the data right after using a GET request and re-pass that data to the react State.

    async function onUpvoteHandler(e){
        e.stopPropagation()

        // post data in database
        const JSONresultPATCH = await fetch('/api/post_upvotes',{
            method:"PATCH",
            body:JSON.stringify({
                action:!didUserUpvote,
                from:auth,
                feedbackId:_id,
            }),
            headers:{
                'Content-Type':'application/json',
            }
        })
        const resultPATCH = await JSONresultPATCH.json()

        //get data from database
        const JSONresultGET = await fetch(`/api/get_upvotes/${_id}`)
        const resultGET = await JSONresultGET.json()
        setLocaleUpvotes(resultGET.upvotes)
    }

And the problem is the time between when the user clicks on the upvote button and the time the frontend gets updated is pretty long ,about 1s ,so it’s bad UX.

Now how can i make this faster ?

here is the link to my live app to see the slowness , it won’t work if you are not sign in !

returnTo behavior error. Url gets removed right before the post request

I am using express session and I have a middleware that sets the req.session.returnTo to the orginalUrl.

router.post(
  '/login',
  passport.authenticate('local', {
    failureFlash: true,
    failureRedirect: '/login',
  }),
  (req, res) => {
    const redirectUrl = req.session.returnTo || '/home';
    delete req.session.returnTo;
    res.redirect(redirectUrl);
  }
);

This is my code that redirects to the originalUrl if there is. I logged the whole session and the url is there under returnTo but gets removed right before this post request.

I tried removing the delete req.session.returnTo and it still doesnt work. It is there when the app makes a get request to /login but gets removed right before /post and then it always redirects to /home.

how to trigger a form’s onChange event if the value of an input / select is being changed programaticaly

As the title indicates, i’m looking for a way for the form onChange event to be triggered without user direct interference. This has more to do with Javascript itself but i’m using React to exemplify what i’m looking for:

I have a custom component DropDown:

function DropDown() {
  const [selectedPerson, setSelectedPerson] = useState(people[0])
  const selectRef = useRef()

  useEffect(() => {
    selectRef.current.value = selectedPerson.id
  }, [selectedPerson])

  return (
    <>
      <Listbox value={selectedPerson} onChange={setSelectedPerson}>
        {({ open, disabled, value }) => {
          console.log()
          return (
            <div>
              <Listbox.Button as="div">
                <span>{selectedPerson.name}</span>
              </Listbox.Button>
              <Listbox.Options static style={{ display: open ? 'block' : 'none' }}>
                {people.map(person => (
                  <Listbox.Option key={person.id} value={person} disabled={person.unavailable}>
                    {person.name}
                  </Listbox.Option>
                ))}
              </Listbox.Options>
            </div>
          )
        }}
      </Listbox>
      <div>
        <select ref={selectRef} name="test" id="">
          {people.map(person => (
            <option key={person.id} value={person.id}>
              {person.name}
            </option>
          ))}
        </select>
      </div>
    </>
  )
}

the “pure” is going to be hidden, it’s just there so i can try and trigger my onChange event of the form that surrounds the component

import DropDown from './DropDown'
import './App.css'

function App() {
  const onChange = ev => {
    console.log(ev)
  }
  return (
    <div className="App">
      <form onChange={onChange}>
        <DropDown />
      </form>
    </div>
  )
}

export default App

As you can see, in my useEffect, i successfully change the selected value of my component but i want it to trigger the onChange event on the form, same way as it happens when i change the option directly in the Select.

Is there a way for this to happen?

how to hide/show elements

i have multiple divs i conviently id’d as “start”, “a”, “b”, “c”, ect. On page load i would like to show only the div id’d as “start”. On the press of a button, i’d like to show only the div id’d as “a”, and repeadtly continue through all the letters of the alphabet. heres the code i have so far.

<div id="start">
Lets Begin<br />
<button id="startbutton">Start</button>
</div>

<div id="a">
<img onclick="play('sounds/apple.mp3')" src="images/apple.png" width="400" height="400" /><br />
<button onclick="play('sounds/correct1.mp3')" class="multiple-choice">Apple</button>
<button onclick="play('sounds/wrong1.mp3')" class="multiple-choice">Slinky</button>
<button onclick="play('sounds/wrong1.mp3')" class="multiple-choice">Orange</button>
</div>

<div id="b">
<img onclick="" src="images/banana.png" width="400" height="400" /><br />
<button onclick="" class="multiple-choice">Monkey</button>
<button onclick="" class="multiple-choice">Banana</button>
<button onclick="" class="multiple-choice">Yellow</button>
</div>

im aware i should use addeventlistners rather than onclicks, but lets work with onclicks for now.

im quite new to javascript but have plenty of php experience. so i thought about switches with display:none, display:block styling. But i just cant peice it together.

Issues migrating gatsby-starter-texblog to Gatsby v4 with gatsby-plugin-mdx

I’m currently trying to update my blog site, which is based on the gatsby-starter-texblog template, to work with the latest version of GatsbyJS. To do so, I’ve been following the instructions in the gatsby-plugin-mdx documentation, specifically the section about migrating from v3 to v4.

Here’s what I’ve done so far:

  1. Removed the defaultLayouts option from gatsby-config.js and moved the gatsbyremark plugins and the remark plugins to the correct places
  2. Modified gatsby-node.js to include ?__contentFilePath=
  3. Updated my postpage.tsx file to accept children as input and replaced the MDX renderer with {children}

However, I keep running into errors when I try to run gatsby develop. Specifically, my blog posts are not being parsed as MDX, but as JavaScript directly. Here’s an example of the error message:

ERROR #gatsby-plugin-mdx_10001  PLUGIN

Failed to compile the file
"/home/faberf/Documents/fynns-blog/content/posts/hello-world.mdx". Original
error message:

Expected usable value, not `undefined`


 ERROR 

Module build failed (from ./node_modules/gatsby/dist/utils/babel-loader.js):
SyntaxError: /home/faberf/Documents/fynns-blog/content/posts/hello-world.mdx:
Invalid left-hand side in prefix operation. (1:2)

> 1 | ---
    |   ^
  2 | title: Hello World
  3 | date: "2023-03-17"
  4 | description: "In this blog, I will be sharing insights into my various 
computer science projects. 
    at instantiate (/home/faberf/Documents/fynns-blog/node_modules/@babel/parser
/src/parse-error/credentials.ts:62:21)

Here are my dependencies:

    "@mdx-js/mdx": "^2.3.0",
    "@mdx-js/react": "^2.3.0",
    "@sindresorhus/slugify": "^2.2.0",
    "gatsby": "^4.0.0",
    "gatsby-cli": "^4.0.0",
    "gatsby-image": "^3.11.0",
    "gatsby-plugin-google-analytics": "^4.0.0",
    "gatsby-plugin-manifest": "^4.0.0",
    "gatsby-plugin-mdx": "^4.0.0",
    "gatsby-plugin-offline": "^5.0.0",
    "gatsby-plugin-react-helmet": "^5.0.0",
    "gatsby-plugin-sass": "^5.0.0",
    "gatsby-plugin-sharp": "^4.0.0",
    "gatsby-plugin-typescript": "^4.0.0",
    "gatsby-remark-katex": "^6.0.0",
    "gatsby-source-filesystem": "^4.0.0",
    "gatsby-source-thirdparty": "^1.0.6",
    "gatsby-transformer-remark": "^5.0.0",
    "gatsby-transformer-sharp": "^4.0.0",
    "he": "^1.2.0",
    "katex": "^0.13.0",
    "node-sass": "^8.0.0",
    "package.json": "^2.0.1",
    "prism-react-renderer": "^1.3.5",
    "prop-types": "^15.8.1",
    "react": "^16.0.0",
    "react-burger-menu": "^3.0.9",
    "react-dom": "^16.0.0",
    "react-helmet": "^6.1.0",
    "react-icons": "^4.8.0",
    "rehype-katex": "^6.0.2",
    "remark-math": "^5.1.1",
    "typescript": "^5.0.2"

I’ve followed the migration guide in the gatsby-plugin-mdx documentation, but it doesn’t seem to be working for me. Any ideas on what could be causing these errors and how to fix them? Thank you in advance!

Unexpected token ‘)’ While Trying To Dynamically Display Button On WordPress Page

I’m building a WordPress blog. I faced an issue so I wrote below JavaScript code just so I can hide the element according to the text it has. If element don’t have any text, It should be hidden. If it has text, it should be visible (which it is already).

For better understanding, please look at the HTML of the problem here.

function btnHidingWordPress(){

// targets spans containing text
let CalendarPrevBtn = document.getElementsByClassName('wp-calendar-nav-prev');
let CalendarNextBtn = document.getElementsByClassName('wp-calendar-nav-next');

// stores spans text
let PrevBtnText = CalendarPrevBtn[0].textContent;
let NextBtnText = CalendarNextBtn[0].textContent;

// deciding if btn needs to be hidden
Array.from(CalendarPrevBtn).forEach((x) => {
if (PrevBtnText == ' ') {    
    CalendarPrevBtn.style.display ="none";
}
    else {
    CalendarPrevBtn.style.display ="block";
    })

Array.from(CalendarNextBtn).forEach((x) => {
if (NextBtnText == ' ') {    
    CalendarNextBtn.style.display ="none";
}
    else {
    CalendarNextBtn.style.display ="block";
    
    })
}

btnHidingWordPress();

Whenever I run this code, instead of hiding the element (span in my case) it throws a console error saying:

Uncaught SyntaxError: Unexpected token ')'

At this point, i don’t even know what am I doing. I just want to make button hide if it does not contain any string. That’s it.

Regards,

I tried to look into different sources and all pointed that i need to loop CalendarPrevBtn via forEach because getElementByClasssName returns an array (Which is true). So, i don’t know too much theory and it somehow solved other bugs which obviously I didn’t either. Now, I am stuck here. What can be done.

How to fix : “Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.”?

I’m trying to get a doc from my database with the slug value found in the url which i compare with the ones in the database. Once I found that doc I want to convert its data to json format but im getting this error :

Error: Error serializing .post returned from getStaticProps in “/[username]/[slug]”.
Reason: undefined cannot be serialized as JSON. Please use null or omit this value.

I’m not sure what the issue is here so if someone has an idea of how to fix the issue, a quick explanation of why im getting the issue would be helpful.

Here is my code on my [slug].js file:

import styles from '../../styles/Post.module.css';
import PostContent from '../../components/PostContent';
import { firestore, getUserWithUsername, postToJSON } from '../../lib/firebase';
import { useDocumentData } from 'react-firebase-hooks/firestore';
import { getDocs, getDoc, query, collection, limit, where } from 'firebase/firestore'

export async function getStaticProps(context) {
  const username = context.params.username;
  const slug = context.params.slug;
  const userDoc = await getUserWithUsername(username);
  console.log(slug);

  let post;
  let path;

  if (userDoc) {
    const postRefQuery = query(
      collection(firestore, 'posts'),
      limit(1),
      where('slug', "==", slug)
    );
    const postRef = (await getDocs(postRefQuery)).docs[0];
    const post = await postToJSON(postRef);
    path = post.path;
  }

  return {
    props: { post, path },
    revalidate: 5000,
  };
}

export async function getStaticPaths() {
  const snapshot = await getDocs(collection(firestore, 'posts'));

  const paths = snapshot.docs.map((doc) => {
    const { slug, username } = doc.data();
    return {
      params : { slug, username },
    };
  });

  return {
    paths,
    fallback: 'blocking',
  };
}

export default function Post(props) {

  return (
    <main>

    </main>
  );
}

Here is my code on my firebase.js file where I run the postToJSON function :

export function postToJSON(doc) {
  const data = doc.data();
  return {
    ...data,
    // Gotcha! firestore timestamp NOT serializable to JSON. Must convert to milliseconds
    createdAt: data?.createdAt.toMillis() || 0,
    updatedAt: data?.updatedAt.toMillis() || 0,
  };
}

Is there a way to to use each value of an array as a function parameter and then store each result in another array or object?

so i have a function that returns array of matchIds. And i have a function that returns object of data from the macth based on the matchID

async function getMatchData(matchId){
    const response = await fetch(`https://europe.api.riotgames.com/lol/match/v5/matches/${matchId}?api_key=`+key);
    var data = await response.json();
    let matchData= {
        teams: data.info.teams.map(element => team = { teamid: element.teamId, win: element.win }),
        players: data.info.participants.map(element => obj = { team: element.teamId, champ: element.championName, champIcon: element.championName + '_0.jpg', summoner: element.summonerName, level: element.champLevel, build: { item1: element.item1, item2: element.item2, item3: element.item3, item4: element.item4, item5: element.item5, item6: element.item6, item0: element.item0 }, kills: element.kills, deaths: element.deaths, assists: element.assists, kda: (element.kills + element.assists) / element.deaths, cs: element.totalMinionsKilled + element.neutralMinionsKilled, victory: element.win })
    }
   return matchData

now i want to use each matchId from the matchIds array as a parameter in the getMatchData function and put each response in an array or object

i tried to run thru the array with map but it says map is not a function

let matchHistoryData= matches.map(element=>getMatchData(element))
     console.log(matchHistoryData);  

matches being the array of matchIds