How to insert data into nested tables through PHP? - 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 ? )

Related

Query conditions to insert data from a form

What I'm trying to do is:
If the age input in my form = 28, 30, 25 or 21 then I want to auto insert value 8 in the column (VE), else keep it empty. Is this the right way to do that?
if($form_data->action == 'Insert')
{
$age=array(28, 30, 25, 21);
$age_str=implode("','", $age);
if($form_data->age == $age_str){
$query="INSERT INTO tbl
(VE) VALUE ('8') WHERE id= '".$form_data->id."'
";
$statement = $connect->prepare($query);
$statement->execute();
}
$data = array(
':date' => $date,
':first_name' => $first_name,
':last_name' => $last_name,
':age' => $age
);
$query = "
INSERT INTO tbl
(date, first_name, last_name, age) VALUES
(:date, :first_name, :last_name, :age)
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
$message = 'Data Inserted';
}
}
Also, how do I insert the new row with the row id from the other form data going into tbl?
Use php's in_array instead of trying to compare a string. To get the id of the query where you insert the form data, you can return the id of the insert row from your prepared statement.
if ($form_data->action == 'Insert') {
// assuming $age, $date, $first_name, $last_name
// already declared prior to this block
$data = array(
':date' => $date,
':first_name' => $first_name,
':last_name' => $last_name,
':age' => $age
);
$query = "
INSERT INTO tbl
(date, first_name, last_name, age) VALUES
(:date, :first_name, :last_name, :age)
";
$statement = $connect->prepare($query);
if ($statement->execute($data)) {
$message = 'Data Inserted';
// $id is the last inserted id for (tbl)
$id = $connect->lastInsertID();
// NOW you can insert your child row in the other table
$ages_to_insert = array(28, 30, 25, 21);
// in_array uses your array...so you don't need
// if($form_data->age == $age_str){
if (in_array($form_data->age, $ages_to_insert)) {
$query="UPDATE tbl SER VE = '8' WHERE id= '".$id."'";
$statement2 = $connect->prepare($query);
$statement2->execute();
}
}
}

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));
}

SQL database insert with select

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.

Insert and update same table with transactions

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");

Issues with Parameters

I've been trying out my PHP skills and it seems when I try to send out the information from my Android app to the PHP, it seems to send just the parameter names(The database shows :Lname as an example.) out to the database. We are using PDO as the way to communicate with the MySQL Database.
Here is the coding as follows:
$query = "INSERT INTO Customer ( Lname, Fname, Address, City, State, ZIP, Phone, myusername, mypassword ) VALUES ( ':Lname', ':Fname', ':Address', ':City', ':State', ':ZIP', ':Phone', ':myusername', ':mypassword')";
//Again, we need to update our tokens with the actual data:
$query_params = array(
':Lname' => $_POST['LName'],
':Fname' => $_POST['FName'],
':Address' => $_POST['Address'],
':City' => $_POST['City'],
':State' => $_POST['State'],
':ZIP' => $_POST['ZIP'],
':Phone' => $_POST['Phone'],
':myusername' => $_POST['username'],
':mypassword' => $_POST['password']
);
//time to run our query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
$response["message"] = $ex->getMessage();
die(json_encode($response));
}
You have included literal values in your query string.
$query = "INSERT INTO Customer ( Lname, Fname, Address, City, State, ZIP, Phone, myusername, mypassword )
VALUES ( ':Lname', ':Fname', ':Address', ':City', ':State', ':ZIP', ':Phone', ':myusername', ':mypassword')";
should be
$query = "INSERT INTO Customer ( Lname, Fname, Address, City, State, ZIP, Phone, myusername, mypassword )
VALUES ( :Lname, :Fname, :Address, :City, :State, :ZIP, :Phone, :myusername, :mypassword)";
You need to remove the quotes from your SQL values, as its being interpreted as literal strings. If you remove them, you should be all good :)
$query = "INSERT INTO Customer ( Lname, Fname, Address, City, State, ZIP, Phone, myusername, mypassword ) VALUES ( ':Lname', ':Fname', ':Address', ':City', ':State', ':ZIP', ':Phone', ':myusername', ':mypassword')";

Categories