// Insert the new user into the database
// This WORKS, and was copied from an example
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: MEMBER. Please contact the developer.');
}
$insert_stmt->close();
// If user inserted, add place with user as owner
// This DOESN'T work, and was added by me
//$ownerid = $mysqli->lastInsertId();
$placename = $_POST['placename'];
$placename = mysqli_real_escape_string($mysqli, $placename);
$location = $_POST['autocomplete'];
$location = mysqli_real_escape_string($mysqli, $location);
if ($place_stmt = $mysqli->prepare("INSERT INTO places (member_owner, location, name) VALUES (?, ?, ?)")) {
$place_stmt->bind_param('iss', 1, $location, $placename);
if (! $place_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: PLACE. Please contact the developer.');
}
}
$place_stmt->close();
}
header('Location: ./register_success.php');
I can confirm that the 2 variables $location and $placename are successfully retrieved. The result I get from running this code is that the members table is successfully updated, but the places table is not and the script dumps me into a blank HTML.
I figured out that bind_param doesn't like to accept hard-coded values. I was trying to "test" my code by inserting a value of 1 into a column before I messed around with trying to get the last inserted ID. The error reporting suggested by Fred really helped (as did other suggestions, as you can see I've implemented).
The altered code:
// Insert the new user into the database
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
header('Location: ./error.php?err=Registration failure: MEMBER. Please contact the developer.');
exit;
}
$insert_stmt->close();
// If user inserted, add place with user as owner
$ownerid = $mysqli->insert_id;
if ($place_stmt = $mysqli->prepare("INSERT INTO places (member_owner, location, name) VALUES (?, ?, ?)")) {
$place_stmt->bind_param('iss', $ownerid, $location, $placename);
if (! $place_stmt->execute()) {
header('Location: ./error.php?err=Registration failure: PLACE. Please contact the developer.');
exit;
}
}
$place_stmt->close();
header('Location: ./register_success.php');
}
Thanks for all the help!
Related
I have this register form but I have an error in it.
Under the register form it appears this code:
document.write = 'Account created';";{ else { echo 'Error :('; } } ?>
and this is the entire code from it:
if ($db=query("INSERT INTO prof
(username,email,fname,lname,country,password)
VALUES ('$username','$email','$fname','$lname','$country','$password')"))
print "<script>document.write = ('Account created');</script>";
{
else {
echo 'Error :(';
}
}
?>
how can I solve the issue?
You have syntax errors and your code is vulnerable to Sql Injections.
Using PDO, your code should be something like that:
$sql = "INSERT INTO prof (username, email, fname, lname, country, password) VALUES (?, ?, ?, ?, ?, ?)";
$stmt= $pdo->prepare($sql);
$insert = $stmt->execute([$username, $email, $fname, $lname, $country, $password]);
if ($insert) {
print "<script>document.write = ('Account created');</script>";
} else {
echo 'Error :(';
}
I have a register PHP function that registers a user like so
//Function to create a new user
public function register($firstName, $lastName, $email, $state, $city, $password, $zipCode, $isHMan, $skills, $experience)
{
$password = md5($password);
$stmt = $this->conn->prepare("INSERT INTO handyman(firstName, lastName, email, state, city, password, zipCode, isHMan, skills, experience) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssssss", $firstName, $lastName, $email, $state, $city, $password, $zipCode, $isHMan, $skills, $experience);
$result = $stmt->execute();
$stmt->close();
if ($result) {
return true;
} else {
return false;
}
}
This function works perfectly when called and everything is inserted into my handyman table (including the md5 hashed password). My problem is with my login function. This is the function:
public function login($email, $password) {
$password1 = md5($password);
$stmt = $this->conn->prepare("SELECT * FROM `handyman` WHERE email = ? AND password = ?");
$stmt->bind_param("ss", $email, $password1);
$result = $stmt->execute();
$stmt->close();
if (mysqli_num_rows($result) != 0) {
echo "results acquired";
return true;
} else {
echo "no results";
return false;
}
}
When I run this I get this warning:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result,
boolean given.
And the program outputs no results.
After doing a search here on stackoverflow, people were saying that this is caused by an error in the SQL query and the $result variable actually is returning a false boolean value. I input the query directly into my database with an email and password from my database and it executed perfectly. I cannot for the life of me figure out what is wrong. My values and SQL query seem to be correct. I am guessing it may have something to do with the bind_param function but I don't know what. Any help would be appreciated.
You have mixed procedural style mysqli functions with object oriented.
You'll need to adjust that code you have to this:
public function login($email, $password) {
$password1 = md5($password); // don't do this btw
$stmt = $this->conn->prepare("SELECT * FROM `handyman` WHERE email = ? AND password = ?");
$stmt->bind_param("ss", $email, $password1);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows != 0) {
echo "results acquired";
return true;
} else {
echo "no results";
return false;
}
}
Note: In order to check num_rows you need to have called store_result first.
You also need to alter your register method too since its looking at a failure bool from execute:
public function register($firstName, $lastName, $email, $state, $city, $password, $zipCode, $isHMan, $skills, $experience)
{
$password = md5($password); // ahem .. no
$stmt = $this->conn->prepare("INSERT INTO handyman(firstName, lastName, email, state, city, password, zipCode, isHMan, skills, experience) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssssss", $firstName, $lastName, $email, $state, $city, $password, $zipCode, $isHMan, $skills, $experience);
$stmt->execute();
$stmt->store_result();
if ($stmt->affected_rows) {
return true;
} else {
return false;
}
}
Note: Using affected_rows also needs store_result to be called. Don't check on the bool result of execute since that is used for failures in sql.
PASSWORDS:
Please look into password_hash() and password_verify() for your storage and login procedures. md5 is insecure, and out dated. Its beyond the scope of this Q/A to provide the full working usage of those functions. Please do look into them though.
I have a wamp server setup. It works perfectly :)
I then entered phpMyAdmin and created a table. With an android app I have made, I would like to insert a record in my database. The android (java) code is correct, I'm 100% sure of that. When I create a record though, it doesn't work.
Since I don't know PHP very well at all I assume my mistake lies somewhere in Register.php
Here is the file:
Any insight into what my problem is would be fantastic!
Please note that I am using my correct public ip in the true file. I just entered a random one for the code below. Also, I have created a user with permissions required (in the place of username and password). The database "database" also DOES exist.
Register.php
$con = mysqli_connect("http://148.12.0.153:3306","username","password", "database");
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$phone = $_POST["phone"];
$balance = $_POST["balance"];
$NameAndSurname = $_POST["NameAndSurname"];
$DateOfBirth = $_POST["DateOfBirth"];
$SchoolName = $_POST["SchoolName"];
$Gender = $_POST["Gender"];
$Grade = $_POST["Grade"];
$Class = $_POST["Class"];
$Country = $_POST["Country"];
$Province = $_POST["Province"];
$Address = $_POST["Address"];
$City = $_POST["City"];
$PostalCode = $_POST["PostalCode"];
$statement = mysqli_prepare($con, "INSERT INTO users (username, email, password, phone, balance, NameAndSurname, DateOfBirth, SchoolName, Gender, Grade, Class, Country, Province, Address, City, PostalCode) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssssisssiisssssi", $username, $email, $password, $phone, $balance, $NameAndSurname, $DateOfBirth, $SchoolName, $Gender, $Grade, $Class, $Country, $Province, $Address, $City, $PostalCode);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
mysqli_close($con);
Ok a number of things to mention here.
First you are using the android app to launch this Register.php script on your Apache server, just like it was a web page, so this script is running on the server and not your phone or tablet. Therefore Apache and MySQL and the script are all running on the WAMPServer PC. So your connection string does not need some real ip address, it can use and should use something like localhost or 127.0.0.1
Next your database access code is assuming everything will just happen correctly and this may not be the case see above paragraph. So always check status codes and report back the status's to the calling program so it can make sensible decisions about what to do next. Its also a good idea to log errors to the PHP Error log, so when this goes live you can check logs and see if anything is going wrong without needing to run the phone app.
So try these changes :
// init the reply class
$result = new stdClass();
$result->status = 'OK';
$con = mysqli_connect("127.0.0.1","username","password", "database");
if ( ! $con ) {
$result->status = 'ERROR';
$result->error_code = mysqli_connect_errno();
$result->error_message = mysqli_connect_error();
// terminate and report to error log
error_log('Database connection failed'.mysqli_connect_error(), 0);
echo json_encode($result); // return status as json
exit;
}
// You should never use data sent from the screen without
// validating it and cleaning it up so you need some sort of
// $_POST = validate_sanity($_POST);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$phone = $_POST["phone"];
$balance = $_POST["balance"];
$NameAndSurname = $_POST["NameAndSurname"];
$DateOfBirth = $_POST["DateOfBirth"];
$SchoolName = $_POST["SchoolName"];
$Gender = $_POST["Gender"];
$Grade = $_POST["Grade"];
$Class = $_POST["Class"];
$Country = $_POST["Country"];
$Province = $_POST["Province"];
$Address = $_POST["Address"];
$City = $_POST["City"];
$PostalCode = $_POST["PostalCode"];
$sql = "INSERT INTO users
(username, email, password, phone,
balance, NameAndSurname, DateOfBirth,
SchoolName, Gender, Grade, Class,
Country, Province, Address, City,
PostalCode)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$statement = mysqli_prepare($con, $sql );
if ( ! $statement ) {
$result->status = 'ERROR';
$result->error_code = mysqli_errno();
$result->error_message = mysqli_error();
// terminate and report to error log
error_log('Database connection failed'.mysqli_error(), 0);
echo json_encode($result); // return status as json
exit;
}
$res = mysqli_stmt_bind_param($statement, "ssssisssiisssssi",
$username, $email, $password, $phone, $balance,
$NameAndSurname, $DateOfBirth, $SchoolName, $Gender,
$Grade, $Class, $Country, $Province, $Address, $City,
$PostalCode);
if ( ! $res ) {
$result->status = 'ERROR';
$result->error_code = mysqli_errno();
$result->error_message = mysqli_error();
// terminate and report to error log
error_log('Database connection failed'.mysqli_error(), 0);
echo json_encode($result); // return status as json
exit;
}
if ( mysqli_stmt_execute($statement) ) {
$result->status = 'OK';
$result->message = 'Row deleted';
echo json_encode($result); // return status as json
exit;
} else {
$result->status = 'ERROR';
$result->error_code = mysqli_errno();
$result->error_message = mysqli_error();
// terminate and report to error log
error_log('Database DELETE failed'.mysqli_error(), 0);
echo json_encode($result); // return status as json
exit;
}
//mysqli_close($con);
//PHP will do all the connection and statment closing automatically
// So you dont actually need to do any of this unless you are running
// a script the will consume large numbers of statement and you may
// feel it necessary to close them out to kepp the memory footprint smaller
Change the mysqli_stmt_close to
mysqli_stmt_close($statement) or die(mysqli_error());
This will give you a more precise error as to why this is failing.
I am using php to create the user accounts on server database.I have used prepare statement to create user account.I want to know how can i close my sql connection using prepare statement or i don't need to close the connections? Is it done automatically.
Here is my code
public function createUser($name, $email, $password,$file_path,$phone,$address,$profession,$language)
{
$response = array();
// First check if user already existed in db
if (!$this->isUserExists($email)) {
// Generating API key
$api_key = $this->generateApiKey();
// insert query
$stmt = $this->conn->prepare("INSERT INTO users(name, email, password, api_key,profile_pic,phone,address,profession,language,date) values(?, ?, ?, ?, ?, ?, ?, ?,?,now())");
$stmt->bind_param("sssssssss", $name, $email, $password, $api_key,$file_path,$phone,$address,$profession,$language);
$result = $stmt->execute();
$stmt->close();
// Check for successful insertion
if ($result)
{
// User successfully inserted
return USER_CREATED_SUCCESSFULLY;
}
else
{
// Failed to create user
return USER_CREATE_FAILED;
}
}
else
{
// User with same email already existed in the db
return USER_ALREADY_EXISTED;
}
return $response;
}
I am new to php so i don't have any idea about this.
$stmt->close();
is enough .
check this
http://www.w3schools.com/php/php_mysql_prepared_statements.asp
$stmt->close(); // Closes the prepared statement
$this->conn->close(); // Closes the mysql connection
I'm doing, or trying to do, a database project for the university, but when registering a user this error appears:
Fatal error: Call to a member function bind_param() on a non-object in (...)
Initially I wrote
$insert = $db->prepare("INSERT INTO customer (name, email, phonenumber, adress, password) VALUES (?, ?, ?, ?, ?");
But then I changed to well, you can see in the code.
<?php
require 'db/connect.php';
require 'functions/security.php';
if(!empty($_POST)) {
if(isset($_POST['name'], $_POST['email'], $_POST['address'], $_POST['phone'], $_POST['password'])) {
$name = trim($_POST['name']);
$email `enter code here` = trim($_POST['email']);
$phone = trim($_POST['phone']);
$address = trim($_POST['address']);
$password = trim($_POST['password']);
if(!empty($name) && !empty($email) &&!empty($phone) && !empty($address) &&!empty($password)){
$insert = $db->prepare("INSERT INTO customer VALUES (?, ?, ?, ?, ?");
$insert->bind_param('ssiss', $name, $email, $phone, $address, $password);
//$insert->close();
if($insert->execute()){
print_r("Done");
die();
}
}
}
}
?>
Call to a member function in query's means that the query couldn't get executed because it contains an error.
In this case, you didn't closed the VALUES ().
Change $insert = $db->prepare("INSERT INTO customer VALUES (?, ?, ?, ?, ?"); to $insert = $db->prepare("INSERT INTO customer VALUES (?, ?, ?, ?, ?)");
Make sure you do check if an error could get executed.
Example of checking if an query could get executed:
$query = $this->_db->prepare("SELECTTEST name FROM user"); //.. Bad query (false)
if(!$query) //.. If the query is false.
{
trigger_error('Query couldn\'t get executed');
}
If this solved your error, I will really appreciate that you vote my answer as answer.