Well, I'm creating a registration system for my website but I'm having trouble executing my query. I've tried to troubleshoot the problem, but I've had no success. Kind of confused :(
Here is my code:
public function registerUser($username, $password, $email) {
global $core;
if(empty($username) || empty($password) || empty($email)) {
throw new Exception ('A required field was left blank');
} else {
//SQL Query Data
$data['username'] = $username;
$data['password'] = $core->encrypt($password);
$data['email'] = $email;
$data['userKey'] = rand(999999, 100000);
$data['ip'] = $_SERVER['REMOTE_ADDR'];
$data['date'] = time();
//SQL Query
$sql = "INSERT INTO `u_userdata` ('user-key', 'username', 'password', 'email', 'register-ip', 'register-date') VALUES (:userKey, :username, :password, :email, :ip, :date)";
$STH = $this->DBH->query($sql);
$STH->execute($data);
}
}
and here is the error I'm getting:
Fatal error: Call to a member function execute() on a non-object in C:\xampp\htdocs\community\inc\user.inc.php on line 33
I'm guessing it's an error with the query, but I'm not sure what!
I think you have got PDO::prepare() mixed up with PDO::query():
It should be either:
$result = $this->DBH->query($sql);
Or:
$STH = $this->DBH->prepare($sql);
$STH->execute($data);
From the docs:
PDO::query() executes an SQL statement in a single function call,
returning the result set (if any) returned by the statement as a
PDOStatement object.
You would normally use PDO::prepare() if you are going to issue the same statement repeatedly, or if you need to bind parameters. As far as I am aware, it is not possible to bind parameters to your query prior to using PDO::query().
Note that with PDO::prepare() you can either use PDOStatement::bindParam() to bind parameters prior to calling PDOStatement->execute(), or you can pass the parameters as an array to PDOStatement->execute().
You also need to prefix your array keys with a colon. So the final result would be:
$data[':username'] = $username;
$data[':password'] = $core->encrypt($password);
$data[':email'] = $email;
$data[':userKey'] = rand(999999, 100000);
$data[':ip'] = $_SERVER['REMOTE_ADDR'];
data[':date'] = time();
//SQL Query
$sql = "INSERT INTO `u_userdata` ('user-key', 'username', 'password', 'email', 'register-ip', 'register-date') VALUES (:userKey, :username, :password, :email, :ip, :date)";
$STH = $this->DBH->prepare($sql);
$STH->execute($data);
You should use ` quote instead of ' in insert query.
"INSERT INTO u_userdata (user-key, username, password, email, register-ip, register-date) VALUES (:userKey, :username, :password, :email, :ip, :date)
the query() function executes the sql statement. you should use the prepare() function.
i'm assuming that you are using pdo, because of the pdo tag
$data[':username'] = $username;
$data[':password'] = $core->encrypt($password);
$data[':email'] = $email;
$data[':userKey'] = rand(999999, 100000);
$data[':ip'] = $_SERVER['REMOTE_ADDR'];
$data[':date'] = time();
//SQL Query
$sql = "INSERT INTO `u_userdata` ('user-key', 'username', 'password', 'email', 'register-ip', 'register-date') VALUES (:userKey, :username, :password, :email, :ip, :date)";
$stmt = $this->DBH->prepare($sql);
$stmt->execute($data);
Related
I have researched it a lot online and spent a lot of time trying to fix this problem.
My code
function createNewAccount() {
global $response;
global $conn;
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
}
the error I get is
Warning: mysqli::prepare(): Couldn't fetch mysqli in
C:\xampp\htdocs\authentication\register.php on line 105
Fatal error: Uncaught Error: Call to a member function bind_param() on
null in C:\xampp\htdocs\authentication\register.php:106 Stack trace:
#0 C:\xampp\htdocs\authentication\register.php(139): createNewAccount() #1 {main} thrown in
C:\xampp\htdocs\authentication\register.php on line 106
I cant seem to find any solution. Any help is highly appreciated.
PHP Variables need to be set before using them:
function createNewAccount() {
global $response; // If you dont need this remove it
global $conn;
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
$stmt->execute();
}
<?php
// DATABASE-HOSTNAME-OR-IPADDRESS-GOES-HERE
// MYSQL-DBNAME-GOES-HERE
class LoginHandler {
public $dbHostname = 'localhost';
public $dbDatabaseName = 'employee101';
public $user = 'root';
public $password = 'root';
public function handleRequest($arg) {
$username = '123';
$password2 = '123';
$fname = 'John';
$lname = 'Doe';
$age = '18';
if ( ! $username ) {
$this->fail();
return;
}
try {
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$sql="SELECT * FROM `employee_data` WHERE `username`='$username'";
$stmt = $pdo->query($sql);
if ( $stmt === false ) {
echo "DB Critical Error";
return;
}
elseif ( $stmt->rowCount() > 0 ) {
echo "user already exists";
return;
}
else {
echo "User created";
$sql = "INSERT INTO employee_data (name, sumame, age, username, password)
VALUES ($fname, $lname, $age, $username, $password2)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam($fname, $_POST[$fname], PDO::PARAM_STR);
$stmtz->bindParam($lname, $_POST[$lname], PDO::PARAM_STR);
$stmtz->bindParam($age, $_POST[$age], PDO::PARAM_STR);
$stmtz->bindParam($username, $_POST[$username], PDO::PARAM_STR);
$stmtz->bindParam($password2, $_POST[$password2], PDO::PARAM_STR);
$resultzzx = $stmtz->execute();
return;
}
}
catch(PDOException $e) {
$this->log('Connection failed: ' . $e->getMessage());
echo "DB Critical Error";
}
}
function log($msg) {
file_put_contents("login.log", strftime('%Y-%m-%d %T ') . "$msg\n", FILE_APPEND);
}
}
$handler = new LoginHandler();
$handler->handleRequest($_POST);
?>
When attempting to use this script above, I get the echo that the user was created, but even when refreshing the table, the new entry doesn't show up.
Now, if i change the values line to be the following, it will work and show the new entry.
('John', 'Doe', '18', $username, $password2)";
What am i doing wrong? I need the first name, last name and age entries to not be concrete, as i will be obtaining them from a POST on my android device. The whole purpose of this script is to create the user and it's records if it doesn't already exist.
You have various mistakes.
1) You are not binding your parameters correctly. To bind them correctly, you place a :variablename in the position you want to include the variable. Usually the "variablename" should be the same as the one you are obtaining from the $_POST superglobal so that the code is cleaner and more readable.
2) You are not obtaining the values from the $_POST superglobal correctly. The key values you place inside are strings, and by placing an empty $fname variable, you are not going to obtain a correct result. It would only work if you had coding saying $fname = 'fname' somewhere up top hidden from us, however that code itself would be unadvised since it is unnecessary and only makes the source code larger.
$sql = "INSERT INTO employee_data (name, sumame, age, username, password)
VALUES (:fname, :lname, :age, :username, :password2)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host=
{$this>dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam(':fname', $_POST['fname']);
$stmtz->bindParam(':lname', $_POST['lname']);
$stmtz->bindParam(':age', $_POST['age']);
$stmtz->bindParam(':username', $_POST['username']);
$stmtz->bindParam(':password2', $_POST['password2']);
I hope that helps.
$sql = "INSERT INTO employee_data (name, sumame, age, username, password) VALUES (:name, :sumame, :age, :username, :password)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam(':name', $fname);
$stmtz->bindParam(':sumame', $lname);
$stmtz->bindParam(':age', $age);
$stmtz->bindParam(':username', $username);
$stmtz->bindParam(':password', $password2);
$resultzzx = $stmtz->execute();
return;
After reviewing the link Fred posted in the comment above, i've modified it to work fine, thanks.
I did some research around and I found two ways to prepared my statements from PDO object. But it seems like both are not working at all. I am missing something?
Named placeholders
$email = 'my_email';
$code = 'my_private_code';
$pdo = new PDO('mysql:host=personal_info;dbname=personal_info', 'personal_info', 'personal_info');
$sql = "UPDATE `promo` SET code = :code WHERE email = :email";
$st = $pdo->prepare($sql);
$st->execute(array(
':code' => $code,
':email' => $email
));
Unamed placeholders
$pdo = new PDO('mysql:host=personal_info;dbname=personal_info', 'personal_info', 'personal_info');
$st = $pdo->prepare("INSERT INTO promo (`email`, `code`) VALUES (?, ?)");
$st->bindParam(1, $email);
$st->bindParam(2, $code);
$email = 'my_email#hotmail.com';
$code = 'my_private_code';
$st->execute();
I have followed some tutorial and I can't understand why this doesn't work.
I have a class Users. It gets a DB connection in the __construct method. Next I have a Create method, that needs to create a user by inserting some data in the table, but it does not execute. I think I have problem with the bindParam function or with MySQL insert code.
I have following error:
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\www\samodel\object\users.php on line 44
Please help me to solve this problem if you know how, Thank you:
<?php
//Was Products, now Users
class Users{
// database connection and table name
private $conn;
private $table_name = "users";
// object properties
public $id;
public $username;
public $first_name;
public $last_name;
public $email;
public $password;
public function __construct($db){
$this->conn = $db;
}
// create user
function create(){
//write query
$query = "INSERT INTO
" . $this->table_name . "
SET
username = ?, first_name = ?, last_name = ?";
$stmt = $this->conn->prepare($query);
$stmt->bindParam("username", $this->username);
$stmt->bindParam("first_name", $this->first_name);
$stmt->bindParam("last_name", $this->last_name);
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
?>
You are mixing two techniques here - you are preparing the statement with positional placeholders, but binding according to names - you should pick one and stick to it.
With positional placeholders:
$query = "INSERT INTO
" . $this->table_name . "
SET
username = ?, first_name = ?, last_name = ?";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->username);
$stmt->bindParam(2, $this->first_name);
$stmt->bindParam(3, $this->last_name);
With named placeholders:
$query = "INSERT INTO
" . $this->table_name . "
SET
username = :username, first_name = :first_name, last_name = :last_name";
$stmt->bindParam("username", $this->username);
$stmt->bindParam("first_name", $this->first_name);
$stmt->bindParam("last_name", $this->last_name);
I think you have bad sql
try
$query = "INSERT INTO {$this->table_name} (username, first_name, last_name) VALUES (:username, :first_name, :last_name)";
I am trying to submit data from a form and have the data be inserted into my database using PDO. I am unsure what i am doing wrong at this point and could use any help that i can get.
Here is the code for connecting to my db
<?php
function connect(){
$config = array(
'$username' => 'root',
'$password' => 'root'
);
try {
$conn = new PDO('mysql:host=localhost;dbname=data', $config['$username'], $config['$password']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'COME GET SOME IT WORKED!!!!';
}
catch(PDOException $e) {
print "Error!";
exit;
}
}
?>
Here is the code for handling the form data
<?php
// We will include connection file first
include('functions.php');
connect();
// check if varaibable is set and Add Rate Button pressed.
if(isset($_POST["submit"])){
echo 'COME GET SOME';
// Define Variables
$firstname = $_POST[firstName]; //firstName
$lastname = $_POST[lastName]; //LastName
$email = $_POST[emailAddress]; //Email Address
$age = $_POST[age]; //Age
// We Will prepare SQL Query
$STM = $dbh->prepare("INSERT INTO 'EmailList'(id, firstName, lastName, emailAddress, age) VALUES (NULL, :firstname, :lastname, :email, :age)");
// bind paramenters, Named parameters always start with colon(:)
$STM->bindParam(':firstname', $firstname);
$STM->bindParam(':lastname', $lastname);
$STM->bindParam(':email', $email);
$STM->bindParam(':age', $age);
// For Executing prepared statement we will use below function
$STM->execute();
// We use header here for redirecting it to other page where we will show success message.
header( "location:index.php");
}
?>