Next.js Discord

Discord Forum

Need help using variables inside mysql query to insert data in to database

Answered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
const [fullname, setFullname] = useState('') const [id, setId] = useState('') function AddMember() { try { sql_query( "INSERT INTO members (id, Fullname) VALUES (?, ?)", [ id, fullname ] ); } catch (error) { throw Error(error.message) } }

<input onChange={e => setId(e.target.value)} id="id" type="number" placeholder="ID Card Number"></input> <input onChange={e => setFullname(e.target.value)} id="fullname" name='fullname' type="text" placeholder="Fullname"></input>

<button onClick={AddMember()} type="submit">Add Member</button>

This is the relevant code I believe. My issue is that this inserts nulls into my database. I'm very new to nextjs so any and all help would be appreciated.
Answered by fuma
1. Why are you doing the database query at the client side?
2. The value onClick is wrong, it should be () => addMember() instead of addMember()
3. Inputs are not controlled, you need to pass the value prop
View full answer

39 Replies

1. Why are you doing the database query at the client side?
2. The value onClick is wrong, it should be () => addMember() instead of addMember()
3. Inputs are not controlled, you need to pass the value prop
Answer
@fuma 1. Why are you doing the database query at the client side? 2. The value `onClick` is wrong, it should be `() => addMember()` instead of `addMember()` 3. Inputs are not controlled, you need to pass the `value` prop
Giant pandaOP
I'm clueless to be completely honest. I picked up nextjs just a month ago to work on a college project. And just learning still. So I don't know the correct way to do a lot of things.

1) I'm unsure how to run query on server side or when to.
2) I don't understand how you want me to add that part to my code..
3) I don't understand
Giant pandaOP
sharing the db.js file where connection is made.

import mysql from 'serverless-mysql' export const db = mysql({ config: { host: process.env.MYSQL_HOST, database: process.env.MYSQL_DATABASE, user: process.env.MYSQL_USERNAME, password: process.env.MYSQL_PASSWORD, // multipleStatements: true } }) export async function sql_query(query_string, values = []) { try { const results = await db.query(query_string, values) await db.end() return results } catch (error) { } }
These are some common nouns in React.js, as a web dev, I would recommend you learning React.js first before touching frameworks like Next.js. When working in Next.js projects, you’ll likely think in the perspective of both client side and server side. In your case:
- Can you connect database from client side?
- No, if the users can do any database queries, everyone can hack into your database
- Instead, create an route handler (API endpoint), and invoke it from client
Only do database queries in the server side
Giant pandaOP
I was recommended to use nextjs for my project by my friend. I am doing my best to integrate the backend by myself. I have done just a bit of php and js with html before. Other than that, I don't have a lot of experience.

So what I've done is completely client side manipulation of database? Any document I can read to learn how to create a route handler? I have made a lot of progress using nextjs on my project. Though I'm sure it's not optimal. Backend is very complicated as of now.
Make a fetch request to that route that you make
Giant pandaOP
😅 Honestly feel lost reading the docs file..
Yep, thanks for heydoon. :love:
Actually most of the questions can be answered by the docs.
anyway back to the topic, your onClick prop in the submit button is wrong, you should pass a lambda instead of invoking addMember directly
Philippine Crocodile
Check this project I made to test out app router.
https://github.com/haydencarlson/todos-next-13

You can see how I made my API routes
https://github.com/haydencarlson/todos-next-13/tree/main/app/api
In my opinion, I think you’re missing some important concept. I can see many common mistakes in your code, and as I suggested, learning Next.js seems to be too fast for you.

I don’t know what have you learned so far, and I’m neither a good teacher. Try taking it step by step, getting started with some simple React.js apps and learn the concepts. The logic of re-render, lifecycles, components, hooks, and some built-in utilities. Next.js is built on the top of React.js, without deeper understanding of it you will quickly feel depressed by the difficulty of learning Next.js
Giant pandaOP
I see. Understandable. Is react js simpler to get started with? Do I have to restart my project from scratch? Or can I reuse the frontend code that I wrote? I have just by the end of the year to finish my project and I'm just trying to learn using the internet as best as I can.
Don’t reuse, create some other projects, like a simple todo app. I mean it’s a chance to get deeper into React.js. It’s August now and you have a whole month to train yourself before starting to work on the project.

React is a JavaScript library with powerful ecosystem, Next.js is a large framework. I believe you can take it easily within two months
So here’s my simple roadmap:
React + Vite (A tool to run react apps) -> Next.js basics
Learn the concept of React Server Components, and start exploring different features of Next.js.
And of course feel free to ask here :meow_party:
@fuma And of course feel free to ask here <a:meow_party:763131349698609173>
Giant pandaOP
Would it be not ideal if I started working on my project and learn as I go along?
It’s fine, above are my suggestions but it still depends on you since my learning method doesn’t suit everyone
Wow, 20 messages a minute
Well, my bad
@fuma It’s fine, above are my suggestions but it still depends on you since my learning method doesn’t suit everyone
Giant pandaOP
Alright. I'll talk with my supervisor about how well the backend integration should be done and get back to you. Because it's a degree level project.
Giant pandaOP
Okay. So, can anyone explain simply why when i use the variables inside the sql query, it doesn't store anything in the database?
"variables" doesn't exist in SQL, it's a parameterized query, the question mark is a placeholder.
So of course, it won't store anything into your database except what you have done with the query (Like insert statement)
Giant pandaOP
So what would I need to do to store data from textbox into database table?
Don’t know you are referring to, you can use an INSERT statement to insert a new row into the table
Read the tutorials/docs of your database if you wanna know the usage
Then how do you handle the submit event? Are you using server actions, library like react-hook-form, or just controlled inputs with useState?
Giant pandaOP
Just controlled inputs. Its just a simple add to table form.
Normally you will make database queries on the server side, so create a POST route handler, and receive inputs from the request body.
After that, you can make a POST request from client side
Giant pandaOP
And if i were to make queries on the client side?
Impossible unless you want everyone to hack into your database
Giant pandaOP
Isee. I am using phpmyadmin as server and with dummy data. And its not a program I would be publishing to the market.
No, never do that since it can be a dangerous security risk
Giant pandaOP
@fuma Hi. It's been almost a month and a half since I asked this question. Just wanted to give an update. I thought I'd take a look at this thread to see if I understand it now.

I have been working on my project in next js still. And now I understand everything you were talking about.

I ended up using php with next js. I learned to use axios and make get, post and put requests.

Two weeks ago I finished all functionalities for the web app. This week I got the mobile app functional and running. It's far from perfect and finished.

Anyways, just wanted to let you know since this was the first thread I created after starting to learn next js.
Sounds nice!