If someone can help me with this, I'm not good with php but I'm trying to learn but this problem I encounter makes my head hurt.
Here's the full error:
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:\xampp\htdocs\website\register.php:34 Stack trace: #0 C:\xampp\htdocs\website\register.php(34): PDOStatement->execute(Array) #1 {main} thrown in C:\xampp\htdocs\website\register.php on line 34
<?php
include 'config.php';
if(isset($_POST['submit'])){
$name = $_POST['name'];
$name = filter_var($name, FILTER_SANITIZE_STRING);
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_STRING);
$pass = md5($_POST['pass']);
$pass = filter_var($pass, FILTER_SANITIZE_STRING);
$cpass = md5($_POST['cpass']);
$cpass = filter_var($cpass, FILTER_SANITIZE_STRING);
$user_type = $_POST['user_type'];
$image = $_FILES['image']['name'];
$image_tmp_name = $_FILES['image']['tmp_name'];
$image_size = $_FILES['image']['size'];
$image_folder = 'uploaded_img/'.$image;
$select = $conn->prepare("SELECT * FROM `users` WHERE email = ?");
$select->execute([$email]);
if($select->rowCount() > 0){
$message[] = 'user already exist!';
}else{
if($pass != $cpass){
$message[] = 'confirm password not matched!';
}elseif($image_size > 2000000){
$message[] = 'image size is too large!';
}else{
$insert = $conn->prepare("INSERT INTO `users`(name, email, password, image, user_type) VALUES(?,?,?,?)");
$insert->execute([$name, $email, $cpass, $image, $user_type]);
if($insert){
move_uploaded_file($image_tmp_name, $image_folder);
$message[] = 'registered succesfully!';
header('location:login.php');
}
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>register</title>
<!-- font awesome cdn link -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
<!-- custom css file link -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<?php
if(isset($message)){
foreach($message as $message){
echo '
<div class="message">
<span>'.$message.'</span>
<i class="fas fa-times" onclick="this.parentElement.remove();"></i>
</div>
';
}
}
?>
<section class="form-container">
<form action="" method="post" enctype="multipart/form-data">
<h3>register now</h3>
<input type="text" required placeholder="enter your username" class="box" name="name">
<input type="email" required placeholder="enter your email" class="box" name="email">
<input type="password" required placeholder="enter your password" class="box" name="pass">
<input type="password" required placeholder="confirm your password" class="box" name="cpass">
<input type="file" name="image" required class="box" accept="image/jpg, image/png, image/jpeg">
<select name="user_type">
<option value="admin">admin</option>
<option value="user">user</option>
<option value="company">company</option>
<p>already have an account? login now</p>
<input type="submit" value="register now" class="btn" name="submit">
</form>
</section>
</body>
</html>
Change this line:
$insert = $conn->prepare("INSERT INTO `users`(name, email, password, image, user_type)
VALUES(?,?,?,?)");
to:
$insert = $conn->prepare("INSERT INTO `users`(name, email, password, image, user_type)
VALUES(?,?,?,?,?)");
Because you want to use 5 parameters , you also need 5 ? marks.
Related
I tried to create a form which will send an email and add data to MySQL data base. For email part because I work on localhost I used formsubmit. All good but there is a conflict. When I press on send only the email is send without any data added to my database. If I delete the action attribute from form data will be added but in this case I can't send any emails. Here is my file:
<?php
require 'config.php';
if(!empty($_SESSION["id"]))
{
$id= $_SESSION["id"];
$result = mysqli_query($conn,"SELECT * FROM tb_user WHERE id= $id");
$row = mysqli_fetch_assoc($result);
}
else
{
header("Location: login.php");
}
if(isset($_POST["submit"]))
{
$name = $_POST['name'];
$email = $_POST['email'];
$cui = $_POST['cui'];
$tip = $_POST['tip'];
$adresa = $_POST['adresa'];
$query = "INSERT INTO beneficiari VALUES('','$email','$name','$cui','$tip','$adresa')";
mysqli_query($conn,$query);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Beneficiari </title>
<link rel="stylesheet" href="indexCSS.css">
<link rel="stylesheet" type="text/css" href="beneficiariCSS.css">
</head>
<body>
<div class="topnav">
Welcome <?php echo $row["name"]; ?>
Logout
<a class="active" href="index.php">Home</a>
Anunturi
Viz
Registration
</div>
<div class="container">
<form action="https://formsubmit.co/0e6b51872b4393271dbfa08bb0655fc8" method="POST">
<h3>Inregistrare</h3>
<input type="text" name="name" id="name" placeholder="Denumire institutie" required>
<input type="email" name="email" id="email" placeholder="Enter an valid email" required>
<input type="text" name="cui" id="cui" placeholder="CUI" required>
<input type="text" name="tip" id="tip" placeholder="Tipul institutie" required>
<input type="text" name="adresa" id="adresa" placeholder="Adresa" required>
<button type="submit" name="submit">Send</button>
</form>
</div>
</body>
</html>
You can remove the action from form, and add it after the SQL query, within the if statement as header, like so:
if(isset($_POST["submit"]))
{
$name = $_POST['name'];
$email = $_POST['email'];
$cui = $_POST['cui'];
$tip = $_POST['tip'];
$adresa = $_POST['adresa'];
$query = "INSERT INTO beneficiari VALUES('','$email','$name','$cui','$tip','$adresa')";
mysqli_query($conn,$query);
header('location: https://formsubmit.co/0e6b51872b4393271dbfa08bb0655fc8');
}
I believe this will work.
But whatever you do make sure you check the input!! The way you are handling your input right now is very dangerous, and allows users to inject you with SQLs (read up on SQL injections and protection)
I am working on a project and includes the ability for the user to create an account on the site. I've been able to set up the database and connect the page to the database and when a user creates an account, the information is added to a table in the database called Users; however, if a duplicate email address is entered I don't want the information to be added to the database and to display to the user to enter another email address. I have been able to prevent duplicate entries by using a UNIQUE INDEX table but I haven't been able to figure out how to first check for an existing email and display an error if one already exists.
register.php (form)
<?php
if(!isset($fName) && !isset($lName) && !isset($zip) && !isset($email) &&
!isset($password)) {
$fName = '';
$lName = '';
$zip = '';
$email = '';
$password = '';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Register</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="/CentralPerk/main.css" />
<link rel="stylesheet" type="text/css" media="screen" href="formstyles.css" />
<script src="main.js"></script>
</head>
<body>
<div id="aside">
<h1>Register For An Account</h1>
</div>
<form action="index.php" method="post" id="registration_form">
<input type="hidden" name="action" value="register">
<label>Personal Information</label>
<br>
<br>
<input type="text" name="fName" placeholder="First Name" required
value="<?php echo htmlspecialchars($fName); ?>" />
<br>
<br>
<input type="text" name="lName" placeholder="Last Name" required
value="<?php echo htmlspecialchars($lName); ?>" />
<br>
<br>
<input name="zip" id="zipcode" type="text" placeholder="Zipcode" required
pattern="^\d{5}(-\d{4})?$"
value="<?php echo htmlspecialchars($zip); ?>" />
<br>
<br>
<label>Account Information</label>
<br>
<br>
<input type="email" name="email" placeholder="Email Address" required
value="<?php echo htmlspecialchars($email); ?>" />
<br>
<br>
<input type="password" name="password" placeholder="password" required
value="<?php echo htmlspecialchars($password); ?>" />
<br>
<br>
</form>
<button type="submit" form="registration_form" value="Submit">Submit</button>
</body>
</html>
index.php (register form connects to index.php when the user submits the form)
<?php
require('../model/database.php');
require('../model/account_db.php');
//form value is 'action'
$action = filter_input(INPUT_POST, 'action');
if($action == 'register') {
$fName = filter_input(INPUT_POST, 'fName');
$lName = filter_input(INPUT_POST, 'lName');
$zip = filter_input(INPUT_POST, 'zip', FILTER_VALIDATE_INT);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$password = filter_input(INPUT_POST, 'password');
//this is where I am trying to determine if the email entered already exists,
//if it does not, it executes the add_user method in the account_db.php file
$checkUserEmail = $db -> query("SELECT UserEmail FROM Users
WHERE `UserEmail` = $email");
if ($checkUserEmail === TRUE) {
$message = "User already exists";
include('../model/test.php');
}
else {
add_user($fName, $lName, $zip, $email);
header('../CentralPerk/index.php');
}
}
?>
account_db.php (adds user to database)
<?php
function add_user($fName, $lName, $zip, $email) {
global $db;
$query = 'INSERT INTO Users
(UserFirstName, UserLastName, UserZipcode, UserEmail)
VALUES
(:fName, :lName, :zip, :email)';
$statement = $db->prepare($query);
$statement->bindValue(':fName', $fName);
$statement->bindValue(':lName', $lName);
$statement->bindValue(':zip', $zip);
$statement->bindValue(':email', $email);
$statement->execute();
$statement->closeCursor();
}
?>
accounts.sql
DROP DATABASE IF EXISTS accounts;
CREATE DATABASE accounts;
USE accounts;
GRANT SELECT, INSERT, UPDATE, DELETE
ON *
TO mgs_user#localhost
IDENTIFIED BY 'pa55word';
CREATE TABLE Users (
UserID BIGINT NOT NULL AUTO_INCREMENT,
UserFirstName VARCHAR(60) NOT NULL,
UserLastName VARCHAR(60) NOT NULL,
UserZipcode INT NOT NULL,
UserEmail VARCHAR(60) NOT NULL,
PRIMARY KEY(UserID)
);
CREATE UNIQUE INDEX user_idx ON Users (
UserEmail
);
Instead of
if ($checkUserEmail === TRUE) {
Use
if($checkUserEmail->num_rows >= 1)
I want to make a student registration form. I get no error messages, but the data is not entered into the database.
INDEX is for INDEX NUMBER
USERNAME is for USER
EMAIL is for EMAIL
I had trouble with index variable it said that it is undefined, I am not sure if I defined the variable properly.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- TemplateBeginEditable name="doctitle" -->
<title>Untitled Document</title>
<!-- TemplateEndEditable -->
<!-- TemplateBeginEditable name="head" -->
<!-- TemplateEndEditable -->
</head>
<body>
<?php
session_start();
$_SESSION["message"] = "";
$mysqli = new MySQLi("localhost","root","","accounts");
if ($_SERVER['REQUEST_METHOD'] == "POST"){
$username = $mysqli->real_escape_string($_POST["username"]);
$email = $mysqli->real_escape_string($_POST["email"]);
$index = ($_POST["email"]);
$_SESSION["username"] = $username;
$_SESSION["email"] = $email;
$sql = "INSERT INTO users (index, email, name) "
. "VALUES ('$index', '$email', '$username')";
//check if mysql query is successful
if ($mysqli->query($sql) === true)
{
$_SESSION[ 'message' ] = "Registration succesful! Added $username to the database!";
//redirect the user to welcome.php
header( "location: welcome.php" );
}
else{
$_SESSION["message"] = "user could not be added to the database";
}
}
else{
$_SESSION["message"] = "could not initiate session";
}
?>
<link href="//db.onlinewebfonts.com/c/a4e256ed67403c6ad5d43937ed48a77b?family=Core+Sans+N+W01+35+Light" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" href="form.css" type="text/css">
<div class="body-content">
<div class="module">
<h1>Create an account</h1>
<form class="form" action="form.php" method="post" enctype="multipart/form-data" autocomplete="off">
<div class="alert alert-error"></div>
<input type="text" placeholder="User Name" name="username" required />
<input type="email" placeholder="Email" name="email" required />
<br>
<input type="text" placeholder="Index Number" name="index" required /><br>
<input type="submit" value="Register" name="register" class="btn btn-block btn-primary" />
</form>
</div>
</div>
</body>
</html>
Change this line :
$sql = "INSERT INTO users (index, email, name) "
. "VALUES ('$index', '$email', '$username')";
To this :
$sql = 'INSERT INTO users (index, email, name) '
. 'VALUES ("$index", "$email", "$username")';
Hope to solve your problem.
I´m working on netbeans, on winsows and with xampp. I believe it has something to do with the version of PHPMailer, I see examples with
PHPAutoload.php
but with the version I downloaded from gitHub I don´t see that file. Everything look fine, it does insert into the data base but got to this part of the code
$msg = "Something wrong happened! Please try again!";
I pasted the PHPMailer folder into c:/xampp/htdocs/pojectmail/PHPMailer.
Here is my register.php code
<?php
$msg = "";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if (isset($_POST['submit'])) {
$con = new mysqli('localhost', 'root', '', 'research_phpEmailConfirmation');
$name = $con->real_escape_string($_POST['name']);
$email = $con->real_escape_string($_POST['email']);
$password = $con->real_escape_string($_POST['password']);
$cPassword = $con->real_escape_string($_POST['cPassword']);
if ($name == "" || $email == "" || $password != $cPassword)
$msg = "Please check your inputs!";
else {
$sql = $con->query("SELECT id FROM users WHERE email='$email'");
if ($sql->num_rows > 0) {
$msg = "Email already exists in the database!";
} else {
$token = 'qwertzuiopasdfghjklyxcvbnmQWERTZUIOPASDFGHJKLYXCVBNM0123456789!$/()*';
$token = str_shuffle($token);
$token = substr($token, 0, 10);
$hashedPassword = password_hash($password, PASSWORD_BCRYPT);
$con->query("INSERT INTO users (name,email,password,isEmailConfirmed,token)
VALUES ('$name', '$email', '$hashedPassword', '0', '$token');
");
include_once "PHPMailer/PHPMailer.php";
include_once "PHPMailer/Exception.php";
$mail = new PHPMailer();
$mail->setFrom('hello#codingpassiveincome.com');
$mail->addAddress($email, $name);
$mail->Subject = "Please verify email!";
$mail->isHTML(true);
$mail->Body = "aa";
if ($mail->send()) {
$msg = "You have been registered! Please verify your email!";
} else {
$msg = "Something wrong happened! Please try again!";
}
}
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Register</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
<div class="container" style="margin-top: 100px;">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3" align="center">
<img src="images/logo.png"><br><br>
<?php if ($msg != "") echo $msg . "<br><br>" ?>
<form method="post" action="register.php">
<input class="form-control" name="name" placeholder="Name..."><br>
<input class="form-control" name="email" type="email" placeholder="Email..."><br>
<input class="form-control" name="password" type="password" placeholder="Password..."><br>
<input class="form-control" name="cPassword" type="password" placeholder="Confirm Password..."><br>
<input class="btn btn-primary" type="submit" name="submit" value="Register">
</form>
</div>
</div>
</div>
</body>
</html>
I try to implement an sign in form based on webcam image, apparently, i don't errors in code, but information don't posted in database.
Here is my index with php code for insert information in database:
<?php
if (isset($_POST['desc'])) {
if (!isset($_POST['iscorrect']) || $_POST['iscorrect'] == "") {
echo "Sorry, important data to submit your question is missing. Please press back in your browser and try again and make sure you select a correct answer for the question.";
exit();
}
if (!isset($_POST['type']) || $_POST['type'] == "") {
echo "Sorry, there was an error parsing the form. Please press back in your browser and try again";
exit();
}
require_once("scripts/connect_db.php");
$name = $_POST['name'];
$email = $_POST['email'];
$name = mysqli_real_escape_string($connection, $name);
$name = strip_tags($name);
$email = mysqli_real_escape_string($connection, $email);
$email = strip_tags($email);
if (isset($_FILES['image'])) {
$name = $_FILES['image']['tmp_name'];
$image = base64_encode(
file_get_contents(
$_FILES['image']['tmp_name']
)
);
}
$sql = mysqli_query($connection, "INSERT INTO users (name,email,image) VALUES ('$name', '$email','$image')")or die(mysqli_error($connection));
header('location: index.php?msg=' . $msg . '');
$msg = 'merge';
}
?>
<?php
$msg = "";
if (isset($_GET['msg'])) {
$msg = $_GET['msg'];
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Licenta Ionut</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!-- font files -->
<link href='//fonts.googleapis.com/css?family=Muli:400,300' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Nunito:400,300,700' rel='stylesheet' type='text/css'>
<!-- /font files -->
<!-- css files -->
<link href="css/style.css" rel='stylesheet' type='text/css' media="all" />
<link href="web.js" rel='stylesheet' type='text/css' media="all" />
<script type="text/javascript" src="web.js"></script>
<!-- /css files -->
</head>
<body>
<p style="color:#06F;"><?php echo $msg; ?></p>
<h1>LogIn with Webcam Password</h1>
<div class="log">
<div class="content1">
<h2>Sign In Form</h2>
<form>
<input type="text" name="userid" value="USERNAME" onfocus="this.value = '';" onblur="if (this.value == '') {
this.value = 'USERNAME';
}">
<input type="password" name="psw" value="PASSWORD" onfocus="this.value = '';" onblur="if (this.value == '') {
this.value = 'PASSWORD';}">
<div class="button-row">
<input type="submit" class="sign-in" value="Sign In">
<input type="reset" class="reset" value="Reset">
<div class="clear"></div>
</div>
</form>
</div>
<div class="content2">
<h2>Register</h2>
<form action="index.php", name="index.php" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" value="Nume">
<input type="text" id="email" name="email" value="EmailAdress">
<br>
<script type="text/javascript" src="webcam.js"></script>
<script language="JavaScript">
document.write(webcam.get_html(320, 240));
</script>
<div class="button-row">
<input class="sign-in" type=button value="Configure" onClick="webcam.configure()" class="shiva">
<input class="reset" type="submit" value="Register" id="image" onClick="take_snapshot()" class="shiva">
</div>
</form>
</div>
<div class="clear"></div>
</div>
</body>
</html>
And here is the script for connection to database:
<?php
$db_host = "localhost";
// Place the username for the MySQL database here
$db_username = "Ionut";
// Place the password for the MySQL database here
$db_pass = "1993";
// Place the name for the MySQL database here
$db_name = "users";
// Run the connection here
$connection=mysqli_connect("$db_host","$db_username","$db_pass") or die (mysqli_connect_error());
mysqli_select_db($connection,"$db_name") or die ("no database");
?>
I don't find error in code and i need your advice/help!
Thank you for interest about my problem!
To solve a problem like this, break the problem into parts.
(1) First, what is the PHP file receiving? At the top of the PHP file, insert:
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
die('-----------------------------------');
(2) If that doesn't reveal the problem, next step is to duplicate the PHP file and in the second copy, HARD CODE the information you will be submitting at the top (replacing the PHP data that would normally be submitted):
<?php
$_POST['desc'] = 'TEST - Description';
$_POST['iscorrect'] = 'what it should be';
$_POST['type'] = 'TEST - Type';
etc
Then, run that modified file and see if the data is submitted.
(3) If that doesn't reveal the problem, keep working with the duplicate PHP file and add echo statements at various places to see where the file is breaking. For example:
$name = $_POST['name'];
$email = $_POST['email'];
$name = mysqli_real_escape_string($connection, $name);
echo 'HERE 01';
$name = strip_tags($name);
$email = mysqli_real_escape_string($connection, $email);
$email = strip_tags($email);
echo 'HERE 02';
if (isset($_FILES['image'])) {
$name = $_FILES['image']['tmp_name'];
$image = base64_encode(
file_get_contents(
$_FILES['image']['tmp_name']
)
);
}
echo 'HERE 03';
$sql = mysqli_query($connection, "INSERT INTO users (name,email,image) VALUES ('$name', '$email','$image')")or die(mysqli_error($connection));
echo 'HERE 04: $sql = ' .$sql;