Insert and update same table with transactions - php

Since I can't/don't know how to auto_increment two columns in one table I trying to do this with transactions. This is what I trying
$pdo->beginTransaction();
try
{
$sql = "INSERT INTO users ( username, password, firstname, lastname, email, user_image, path)
VALUES (:username, :password, :firstname, :lastname, :email, :user_image, :path)";
$q = $pdo->prepare($sql);
$q->execute(array(
':username' => $username,
':password' => sha1($password),
':firstname' => $firstname,
':lastname' => $lastname,
':email' => $email,
':user_image' => $forDB,
':path' => $path,
));
$lastInsertID = $pdo->lastInsertId();
$sql = $pdo->prepare("INSERT INTO users (usertype)
VALUE (:user_id)");
$sql->execute(array(
':user_id' => $lastInsertID
));
$pdo->commit();
}
// any errors from the above database queries will be catched
catch (PDOException $e)
{
// roll back transaction
$pdo->rollback();
// log any errors to file
ExceptionErrorHandler($e);
exit;
}
So basically I want to insert in column usertype the ID of this record (user_id) both columns must be equal.
Now when I try with this .. it is save empty fields except for the usertype which is updated with lastInsertID

Change
$sql = $pdo->prepare("INSERT INTO users (usertype)
VALUE (:user_id)");
to this
$sql = $pdo->prepare("UPDATE users SET usertype=:user_id WHERE user_id=:user_id");

Related

Inserting values with a foreign key relationship into two different tables simultaneously? (MySQL)

So I have 2 tables:
users with columns id (primary, auto_increment), username, password, person_id (foreign key)
people with columns id (primary, auto_increment), first_name, last_name
What I'm trying to do is when registering a new account have a new row inserted into people and then have a new row inserted into users with the people.id as foreign key users.person_id.
Right now I have 2 php functions that get executed right after eachother, firstly one with this query:
insert into people (first_name, last_name) values (:firstname,
:lastname)
Secondly one with this query:
insert into users (username, password, person_id) values (:user,
:pass, LAST_INSERT_ID())
All of this works fine except for the fact that last_insert_id() keeps giving value 0 instead of the id from the previous query. Is it maybe not possible to use last_insert_id() when using 2 separate queries? If so what would be the best way to go about it then?
This is my relevant php code:
//make new person
$newPerson = new PeopleManagement();
$pm = $newPerson->createNewPerson($_POST["firstName"], $_POST["lastName"]);
//make new user
$newUsr = new Authentication();
$ac = $newUsr->registerNewUser($_POST["user"], $_POST["pass"]);
public function registerNewUser ($user, $pass) {
try {
$dbm = new PDO(DBCONFIG::$db_conn, DBCONFIG::$db_user, DBCONFIG::$db_pass);
$dbm->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbm->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
hash = password_hash($pass, PASSWORD_DEFAULT);
$sql = "insert into users (username, password, person_id) values (:user, :pass, LAST_INSERT_ID())";
$stmt = $dbm->prepare($sql);
$stmt->execute(array(
':user' => $user,
':pass' => $hash
));
$dbm = null;
} catch(PDOException $ex) {
return "Could not connect to database";
}
}
public function createNewPerson($firstName, $lastName) {
$dbm = new PDO($this->dbConn, $this->dbUser, $this->dbPass);
$sql = "insert into people (first_name, last_name) values (:firstname, :lastname)";
$stmt = $dbm->prepare($sql);
$stmt->execute(array(
':firstname' => $firstName,
':lastname' => $lastName
));
$dbm = null;
}

How to pass variable created in php to mysql database?

I'm working on an app. I've published a few apps, but I only have limited experience with PHP. This app uses a mysql database and a php script to pass data from the app to the database. I've figured out how to use POST to get data from the input fields in the app to the database, but for some reason I can't figure out how to pass a variable created in php to the database, i.e., without using POST.
The variable I'm having trouble with is a user_id variable. I'm going to create it within the registration.php script, which also passes the inputs from the app via POST. Here's the relevant portion of the code. Everything works except the user_id variable never makes it to the database (i.e., the column always shows '0').
EDIT: In the database, the user_id column is INT(11) type.
//I have a whole script prepared for creating the unique user_id, but to keep it simple for
// testing, I'm just using '0000000'.
// This part doesn't work.
$query = "INSERT INTO users (user_id) VALUES ('0000000')";
mysql_query($query);
// everything from here down works:
$query = "INSERT INTO users (username, password, email, firstname, lastname) VALUES ( :user, :pass, :email, :firstname, :lastname)";
$query_params = array(
':user' => $_POST['username'],
':pass' => $_POST['password'],
':email' => $_POST['email'],
':firstname' => $_POST['firstName'],
':lastname' => $_POST['lastName'],
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Failed to run query: " . $ex->getMessage();
die(json_encode($response));
}
mysql_query is not part of the PDO class that you use in your working code below.
Use the PDO class to execute that statement too.
$query = "INSERT INTO users (user_id) VALUES (:uid)";
$query_params = array(
':uid' => '0000000'
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Failed to run query: " . $ex->getMessage();
die(json_encode($response));
}
It's also curious why you say that you're inserting '000000' and the result is always 0 - this makes sense.
For anyone with the same problem, the comments and responses were right... I had two problems. First, '0000000' is treated as '0' when dealing with an INT datatype (DUH!), so of course my database was always receiving '0'. Second, mysql_query is not part of the PDO class I was using. I revised the code and now it works:
$userid = '1';
$query = "INSERT INTO users (username, password, email, firstname, lastname, user_id) VALUES ( :user, :pass, :email, :firstname, :lastname, :uid)";
$query_params = array(
':user' => $_POST['username'],
':pass' => $_POST['password'],
':email' => $_POST['email'],
':firstname' => $_POST['firstName'],
':lastname' => $_POST['lastName'],
':uid' => $userid
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Failed to run query: " . $ex->getMessage();
die(json_encode($response));
}

How to insert data into nested tables through PHP?

I think this is something related to PDO.
this is my patientinfo table
patientid | name | age | email | address
and this is my remarks tables
patientid | remarksid | date | description
I'd like to INSERT data to the patientinfo and to the remarks table where patientid of both tables will be synchronized. The problem is I dont know how to query this. This is what I do but it gives me an error.
$query = "INSERT INTO patientinfo (name, age, email, address)
VALUES (:name, :age, :email, :address);";
$query_params = array(
':name' => $_POST['name'],
':age' => $_POST['age'],
':email' => $_POST['email'],
':address' => $_POST['address'],
);
$query = "INSERT INTO remarks (patient_id, description) VALUES (:patient_id, :remarks) WHERE remarks.patient_id = patientinfo.patient_id;";
$query_params = array(':remarks' => $_POST['remarks']);
try{
$stmt = $dbname->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
$response["success"] = 0;
$response["message"] = $ex ;
die(json_encode($response));
}
i made patientid in the patientinfo AUTOINCREMENT.
PLEASE! THANK YOU SO MUCH FOR YOUR HELP!
$query = "INSERT INTO patientinfo (name, age, email, address)
VALUES (:name, :age, :email, :address);";
$query_params = array(
':name' => $_POST['name'],
':age' => $_POST['age'],
':email' => $_POST['email'],
':address' => $_POST['address'],
);
try{
$stmt = $dbname->prepare($query);
$stmt->execute($query_params);
$patient_id = $dbname->lastInsertId();
$query = "INSERT INTO remarks (patientid, description) VALUES (:patient_id, :remarks)";
$query_params = array(':remarks' => $_POST['remarks'],':patient_id'=>$patient_id);
$q = $dbname->prepare($query);
$q->execute($query_params);
}catch(PDOException $ex){
$response["success"] = 0;
$response["message"] = $ex ;
die(json_encode($response));
}
You should write something like that. Check column names please(patientid or patient_id ? )

PDO prepare statement for inserting array into db issue

I am creating a user registration system using PDO, and am attempting to insert the users form data into a database table. Very simple, however the wrong value is entered into the database. The values entered into the database are :username, :password, :email_address, :city, etc, rather than the value passed to the function from my form. Any idea as to what I am doing wrong? I tried using bindParam and bindValue but had similar results, and based on other posts I concluded that using an array is the best way to do it. help!
function add_user($username, $password, $email, $fName, $lName, $address, $city, $state, $zip, $phone ) {
global $db;
$sql = "INSERT INTO alumni_user_info
(username, password, email_address, first, last, address, city, state, zip_code, phone)
VALUES
(':username', ':password', ':email_address', ':first', ':last', ':address', ':city', ':state', ':zip_code', ':phone')";
$sth = $db->prepare($sql);
$result = $sth -> execute(array(':username' => $username, ':password' => $password, ':email_address' => $email, ':first' => $fName, ':last' => $lName, ':address' => $address, ':city' => $city, ':state' => $state, ':zip_code' => $zip, ':phone' => $phone));
if ($sth->execute()) {
$success = "Registration successful";
return $success;
} else {
var_dump($result->errorInfo());
$success = "Registration failed";
return $success;
}
Do not use quotes for parameters. It will be escaped because you're binding parameters already.
$sql = "INSERT INTO alumni_user_info
(username, password, email_address, first, last, address, city, state, zip_code, phone)
VALUES
(:username, :password, :email_address, :first, :last, :address, :city, :state, :zip_code, :phone)";
If you do something like this ':username' PDO will treat it as string.

Database returning false, cant figure out where i went wrong?

I am sorry to bother you with such a newbie question, and thank you for taking the time to go over it and answer it.
function dbaddusr($username, $email, $password){
try{
$conn = new PDO(CONNECTDATA);
$stmt = $conn->prepare("INSERT INTO 'users' ('username', 'email', 'password') VALUES (:username, :email, :password)");
$pass = crypt($password);
$result = $stmt->execute(array("username" => $username, "email" => $email, "password" => $pass));
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
return false;
}
}
Problem is, $result is always false. (I discovered this by some simple var_dump statements inside the try block.
I am very new to this and your help on fixing it is highly appreciated.
Don't quote the column names, if you want, use the backticks `
INSERT INTO users (username, email, password) VALUES (:username, :email, :password)
Change quotes to backticks for table & column name in your query,
$stmt = $conn->prepare("INSERT INTO `users` (`username`, `email`, `password`) VALUES
(:username, :email, :password)");
You are passing $pass in your array and your function accepts $password
Check your error messages to get specific details and you will find the problem.
A non-bloated version with all useless and wrong code cleaned.
function dbaddusr($username, $email, $password){
global $conn;
$sql = "INSERT INTO users (username, email, password) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
$pass = crypt($password);
$stmt->execute(array($username, $email, $pass));
}
You have to connect ONCE per application, and then use that single connection all the way.

Categories