i have user add form in my webpage.
Codes like this;
if(isset($_POST['submitted']) ==1) {
$name = mysqli_real_escape_string($dbc, $_POST['name']);
$surname = mysqli_real_escape_string($dbc, $_POST['surname']);
$date = mysqli_real_escape_string($dbc, $_POST['date']);
$email = mysqli_real_escape_string($dbc, $_POST['email']);
$password = mysqli_real_escape_string($dbc, $_POST['password']);
$city = mysqli_real_escape_string($dbc, $_POST['city']);
$q = "INSERT INTO users (name, surname, date, email, password, city) VALUES('$name', '$surname', '$date', '$email', '$password', '$city')";
$r = mysqli_query($dbc, $q);
if($r) {
$message = 'User was added';
}else{
$message = 'User could not be added because: '.mysqli_error($dbc);
$message .= '<p>'.$q.'</p>';
}
}
my submit button is:
<button type="submit" class="btn btn-default">Add User</button>
<?php if(isset($message)) { echo $message; }?>
<input type="hidden" name="submitted" value="1">
I want to check existing values in my database table with that post button.
How can i check same values in this post?
you can do something like this:
<?php
if (isset($_POST['submitted']) == 1) {
$name = mysqli_real_escape_string($dbc, $_POST['name']);
$surname = mysqli_real_escape_string($dbc, $_POST['surname']);
$date = mysqli_real_escape_string($dbc, $_POST['date']);
$email = mysqli_real_escape_string($dbc, $_POST['email']);
$password = mysqli_real_escape_string($dbc, $_POST['password']);
$city = mysqli_real_escape_string($dbc, $_POST['city']);
$q = "SELECT * FROM users WHERE email='".$email."'";
$r = mysqli_query($dbc, $q);
if ($r->num_rows == 0) {
$q = "INSERT INTO users (name, surname, date, email, password, city) VALUES('$name', '$surname', '$date', '$email', '$password', '$city')";
$r = mysqli_query($dbc, $q);
if ($r) {
$message = 'User was added';
} else {
$message = 'User could not be added because: ' . mysqli_error($dbc);
$message .= '<p>' . $q . '</p>';
}
} else {
$message = "Email does exist already";
}
}
Related
The code I have below is suppose to insert some information into a mysql database. For some reason every time I test it I get the error statement that it was not able to execute. Everything looks like it should work to me. Is there something I am missing here?
<?php
include("phpconnect.php");
$name = $_GET["name"];
$date = $_GET["date"];
echo $name;
echo $date;
$sql = "INSERT INTO main (name, visits, visitDate, lastVisit)
VALUES ('$name', '1', '$date', '$date')";
if (mysqli_query($conn, $sql))
{
echo "Records added successfully.";
}
else
{
echo "ERROR: Could not execute $sql. "
.mysqli_error($conn);
}
mysqli_close($conn);
?>
Maybe, you should build your SQL statement slightly different. You can always throw an error message, better for the overview -
$sql = "INSERT INTO main (name, visits, visitDate, lastVisit)
VALUES (?, 1, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
$stmt->bind_param('sss', $name, $date, $date);
if (!$stmt->execute()) {
return false;
// or print error message
} else {
return true;
} else {
return false;
}
Or check this out - MySQL INSERT INTO with PHP $variable !
First Check your datbase connection
Second check your form method GET or POST then apply
Check your table column name
include("phpconnect.php");
if(isset($_POST['submit'])){
$name = $_POST["name"];
$date = $_POST["date"];
$sql = "INSERT INTO main (name, visits, visitDate, lastVisit) VALUES ('$name', '1', '$date', '$date')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
Try something like this. This function accurately inserts into my database and also scrapes for SQL injection.
function addRestaurant() {
if(isset($_POST['submit'])) {
global $connection;
$name = $_POST['name'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$googlemapslink = $_POST['googlemapslink'];
$restauranttype = $_POST['restauranttype'];
$website = $_POST['website'];
$logo = $_POST['logo'];
$sitelink = $_POST['sitelink'];
if ($googlemapslink == "") {
$googlemapslink = "https://youtu.be/dQw4w9WgXcQ";
}
if ($website == "") {
$website = "https://youtu.be/dQw4w9WgXcQ";
}
if ($logo == "") {
$logo = "https://youtu.be/dQw4w9WgXcQ";
}
$name = mysqli_real_escape_string($connection, $name);
$address = mysqli_real_escape_string($connection, $address);
$city = mysqli_real_escape_string($connection, $city);
$state = mysqli_real_escape_string($connection, $state);
$zipcode = mysqli_real_escape_string($connection, $zipcode);
$googlemapslink = mysqli_real_escape_string($connection, $googlemapslink);
$restauranttype = mysqli_real_escape_string($connection, $restauranttype);
$website = mysqli_real_escape_string($connection, $website);
$logo = mysqli_real_escape_string($connection, $logo);
$sitelink = mysqli_real_escape_string($connection, $sitelink);
$query = "INSERT INTO `restaurants` (Name, Address, City, State, ZipCode, GoogleMapsLink, Website, RestaurantType, RestaurantLogo, SiteLink) ";
$query .= "VALUES (";
$query .= "'$name', ";
$query .= "'$address', ";
$query .= "'$city', ";
$query .= "'$state', ";
$query .= "'$zipcode', ";
$query .= "'$googlemapslink', ";
$query .= "'$website', ";
$query .= "'$restauranttype', ";
$query .= "'$logo', ";
$query .= "'$sitelink'); ";
$filesite = "restaurants/" . $sitelink;
$file = "restaurants/menu.php";
$contents = file_get_contents($file);
file_put_contents($filesite, $contents);
$result = mysqli_query($connection, $query);
if(!$result) {
die("Query failed." . mysqli_error($connection));
} else {
echo "Record updated!";
}
}
}
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'm creating a Wedding Planning Web Application. My Database is connected but no data is being inserted nor am I receiving any error messages when trying to register a user.
I'm being directed straight to the linked Login page. I've tried to match the date formatting (User input as dd/mm/yyyy and being stored as yyyy/mm/dd) from php and MySQL but not sure if it's working/ if it is the issue.
I've been trying to figure out a solution for hours and I'm under pressure to solve it so I can complete my dissertation.
<?php
//Starts the session
session_start();
require_once 'DBConnect.php';
$firstname = "";
$lastname = "";
$email_address = "";
$phone_num = "";
$acc_password = "";
$weddingdate = "";
// REGISTER USER
if (isset($_POST['btn-Register']))
{
// receive all input values from the form
$firstname = mysqli_real_escape_string($DBcon, $_POST['firstname']);
$lastname = mysqli_real_escape_string($DBcon, $_POST['lastname']);
$email_address = mysqli_real_escape_string($DBcon,
$_POST['email_address']);
$phone_num = mysqli_real_escape_string($DBcon, $_POST['phone_num']);
$acc_password = mysqli_real_escape_string($DBcon,
$_POST['acc_password']);
$weddingdate = mysqli_real_escape_string($DBcon,
$_POST['weddingdate']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
// phone_num and weddingdate can be NULL
if (empty($firstname)) { array_push($errors, "First Name is
required"); }
if (empty($lastname)) { array_push($errors, "Last Name is
required"); }
if (empty($email_address)) { array_push($errors, "Email is
required"); }
if (empty($acc_password)) { array_push($errors, "Password is
required"); }
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM customer WHERE email_address =
'$email_address' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
//if user exists
if ($user['email_address'] === $email_address)
{
array_push($errors, "User already exists");
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0)
{
//encrypt the password before saving in the database
$acc_password = md5($acc_password);
$query = "INSERT INTO customer (firstname, lastname,
email_address, phone_num, acc_password, weddingdate)
VALUES('$firstname', '$lastname' '$email_address',
'$phone_num', '$acc_password', '$weddingdate')";
mysqli_query($DBcon, $query);
$_SESSION['email_address'] = $email_address;
$_SESSION['success'] = "You are now Registered";
header('location: Login.php');
}
//This should format the date with phpMyAdmin
$weddingdate = date('Y-m-d H:i', strtotime($_POST["weddingdate"]));
// LOGIN USER
if (isset($_POST['btn-Login']))
{
$email_address = mysqli_real_escape_string($DBcon,
$_POST['email_address']);
$acc_password = mysqli_real_escape_string($DBcon,
$_POST['acc_password']);
if (empty($email_address))
{
array_push($errors, "Email Address is required");
}
if (empty($acc_password))
{
array_push($errors, "Password is required");
}
if (count($errors) == 0)
{
$acc_password = md5($acc_password);
$query = "SELECT * FROM customer WHERE
email_address='$email_address' AND
acc_password='$acc_password'";
$results = mysqli_query($DBcon, $query);
if (mysqli_num_rows($results) == 1)
{
$_SESSION['email_address'] = $email_address;
$_SESSION['success'] = "You are now logged in";
header('location: Main.php');
}else
{
array_push($errors, "Wrong username/password
combination");
}
}
}
}
?>
There is syntax error in insert query line.
$query = "INSERT INTO customer (firstname, lastname, email_address, phone_num, acc_password, weddingdate)
VALUES('$firstname', '$lastname', '$email_address', '$phone_num', '$acc_password', '$weddingdate')";
One Comma , is missing after '$lastname'
The issue is probably that the variables aren't being taken as their values. You need to escape the sequence before you can add the variables. So, instead of having
$query = "INSERT INTO customer (firstname, lastname,
email_address, phone_num, acc_password, weddingdate)
VALUES('$firstname', '$lastname', '$email_address',
'$phone_num', '$acc_password', '$weddingdate')";
You need to do this
$query = "INSERT INTO customer (firstname, lastname, email_address,
phone_num, acc_password, weddingdate) VALUES(
'" . $firstname . "', '" . $lastname . "',
'" . $email_address . "', '" . $phone_num . "',
'" . $acc_password . "', '" . $weddingdate . "')";
This should fix your problem, but as a few of the other commenters have mentioned, this may leave you open to SQL injection. You should be using prepared statements to protect yourself from those vulnerabilities.
I'm following a tutorial and I've run into an issue where I can complete my registration form but my info isn't saved into the database table. All my code is the same as the tutorial. Am I missing something?
Obviously it has to do with my $insert variable, but I can't figure out what it is.
if(isset($_POST['register'])) {
$user_name = mysqli_real_escape_string($con, $_POST['user_name']);
$user_pass = mysqli_real_escape_string($con, $_POST['user_pass']);
$user_email = mysqli_real_escape_string($con, $_POST['user_email']);
$user_country = mysqli_real_escape_string($con, $_POST['user_country']);
$user_number = mysqli_real_escape_string($con, $_POST['user_number']);
$user_address = mysqli_real_escape_string($con, $_POST['user_address']);
$user_gender = mysqli_real_escape_string($con, $_POST['user_gender']);
$user_b_day = mysqli_real_escape_string($con, $_POST['b_day']);
$user_image = $_FILES['user_image']['name'];
$user_tmp = $_FILES['user_image']['tmp_name'];
if($user_address=='' OR $user_country=="" OR $user_image=="" OR $user_gender=='') {
echo "<script>alert('Please fill all the fields.')</script>";
exit();
}
if(!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
echo "<script>alert('Your email is not valid.')</script>";
exit();
}
$sel_email = "SELECT * FROM register_user WHERE user_email='" . $user_email . "';";
$run_email = mysqli_query($con, $sel_email);
$check_email = mysqli_num_rows($run_email);
if($check_email==1) {
echo "<script>alert('This email is already registered. Please choose another.')</script>";
exit();
}
else {
$_SESSION['user_email'] = $user_email;
move_uploaded_file($user_tmp, "images/$user_image");
$insert = "INSERT INTO register_user (user_name,
user_pass,
user_email,
user_country,
user_number,
user_address,
user_gender,
user_b_day,
user_image,
register_date)
VALUES ('$user_name',
'$user_pass',
'$user_email',
'$user_country',
'$user_number',
'$user_address',
'$user_gender',
'$user_b_day',
'$user_image',
NOW())";
mysqli_query($con, $insert);
echo "<script>alert('Registration successful.')</script>";
echo "<script>window.open('home.php', '_self' )</script>";
}
}
If you have no error message, try this:
$insert = "INSERT INTO register_user (user_name,
user_pass,
user_email,
user_country,
user_number,
user_address,
user_gender,
user_b_day,
user_image,
register_date)
VALUES ('".$user_name."',
'".$user_pass."',
'".$user_email."',
'".$user_country."',
'".$user_number."',
'".$user_address."',
'".$user_gender."',
'".$user_b_day."',
'".$user_image."',
NOW())";
Hi Guys I am having a problem that when adding form data into a database. For some reason the data is not inserted. here is my code:
<?php include_once 'secure/connect.php'; ?>
<?php
$name = "Your Name";
$email = "Your Best Email";
$msg_to_user = "";
if ($_POST['name'] != ""){
//Be sure to filter this data to deter SQL injection
$name = $_POST['name'];
$name = stripslashes($name);
$name = strip_tags($name);
$email = $_POST['email'];
$email = stripslashes($email);
$email = strip_tags($email);
$sql = mysql_query("SELECT * FROM newsletter WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if(!$email){
$msg_to_user = '<h4><font color="FF0000">Please Type an email address ' . $name . '</font></h4>';
} else if ($numRows > 0) {
$msg_to_user = '<h4><font color="FF0000">' . $email . ' is already in our system</font></h4>';
} else {
$sql_insert = mysql_query("INSERT INTO newsletter (name, email, dateTime) VALUES ('$name', '$email', now())") or die (mysql_error());
$msg_to_user = '<h4><font color="0066FF">Thanks' . $name . ', You have been added successfully</font></h4>';
$name = "";
$email = "";
}
}
?>
And my html form looks like this:
<div class="topForm">
<H3 style="text-align:center">SIGN UP FOR OUR NEWSLETTER</H3>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="name" value="<?php echo $name; ?>"/>
<input type="text" name="email" value="<?php echo $email; ?>"/><br/>
<input name="mySubmitBtn" type="submit" value="SUBMIT">
<?php echo $msg_to_user; ?>
</form>
</div>
Many thanks in advance all
Phillip
This is what I have now and nothing is still working...
<?php
$name = "Your Name";
$email = "Your Best Email";
$msg_to_user = "";
if ($_POST['name'] != ""){
include_once 'secure/connect.php';
//Be sure to filter this data to deter SQL injection
$name = $_POST['name'];
$name = stripslashes($name);
$name = strip_tags($name);
$email = $_POST['email'];
$email = stripslashes($email);
$email = strip_tags($email);
$sql = mysql_query("SELECT * FROM newsletter WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if(!$email){
$msg_to_user = '<h4><font color="FF0000">Please Type an email address ' . $name . '</font></h4>';
} else if ($numRows > 0) {
$msg_to_user = '<h4><font color="FF0000">' . $email . ' is already in our system</font></h4>';
} else {
$sql_insert = mysql_query("INSERT INTO newsletter (name, email) VALUES ('".$name."', '".$email."')") or die (mysql_error());
$msg_to_user = '<h4><font color="0066FF">Thanks' . $name . ', You have been added successfully</font></h4>';
$name = "";
$email = "";
}
}
?>
without regard to other errors or inconsistencies. also let me note that you should use mysqli or pdo. but php uses time()
$sql_insert = mysql_query("
INSERT INTO newsletter
(name, email, dateTime)
VALUES
('$name', '$email', ".time().")
");
or if you want a date time instead of the timestamp you can use the date() function.
You have to change now() from your code. And Use Following code.
$time = time() ;
$sql_insert = mysql_query("INSERT INTO newsletter (name, email, dateTime) VALUES ('".$name."', '".$email."', '".$time."' )") or die (mysql_error());
make sure you are connected to the database ! see what echo mysql_error(); says
if a form was submitted, catch the values, and then sanitize
insert query
ps: see what the following do:
if(isset($_POST['name']) ...
echo mysql_insert_id();
time() not now()
see the id of the new data inserted
your code, should work, if you follow these steps, and if you are connected to the database