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));
}
Related
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;
}
I understand that there is a way to insert a constant from select statement which i found the source from here such as:
INSERT INTO MyTable(ColA,ColB,ColC)
SELECT 1,colBB,colCC FROM MyTable2
But is it possible to add an user input values (using php) instead of a constant value as well? If possible provide with example. Thanks in advance.
UPDATED:
I tried to create a simple web page however there are some syntax error that i have no idea to solve it:
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\xampp\htdocs\webservice\result.php on line 10
Below are my codes:
<?php
//start a session
require("config.inc.php");
$username = $_SESSION["username"];
if(!empty($_POST)){
//check if user choose non-required drop down list
if(empty($_POST['subcategory'])){
if(empty($_POST['yearofstudy'])) {
$query = "INSERT INTO comments ( username, title, message, tousername )
SELECT :username, :title, :message, username
FROM utarstudents WHERE faculty = :faculty";
$query_params = array(
':faculty' => $_POST['category'],
':username' =>$username,
':title' =>$_POST['title'],
'message' =>$_POST['message']
);
}
else {
$query = "INSERT INTO comments ( username, title, message, tousername )
SELECT :username, :title, :message, username
FROM utarstudents WHERE faculty = :faculty AND year_of_study = :yearofstudy";
$query_params = array(
':faculty' => $_POST['category'],
'yearofstudy' => $_POST['yearofstudy'],
':username' =>$username,
':title' =>$_POST['title'],
'message' =>$_POST['message']
);
}
}
else {
if(empty($_POST['yearofstudy'])) {
$query = "INSERT INTO comments ( username, title, message, tousername )
SELECT :username, :title, :message, username
FROM utarstudents WHERE faculty = :faculty AND course = :course";
$query_params = array(
':faculty' => $_POST['category'],
':course' => $_POST['subcategory'],
':username' =>$username,
':title' =>$_POST['title'],
'message' =>$_POST['message']
);
}
else {
$query = "INSERT INTO comments ( username, title, message, tousername )
SELECT :username, :title, :message, username
FROM utarstudents WHERE faculty = :faculty AND year_of_study = :yearofstudy AND course = :course";
$query_params = array(
':faculty' => $_POST['category'],
'yearofstudy' => $_POST['yearofstudy'],
':course' => $_POST['subcetagory'],
':username' =>$username,
':title' =>$_POST['title'],
'message' =>$_POST['message']
);
}
}
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
}
Here is an edited code snippet of mine that accomplishes what you are trying to. So in my form file I have something like this for contributing to a project:
<form name="contribute" method="post" action="contribute-dbquery.php" onsubmit="return validateForm()">
First Name:
<input name="nameValue" type="text" size="40" maxlength="12" required/>
<input name="Submit" type="submit" value="Add"/>
</form>
So what it says is when Add is goto Tcontribute-dbquery.php with the value of nameValue. Then in my contribute-dbquery.php I assign nameValue from the form to $name and then assign inset it into my database. I assigned it to a variable because I used it on that page as well. You can inset it right into the database if you want.
$name = $_POST['nameValue'];
$insert_sql = "INSERT INTO mastertable (name) VALUES (' " . $name . " ')";
If this helps mark it as answered. Let me know if you need any help.
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");
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 ? )
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.