How to solve this i don't add data using by $_Post Method, but without $_POST method showing undefine variable?
if (isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['age'])){
//Getting values
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$age = $_POST['age'];
//Creating an sql query
$sql = "INSERT INTO info (firstname,lastname,age) VALUES ('$firstname','$lastname','$age')";
//Importing our db connection script
require_once('connect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Employee Added Successfully';
}else{
echo 'Could Not Add Employee';
}
//Closing the database
mysqli_close($con);
}
You need to define your variables to something if $_POST is not set.
So code would look something like this:
$firstname = isset($_POST['firstname']) ? $_POST['firstname'] ? "";
$lastname = isset($_POST['lastname']) ? $_POST['lastname'] : "";
$age = isset($_POST['age']) ? $_POST['age'] : "";
//if isset $_POST['age'] then assign it to $_POST['age'] else assign it to ""
if (isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['age'])){
//Creating an sql query
$sql = "INSERT INTO info (firstname,lastname,age) VALUES ('$firstname','$lastname','$age')";
//Importing our db connection script
require_once('connect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Employee Added Successfully';
}else{
echo 'Could Not Add Employee';
}
//Closing the database
mysqli_close($con);
}
Bonus:
You code can be easily injected. Use prepared statements to avoid this.
$sql = "INSERT INTO info (firstname,lastname,age) VALUES (?,?,?)"; // question marks are placeholders to bind values to
$stmt = $con->prepare($sql); // prepare query
$stmt->bind_param("sss", $firstname, $lastname, $age); // bind values to your query
if($stmt->execute()){ // if success
echo 'Employee Added Successfully';
}else{
echo 'Could Not Add Employee';
}
You can learn more about it here
Try changing this one:
$sql = "INSERT INTO info (firstname,lastname,age) VALUES ('$firstname','$lastname','$age')";
To this one:
$sql = "INSERT INTO info (firstname,lastname,age) VALUES ('".$firstname."','".$lastname."','."$age."')";
Related
I had created a database which named student with ID, name, mat_number, specialty, age, and gender, in a PHP application.
I do not want the name or mat_number be taken in more than once.
I have done the connection to my database in a different page and called it in the add student page.
This following codes is for a faculty database collection
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender))
{
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}
else{
echo "Error: Complete all records";
}
}
?>
I want to get an error message demanding for a change if the 2 fields already exist in the database.
first name to check in database if already exist the record.
if no record run sql insert command.
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
$sql = "SELECT * FROM `student` WHERE name = "'.$name.'" and UB_number = '".$matNo."'";
$conn->query($sql);
$cnt = $conn->rowCount();
if($cnt == 0){
$sql = "INSERT INTO `student`
(`name`, `UB_number`, `age`,`sex`, `specialty`)
VALUES
('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}else{
echo "Error: Complete all records";
}
}
If you would like to insert a new record to DB only if one doesn't exist which has the same name or mat_number then you first need to execute SELECT statement to see if it exists.
Using MySQLi:
<?php
include 'mysqli.php';
$conn = $mysqli;
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if ($name && $matNo && $age && $specialty && !$gender) {
$stmt = $conn->prepare('SELECT 1 FROM student WHERE name=? OR UB_number=?');
$stmt->bind_param('ss', $name, $matNo);
$stmt->execute();
$stmt->bind_result($exists);
$stmt->fetch();
if (!$exists) {
$stmt = $conn->prepare('INSERT INTO `student`(`name`, `UB_number`, `age`, `sex`, `specialty`) VALUES(?,?,?,?,?)');
$stmt->bind_param('sssss', $name, $matNo, $age, $gender, $specialty);
$stmt->execute();
exit(header("Location: index.php"));
} else {
echo 'A record with this name or material number already exists!';
}
} else {
echo "Error: Complete all records";
}
}
Using PDO:
<?php
include 'lib.php';
$conn = $pdo;
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if ($name && $matNo && $age && $specialty && !$gender) {
$stmt = $conn->prepare('SELECT 1 FROM student WHERE name=? OR UB_number=?');
$stmt->execute([$name, $matNo]);
$exists = $stmt->fetchColumn();
if (!$exists) {
$stmt = $conn->prepare('INSERT INTO `student`(`name`, `UB_number`, `age`, `sex`, `specialty`) VALUES(?,?,?,?,?)')
->execute([$name, $matNo, $age, $gender, $specialty]);
exit(header("Location: index.php"));
} else {
echo 'A record with this name or material number already exists!';
}
} else {
echo "Error: Complete all records";
}
}
hope this may be helpfull to you. In here I asume that you are not using any framework. But if you use a framework there are plenty of easy methods to do this.In here I have checked only name field. You should update code as you wants. Also it it better if you could validate your inputs before check. Like trim(). Thanks
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
//after user click the submit button
$sql_Select_Stundets = "SELECT * FROM student WHERE name = '$name' ";
// query the sql with db connection
$result_sql_Select_Stundets = mysqli_query($conn,$sql_Select_Stundets);
//Now check the row count to verify the output if there is any match
$rowcount=mysqli_num_rows($result);
//Now write insert inside if condition
if( $rowcount >0 ) {
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender)) {
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
bheader("Location: index.php");
}else{
echo "Error: Complete all records";
}
}else{
echo "<script>
alert('sorry this name is already available');
</script>";
}
}
?>
I started to learn PHP and I need your help because I'm trying to write on my MySQL database. The script seems fine (for me :D) and it doesn't give me errors. But when I submit the query the data doesn't appear inside my MySQL database. Could you help me, please?
This is my HTML/PHP code:
<?php
session_start();
$_SESSION['message'] = '';
//connection variables
$host = '127.0.0.1';
$user = 'root';
$password = 'MyPassword';
$database= 'test';
$port= '3306';
//create mysql connection
$mysqli = new mysqli($host, $user, $password,$database,$port);
if ($mysqli->connect_errno) {
printf("Connection failed: %s\n", $mysqli->connect_error);
die();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $mysqli->real_escape_string($_POST['name']);
$email = $mysqli->real_escape_string($_POST['email']);
if ($mysqli->query("INSERT INTO 'contatti' ('name', 'email') VALUES ('$name','$email')") == true) {
$_SESSION['message'] = "registration succesfull! Added $name to the database";
} else {
$_SESSION['message'] = "User can't be added to the database";
}
}
?>
<!DOCTYPE html>
<html>
<center>
<h1>Inputs</h1>
<form class="form" action="welcome.php" method="post" autocomplete="off">
<div class="alert alert-error"><?= $_SESSION['message'] ?></div>
<input type="text" name="name" placeholder="Insert your name" /> <br>
<input type="email" name="email" placeholder="Insert your email"/><br>
<input type="submit" name="submit" placeholder="Submit"/>
</form>
</center>
</html>
This is the database:
[Table structure]
[]1
[Database info]
Please use preapared statements and bind parameters instead: http://php.net/manual/en/mysqli-stmt.bind-param.php
You can also debug your mysql server response with error_list:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$stmt = $mysqli->prepare("INSERT INTO `contatti` (`name`, `email`) VALUES (?,?)");
$stmt->bind_param('ss', $name, $email);
if ($stmt->execute()) {
/* ... */
}
else {
$errors = $stmt->error_list;
/* ... */
}
}
You should use prepared statements for MYSQL and PHP, if possible, at least to protect yourself from SQL injection (SO Ref).
That said, when you read this line :
if ($mysqli->query("INSERT INTO 'contatti' ('name', 'email') VALUES ($name,$email)") == true)
You are concatening strings into your SQL query without quotes, and the query string look like (with $name = 'test', $email = 'test#test' :
INSERT INTO 'contatti' ('name', 'email') VALUES (test,test#test) : incorrect syntax
You must escape strings on SQL :
if ($mysqli->query("INSERT INTO 'contatti' ('name', 'email') VALUES ('$name', '$email' )") == true)
The resulting query should look like : INSERT INTO 'contatti' ('name', 'email') VALUES ('test','test#test')
Edit : please note that the table (contatti) and the fields name (name, email) are supposed to be surrounded by backticks, not single quotes (I cannot escape backticks in a quote), and variables $name and $email by single quotes
You have a syntax error in your query, try to change the INSERT query inside the if condition here:
if ($mysqli->query("INSERT INTO 'contatti' ('name', 'email') VALUES ('$name','$email')") == true) {
$_SESSION['message'] = "registration succesfull! Added $name to the database";
} else {
$_SESSION['message'] = "User can't be added to the database";
}
To be like this:
if ($mysqli->query("INSERT INTO contatti (name, email)
VALUES('$name', '$email')") == true) {
$_SESSION['message'] = "registration succesfull! Added $name to the database";
} else {
$_SESSION['message'] = "User can't be added to the database";
}
Here's a well known example how to prevent sqlinjection. There are two files like login.php and profile.php But it doesn't do anything with ether entering a correct login and pass or incorrect data. Doesn't echo about any case. SQL server goes by MAMP.
Here's the code:
<?php
$con = new mysqli("localhost", "root", "root", "phpsec");
if ($con->connect_error){
echo $con->connect_error;
}
if (isset($_POST["submit"])) {
$pre_stmt = $con->prepare("SELECT * FROM userinfo WHERE email = ? AND pass = ?");
$pre_stmt->bind_param("ss",$_POST["email"],$_POST["pass"]);
$pre_stmt->execute();
$result = $pre_stmt->get_result();
if($result->num_rows > 0){
$row = $result->fetch_assoc();
header("location:profile.php?email=".$row["email"]);
} else{
echo "login fail";
}
}
?>
and profile.php:
<?phpecho "Welcome ".$_GET["email"]; ?>
What and where did I do wrong?
you can prevent your page from sql injection using prepared statement in php
try this code in while performing sql statements.
<?php
// prepare and bind
$stmt = $conn->prepare("INSERT INTO example(firstname, lastname, email) VALUES (?, ?,
?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "parth";
$lastname = "gandhi";
$email = "gandhi#example.com";
$stmt->execute();
?>
here in bind_param method in first parameter s is stands for string. if you want to use integer there you can use "i" and for decimal "d".
thanks for reading my solution.
I am trying to insert form data into mysql database but it is not inserted into table and there is no error!
Here is my code
<?php
$con = mysqli_connect('localhost', 'root', '', 'register');
if (isset($_POST['submit'])) {
$shop = $_POST['shopname'];
$name = $_POST['name'];
$user = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$repassword = $_POST['repassword'];
$phone = $_POST['phone'];
$sql = "INSERT INTO registration (shop_name,name,username,email,password,repassword,phone) VALUES ('$shop','$name''$user','$email','$password','$repassword','$phone')";
if (mysqli_query($con, $sql)) {
echo "Signup Sucessfull";
} else {
echo mysqli_error();
}
}
?>
How can I resolve this problem?
Turns out you forgot to mention a comma after the name.
'$name''$user' // Missing comma in between
Also, it should be mysqli_error($con) instead of mysqli_error()
Try some debugging:
$sql = "INSERT INTO registration (shop_name,name,username,email,password,repassword,phone) VALUES ('".$shop."','".$name."', '".$user."','".$email."','".$password."','".$repassword."','".$phone."')";
mysqli_query($con, $sql) or die(mysqli_error($con));
You seems to miss "," between the insert values. This code will work fine.
<?php
$con = mysqli_connect('localhost', 'root', '', 'register');
if (isset($_POST['submit'])) {
$shop = $_POST['shopname'];
$name = $_POST['name'];
$user = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$repassword = $_POST['repassword'];
$phone = $_POST['phone'];
$sql = "INSERT INTO registration (shop_name,name,username,email,password,repassword,phone) VALUES ('".$shop."','".$name."','".$user."','".$email."','".$password."','".$repassword."','".$phone."')";
if (mysqli_query($con, $sql)) {
echo "Signup Sucessfull";
} else {
die(mysqli_error($con));
}
}
?>
Yes, As already #ObjectManipulator pointed your silly mistake
near '$name''$user'.
I will strongly recommend you to use mysqli_prepare to avoid SQL Injection.
<?php
$con = mysqli_connect('localhost', 'root', '', 'register');
if (isset($_POST['submit'])) {
$stmt = mysqli_prepare($con, "INSERT INTO registration (shop_name,name,username,email,password,repassword,phone) VALUES (?, ?, ?, ?,?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssssss',$_POST['shopname'],$_POST['name'],$_POST['username'],$_POST['email'],$_POST['password'],$_POST['repassword'],$_POST['phone']);
if (mysqli_stmt_execute($stmt)) {
echo "Signup Sucessfull";
} else {
echo mysqli_error($con);
}
}
?>
And, as #JonStirling suggested not to store password in plain text
and use any Password API to encrypt password.
There are many ways to encrypt your password. Use anyone of them. Right now, I illustrated with md5().
And, Why to store password and repassword in database table. While storing user data into database table, check there itself if password & repassword matches or not.
Just a suggestion. It's upto you to choose.
<?php
$con = mysqli_connect('localhost', 'root', '', 'register');
if (isset($_POST['submit'])) {
if(isset($_POST['password']) && isset($_POST['repassword']) && ($_POST['password'] == $_POST['repassword'])){
$stmt = mysqli_prepare($con, "INSERT INTO registration (shop_name,name,username,email,password,phone) VALUES (?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'ssssss',$_POST['shopname'],$_POST['name'],$_POST['username'],$_POST['email'],md5($_POST['password']),$_POST['phone']);
if (mysqli_stmt_execute($stmt)) {
echo "Signup Sucessfull";
} else {
echo mysqli_error();
}
} else {
echo "Password must match.";
}
}
?>
else {
echo mysqli_error($con);
}
Problem solved. You forgot the connection details $con for your MySQL error output. This will now correctly output your MySQL Syntax mistakes from your query.
Other Notes:
Use Prepared statements for MySQLi (link)
Use a proper Password hashing algorithm such as Password_hash. Do not use MD5 (it's too fast and has too many collisions) and NEVER store passwords as plaintext.
Use the various filter_Var on your POSTed variables to clean them and make sure you catch any invalid data (such as improper email addresses)
Put comma in your sql query as below
$sql = "INSERT INTO registration (shop_name,name,username,email,password,repassword,phone)VALUES
('$shop','$name','$user','$email','$password','$repassword','$phone')";
I am creating a database for employees, and I am applying the crud operation to it
The problem with the code is that I cannot insert data into the database from the fields, I also get this error:
do not access superglobal $_post array directly.
<?php
session_start();
include("configa.php");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$FirstName = filter_input(INPUT_POST, $_POST["FirstName"]);
$LastName = filter_input(INPUT_POST, $_POST["LastName"]);
// attempt insert query execution
$sql = "INSERT INTO employeeinfo (FirstName, LastName) VALUES ('$FirstName', '$LastName')";
if(mysqli_query($mysqli, $sql)){
echo "Records added successfully.";}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($mysqli);
}
// close connection
$sql = 'INSERT INTO `employeeinfo`(`FirstName`, `LastName`) ';
$sql = $sql . "VALUES (\"$FirstName\", \"$LastName\") ";
if ($mysqli->query($sql) === TRUE) {
echo "New record created successfully";
$_SESSION['completed'] = "YES";
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
header('Location: Employee.php');
}else
{
echo 'BYE BYE !!!';
}
mysqli_close($mysqli);
?>
So the filter_input() method in php accepts a third parameter specifying what it should do as a filtering function. You could go with the filter FILTER_SANITIZE_STRING, judging by your case.
Refer the filter_array method in php manual : http://php.net/manual/en/function.filter-input.php
Refer what filters are available in php : http://php.net/manual/en/filter.filters.php
What Filter am I using for this demo : http://php.net/manual/en/filter.filters.sanitize.php
So your input assignment to variables will look like the following,
$FirstName = filter_input(INPUT_POST, $_POST["FirstName"], FILTER_SANITIZE_STRING);
$LastName = filter_input(INPUT_POST, $_POST["LastName"], FILTER_SANITIZE_STRING);
And i gather you might be using NetBeans for PHP development (https://blogs.oracle.com/netbeansphp/entry/improve_your_code_with_new). This has the same warning as you've mentioned. But I'm not quite sure you will see the warning around other IDE's.