PHP add unique Id to SQL - php

I'm working on a small project for my English teacher, and it's my first time doing anything with databases. I have a table called Books, with four columns: Id, Title, Link, and Rating. The idea is that a user could submit the title of a book they recently read, a link to it on goodreads, and a rating out of 5 stars. (I don't have any input validating yet, but I'm going to add that after I finish up with my current problem.)
The problem happens in the Id column. I'm trying, with PHP and SQL, to grab the largest Id in the entire table, and then set the Id of the newly added book (row) to be one more than the old largest.
Here's my HTML:
<form action="bookSubmit.php" method="post">
Book Title: <input type="text" name="title"><br>
Goodreads Link: <input type="text" name="link"><br>
Rating (1 to 5): <input type="number" name="rating" min="1" max="5"><br>
<input type="submit" value="submit">
</form>
and bookSubmit.php:
<?php
$servername = "localhost";
$username = "[My username]";
$password = "[My password]";
$dbname = "PullJosh_books";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$newId = $conn->query("SELECT MAX(Id) FROM Books"); // Replacing this line with $newId = and then manually typing in the current highest Id works (meaning everything else is all set).
$newId++;
$sql = "INSERT INTO Books (Id, Title, Link, Rating)
VALUES ('". $newId ."', '" . $_POST['title'] . "', '" . $_POST['link'] . "', '" . $_POST['rating'] . "')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When I run SELECT MAX(Id) FROM Books in the phpmyadmin sql tab, I get 2, which is correct.
If you happen to notice any security issues (besides not validating the input), please let me know about that as well.

You need not to first find the largest number in the table and then add one number to it and then submit. In your data table in mysql turn id into primary key and make it auto increment true that will always insert a unique and increased id.
syntax for the same
ALTER TABLE tbl_name ADD id INT PRIMARY KEY AUTO_INCREMENT;

Related

Insert into SQL database user input from HTML form

I am trying to insert into column "UserId" in my sql database, using php, text that the user inputs in the HTML form.
Below is a basic example to help me figure out what I am doing wrong.
HTML
<html>
<form action="index1.php" method ="post" name="trial">
<input type="text" name="testName" id="testId">
<br>
<input type="submit" value="Submit">
</form>
</html>
PHP
$servername = "localhost";
$username = "root";
$password = "xx";
$dbname = "wp";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$UserId = $_POST['testName'];
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$testName')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Some notes:
I can connect to database and insert in the correct columns checkbox and radio values from the form
I cannot find a way to insert in the database the user text input from the form (UserProfile is the table and UserId the column).
Would using a javascript variable, like below one, help?
var testVar = document.getElementById("testId").value;
I know I am opening myself to hacking using the above code, I would like to improve it later on but I think I need to first figure out the basics (ie: how to get the user text input added to the database)
Than you in advance for any help!
you are storing the value in $UserId, not in $testName:
Change your SQL Query to
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$UserId')";
I think this will help.
BTW: Think about SQL-Injection! Look here: How can I prevent SQL injection in PHP?
Look here
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$testName')";
Change $testName to $UserId in sql statement because it's the name of your new variable in php:
$UserId = $_POST['testName'];
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$UserId')";
But I advice you to:
1- use PDO for any sql handling in php
2- use mysqli_real_escape_string to protect your code from threats.
make it like:
$UserId = mysqli_real_escape_string($con, $_POST['testName']);

How to write multiple insert in multiple tables using the same form PHP

I have a problem with inserting data into two different tables: When a new member is created, it will be insert into member and grade tables after getting the id course from course table. I used INSERT for both of them at the same time with a multi query function but it doesn't work.
Can you help me please?
The form:
<form>
<input type="text" name='m_fName'>
<input type="text" name='m_lName'>
<input type="text" name ='m_nId'>
</form>
Php
$id = $re['c_id']; //to get id of course that I want to insert
$sql="INSERT INTO member (m_fName, m_lName, m_nId)
VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');
INSERT INTO grade(c_id,m_nId)
VALUES( '$id','$_POST[m_nId]')";
mysqli_multi_query($conn,$sql);
$id = $re['c_id'];
$sql="INSERT INTO member (m_fName, m_lName, m_nId) VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');";
$sql .="INSERT INTO grade(c_id,m_nId) VALUES( '$id','$_POST[m_nId]')";
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Hope this will help. but try to first validate the posted data. check if isset .you did not show in the are you using post and the page you are posting your data
Answer above is the correct one, alternative way is the code below
$id = $re['c_id']; //to get id of course that I want to insert
$sql="INSERT INTO member (m_fName, m_lName, m_nId) VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');";
$act = mysqli_query($conn,$sql);
if($act) {
$sql2 = "INSERT INTO grade(c_id,m_nId)
VALUES( '$id','$_POST[m_nId]')";
$act2 = mysqli_query($conn,$sql2);
}

Update values in a row if there is a same name in a column (with PHP in MySQL)

I have a database with three columns: ID, userName, feedback
I want the feedback value to be updated when the userName is same.
my php code:
<?php
conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['name'];
$value2 = $_POST['message'];
$sql = "INSERT INTO js (userName, feedback) VALUES('$value', '$value2');
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
};
$conn->close();
?>
If you want to do it with mysql you first of should define a unique index on the userNamecolumn.
ALTER TABLE js
ADD CONSTRAINT u_userName UNIQUE (userName)
The edit your insert query like this:
INSERT INTO js (userName, feedback) VALUES ('$value', '$value2')
ON DUPLICATE KEY UPDATE feedback=VALUES(feedback);
Now if the duplicate key violation is hit by mysql, the value for feedback will be updated while inside the row where your username equals.
Or you implement a update logic inside php and detect if there already is an entry inside the table with the same username.

PHP Can't enter data into database table

I am trying to enter the data that I get from the two variables stuname and book in the table's username and book columns !! I only want to enter data into those two columns since the id column is auto increment and the date is auto updated with time stamp!!! Each time I run my code I enter my data into the two text fields and when I press submit I get this message!!
Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\assignment.php on line 35
Warning: mysqli_query() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\assignment.php on line 36
Here is my Code:
<?php
$servername = "localhost";
$Username = "root";
$Password = "admin";
$Dbname = "nfc";
$conn = mysqli_connect($servername, $Username, $Password, $Dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "Connected successfully";
if(isset($_POST["stuname"])&&($_POST["book"]))
{
$stuname = $_POST["stuname"];
$book =$_POST["bookname"];
$sql = "INSERT INTO library (id, username, book, date)
VALUES ('', '$stuname', '$book','')";
mysqli_select_db($conn, 'nfc') or die(mysqli_error($con));
$retval = mysqli_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
else
{
echo "Success";
}
echo " to stuname ". $stuname;
echo " to book ". $book;
}
?>
<form id="form1" name="form1" method="post" action="#">
<p>
<label for="1">student name</label>
<input type="text" name="stuname" id="1" />
</p>
<p>
<label for="12">book name</label>
<input type="text" name="bookname" id="12" />
</p>
<input name="submit" type="submit" value="Submit" />
</form>
In the mysqli_query you should put the conn first and then the query itself
$retval = mysqli_query( $conn, $sql );
The first problem was solved by #Ghost in the comments.
Now on to the rest of the problems:
1. Your database design is faulty
This should have failed immediately because you are inserting an empty value for id. id should be a primary key and therefore should be unique. An auto-increment doesn't work if you insert an empty value.
2. Your insert statement is faulty
You should exclude an auto-increment column in the INSERT statement and should not use an empty value for date. If date is a timestamp, you should either use NULL if the time is supposed to be empty or use NOW() to use the current timestamp.
3. You shouldn't be using insert on this page according to your comments.
You should be using UPDATE or REPLACE instead of INSERT if you are trying to update the existing row but you should be using the primary key to signify which row you are replacing. Right now, it looks like you don't have a primary key, so refer to my 1st point.
4. Security concerns: Your query is subject to SQL injections.
You use user input ($_POST) directly in a query. Any malicious user can take advantage of this and extract, delete, or manipulate data in your database. You should be using prepared statements, or at the very least escape functions.

Copy value to another table

I have a problem with my code. I have a table called "users" with an "id" field.I want to copy the id value to another table called "aircondition" . This is the code that inserts values into the aircondition table .The problem is that when I use this code I get 0 in the new id field instead of the user.id
<?php
$con=mysqli_connect("localhost","george","george123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$acname = mysqli_real_escape_string($con, $_POST['ACName']);
$btu = mysqli_real_escape_string($con, $_POST['BTU']);
$space = mysqli_real_escape_string($con, $_POST['Space']);
$energyclass = mysqli_real_escape_string($con, $_POST['EnergyClass']);
$sql="INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
VALUES ('SELECT id
FROM users', '$acname', '$btu', '$space', '$energyclass')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
header('location:aircondition.php');
mysqli_close($con);
?>
Use this query
INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
SELECT id, '$acname', '$btu', '$space', '$energyclass'
FROM users

Categories