i'm new to this PHP please help me here i'm unable to insert values into table.
But if i gave values directly to insert command in place of variables it works.
<?php
include ("db.php");
$msg = "";
if(isset($_POST["submit"]))
{
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$name = mysqli_real_escape_string($db, $name);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$sql="SELECT email FROM users2 WHERE email='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
$msg = "Sorry...This email already exist...";
}
else
{
$query = mysqli_query($db, "INSERT INTO users2 (name, email, password)VALUES ('$name', '$email', '$password')");
if($query)
{
$msg = "Thank You! you are now registered.";
}
}
}
?>
$sql = "INSERT INTO users2 (name, email, password) VALUES (?,?,?)";
if (!$stmt = $db->prepare($sql)) {
die($db->error);
}
$stmt->bind_param("sss", $name, $email, $password);
if (!$stmt->execute()) {
die($stmt->error);
}
I don't know what is the problem in my above question but
i used the above query instead of the one i used the in question and Boom it is a success.
if any one of you know whats the problem in the question please let me know.
You have to concat the variable in string of insert not just put as variable
$query = mysqli_query($db,"INSERT INTO users2 (name, email, password)VALUES ('".$name."', '".$email."', '".$password."')")
or
$query = mysqli_query($db,"INSERT INTO users2 (name, email, password)VALUES ('{$name}', '{$email}', '{$password}')")
You should use prepare statement for this mysql_real_escape_string-versus-Prepared-Statements
Never use md5() is-md5-considered-insecure
Prefer password_hash() or password_verify() Manuel
``
Related
Im using the following code and testing it using WAMP on my localhost.
It works fine and inserts the data however for some reason it creates duplicate row.
Is there are reason why it makes it appear twice?
<?php
require "conn.php";
$name =$_POST["name"];
$surname = $_POST["surname"];
$age = $_POST["age"];
$username = $_POST["username"];
$userpass = $_POST["password"];
$mysql_qry = "insert into employee_data(name, surname, age, username, password) values ('$name', '$surname', '$age', '$username', '$userpass')";
$result = mysqli_query($conn, $mysql_qry);
if ($conn->query($mysql_qry) === TRUE){
echo "insert success";
}
else{
echo "Error:" .$mysql_qry . "<br> " . $conn->error;
}
$conn->close();
?>
Thank you
YES, you run the query TWICE, see comments in the code
<?php
require "conn.php";
$name =$_POST["name"];
$surname = $_POST["surname"];
$age = $_POST["age"];
$username = $_POST["username"];
$userpass = $_POST["password"];
$mysql_qry = "insert into employee_data
(name, surname, age, username, password)
values ('$name', '$surname', '$age', '$username', '$userpass')";
//ONCE HERE
$result = mysqli_query($conn, $mysql_qry);
//AND AGAIN HERE
if ($conn->query($mysql_qry) === TRUE){
echo "insert success";
}
else{
echo "Error:" .$mysql_qry . "<br> " . $conn->error;
}
$conn->close();
?>
ALSO Your script is wide open to SQL Injection Attack
Even if you are escaping inputs, its not safe!
Use prepared parameterized statements in either the MYSQLI_ or PDO API's
Coded using prepared and bound queries
<?php
require "conn.php";
$sql = "insert into employee_data
(name, surname, age, username, password)
values (?,?,?,?,?)";
$stmt = $conn-prepare($sql);
$stmt->bind_param('sssss', $_POST["name"],
$_POST["surname"];
$_POST["username"];
$_POST["password"];
if ( $stmt->execute() ){
echo "insert success";
}else{
echo "Error:" .$mysql_qry . "<br> " . $conn->error;
}
$conn->close();
?>
Now I have to mention how bad it is to use Plain Text Password.
PHP provides password_hash()
and password_verify() please use them.
And here are some good ideas about passwords
I have a registration page, which is tied to this process.php code below. When I run this code, it returns "Error". Did I make a mistake somewhere?
<?php
require_once ('newmeowconnection.php');
if (isset($_POST['form_input']) && $_POST['form_input'] == 'registration') {
registerUser();
}
function registerUser() {
$query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at)
VALUES('{$_POST['first_name']}','{$_POST['last_name']}','{$_POST['email']}', '{$_POST['password']}', NOW(), NOW())";
$run = mysqli_query($query);
if ($run) {
$_SESSION['loggedin'] = TRUE;
$_SESSION['user'] = $_POST['email'];
header('Location: http://localhost/homepage.php');
} else {
echo 'Error';
}
}
?>
mysqli_query need run on connection object or pass connection to it:
$run = mysqli->query($connection, $query);
or
$run = $connection->query($query);
The problem is you are using single quotes-inside single-quotes. For instance '{$_POST['first_name']}' is read as {$_POST[ being one thing first_name as a SQL variable and ]} another string.
Try the following
...
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at) VALUES('{$first_name}','{$last_name}','{$email}', '{$password}', NOW(), NOW())";
...
So when I want to retrieve data and check it i.e. if the email already exist echo already registered. That part works fine, however inserting the same data does not work. Are my conditionals ordered improperly?
(intentionally left out values for the dbhostname id pw variables)
$dbname = "hw2";
$link = mysqli_connect($dbhostname, $dbuserid, $dbpassword, $dbname);
$firstname = $_POST["signup-firstname"];
$lastname = $_POST["signup-lastname"];
$email = $_POST["signup-email"];
$password = $_POST["signup-password"];
$repassword = $_POST["signup-repassword"];
if ($password != $repassword){
echo "<br><h3>Passwords did not match. <br>Please try again.</h3>";
}
else {
$ret_email = "SELECT * FROM hw2 WHERE email = '$email'";
$result = mysqli_query($link, $ret_email);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0){
echo "This email is already registered.";
}
else{
$insert_query = "INSERT INTO hw2 (firstname, lastname, email, password, repassword) VALUES ('$firstname', '$lastname', '$email', '$password', '$repassword')";
echo "$insert_query";
}
}
?>
You should perform the query not only echoing it
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
if ($num_rows > 0){
echo "This email is already registered.";
}
else{
$insert_query = "INSERT INTO hw2 (firstname, lastname, email, password, repassword) VALUES ('$firstname', '$lastname', '$email', '$password', '$repassword')";
echo "$insert_query";
mysqli_query($link,$insert_query)
}
I have this code which checks email availability from database, but it's only checking email and not username. I want to check both email and username, I tried to check them through the code below but it doesnt work.
What is wrong with the code?
<?php
require_once './config.php';
if (isset($_POST["sub"])) {
$fname = ($_POST["fname"]);
$lname = ($_POST["lname"]);
$name = ($_POST["username"]);
$pass = ($_POST["password"]);
$email = ($_POST["email"]);
$sql = "SELECT COUNT(*) AS count from users where email = :email_id and username = :username_id ";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue(":email_id", $email);
$stmt->bindValue(":username_id", $name);
$stmt->execute();
$result = $stmt->fetchAll();
if ($result[0]["count"] > 0) {
echo "<div style='color:red;' class='errorbox'>Incorrect Username or Password</div><br>";
} else {
$sql = "INSERT INTO `users` (`username`, `password`, `email`, `firstname`, `lastname`) VALUES " . "( :name, :pass, :email, :fname, :lname)";
}
}
}
?>
You have a problem with your SQL statement, you are checking that both email and username are together try changing your statement from
$sql = "SELECT COUNT(*) AS count from users where email = :email_id and username = :username_id "
to
$sql = "SELECT COUNT(*) AS count from users where email = :email_id or username = :username_id "
This should force a return of 1 whenever either the username or email appears proving that they are not unique
You are using and condition. If you use or condition means it will be fine.
$sql = "SELECT COUNT(*) AS count from users where email = :email_id or username = :username_id ";
Typographical error. This line should be replaced:
$stmt->bindValue(":username_id", $email);
should be replaced with:
$stmt->bindValue(":username_id", $name);
Maybe you have an error here:
$stmt->bindValue(":email_id", $email); //ok
$stmt->bindValue(":username_id", $email); //you bind with $email again .. is it normal ?
You should validate your $_POST datas with !empty i.e.:
if(!empty($_POST["email"]) $email = $_POST["email"]) ... because with your actual code you could make sql queries with empty $email = null
I sanitise the data I receive from the form in the following way:
$gender = filter_var($_POST['gender'], FILTER_SANITIZE_STRING);
$firstName = filter_var($_POST['firstName'], FILTER_SANITIZE_STRING);
$lastName = filter_var($_POST['lastName'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
$address = filter_var($_POST['address'], FILTER_SANITIZE_STRING);
$numBrochures = (int) filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT);
The relevant SQL queries that insert the data are as follows:
if (mysqli_query($conn, "INSERT INTO users(firstName, lastName, email, gender) VALUES('$firstName', '$lastName', '$email', '$gender')") == TRUE) {
logSuccess($file, "Adding user");
}
else {
logError($file, "Adding user", mysqli_error($conn));
}
$userId = $conn->query("SELECT `userId` FROM users WHERE `firstName` = '$firstName' AND `lastName` = '$lastName' AND `email` = '$email'")->fetch_object()->userId;
if ($userId == false) {
logError($file, "Fetching user id", mysqli_error($conn));
}
if (mysqli_query($conn, "INSERT INTO brochureOrders(userId, address, numBrochures, message) VALUES('$userId', '$address', '$numBrochures', '$message')") == TRUE) {
logSuccess($file, "Brochure Order");
$sendConfirmationEmail = true;
}
else {
logError($file, "Brochure Order", mysqli_error($conn));
}
However, in my database, I see entries like the following:
address = "vz8y8E gghwptvvzuak, [url=http://ytvsmximkjnp.com/]ytvsmximkjnp[/url], [link=http://hiabgyvsjifp.com/]hiabgyvsjifp[/link], http://tyvylndqitoy.com/"
Shouldn't the following have taken care of this?
$address = filter_var($_POST['address'], FILTER_SANITIZE_STRING);
Could someone tell me what I am doing incorrectly here?
Because the OP stated in the comments he wants to switch to prepared statement, I thought I'd show him an example.
Instead of something like this:
if (mysqli_query($conn, "INSERT INTO users(firstName, lastName, email, gender) VALUES('$firstName', '$lastName', '$email', '$gender')") == TRUE) {
logSuccess($file, "Adding user");
}
else {
logError($file, "Adding user", mysqli_error($conn));
}
Do something like this:
$query = "INSERT INTO users (firstName, lastName, email, gender) VALUES(?, ?, ?, ?)";
if($stmt = $mysqli->prepare($query)){
$stmt->bind_param('ssss', $firstName, $lastName, $email, $gender);
$stmt->exeucte();
$stmt->close();
}else die("Failed to prepare!");
and this
$query = "SELECT `userId` FROM users WHERE `firstName` = ? AND `lastName` = ? AND `email` = ?";
if($stmt = $mysqli->prepare($query)){
$stmt->bind_param('sss', $firstName, $lastName, $email);
$stmt->execute();
$stmt->bind_result($userId);
$stmt->fetch();
$stmt->close()
}else die("Failed to prepare!");