SQL database insert with select - php

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.

Related

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

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

SQL Selecting Data with WHERE ". $variable ."

my question is:
I have an issue with my code (SELECTING data from MySql)
This is my code
<?php
$user_name = $_SESSION['user_name'];
$user_email = $_SESSION['user_email'];
echo $user_email;
$con = mysqli_connect("localhost", "root", "", "minehelp");
$id_query = mysqli_query($con, "SELECT user_name FROM users_en WHERE user_name = '" . $user_name . "' OR user_email = '" . $user_email . "';");
while ($row_id_query = mysqli_fetch_assoc($id_query)){
print($row_id_query['user_name']);
}
?>
I want to select data WHERE the "user_name is $user_name"
This is login system, that means the $_SESSION'user_name'
is part of my code and i can't remake it.
Thanks for every answer,
Jakubk-0
Should be looking similar to
$sql = "INSERT INTO users (NickName, PassWord, Email)
VALUES (:nick, :pass, :mail)";
$conn->prepare($sql);
$conn->execute(array(':nick' => $NickNaming, ':pass' => $PassWording, ':mail' => $Emailing));
You should use PDO::prepare
Prepares an SQL statement to be executed by the
PDOStatement::execute() method.
and PDO::execute
Execute the prepared statement.
So your prepare and execute would look like this:
$sth = $conn->prepare( 'INSERT INTO users (NickName, PassWord, Email)
VALUES (:nick, :pass, :mail)');
$sth->execute( array(':nick' => $NickNaming,
':pass' => $PassWording,
':mail' => $Emailing));
I tried to not use PDO :
$insert = mysqli_query($con,"INSERT INTO users (Nickname, PassWord, Email)
VALUES ('$NickName','$PassWording','$Emailing')");
That will work

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 ? )

why email value stored as %email in mysql database?

I am so new in making project, so please don't mind. i created a code using php, html, css to store some data into mysql database. Everything is fine but the email value is stored as %email in the database. Can anybody help me please.
html code for email field:
<div class="row">
<div class="label">Email Id</div>
<div class="inputaddr">
<input type="text" id="email" required="required" class="detail" name="email"/>
</div>
<div class="label">Category</div>
<div class="inputmobile">
<input type="text" id="category" required="required" class="shortdetail" name="category"/>
</div>
</div> <!-- end of 5th row -->
.php file:
<?php
$conn = mysql_connect("localhost", "root", "");
$db = mysql_select_db('ssitdashboard', $conn) or die(mysql_error());
if(isset($_REQUEST['submit'])){
$fullname = $_POST['fullname'];
$fname = $_POST['fname'];
$mname = $_POST['mname'];
$raddr = $_POST['raddr'];
$laddr = $_POST['laddr'];
$email = $_POST['email'];
$sex = $_POST['sex'];
$dob = $_POST['dob'];
$bloodgroup = $_POST['bloodgroup'];
$mobile = $_POST['mobile'];
$rmobile = $_POST['rmobile'];
$category = $_POST['category'];
$usn = $_POST['usn'];
$branch = $_POST['branch'];
$sem = $_POST['sem'];
$eca = $_POST['eca'];
$year = $_POST['years'];
$quota = $_POST['quota'];
$que = "INSERT INTO personal_details(name, fname, mname, raddr, laddr, email, sex, dob, blood_group, mobile, rmobile, category, usn, branch, sem, eca, year, quota) VALUES ('$fullname', '$fname', '$mname', '$raddr', '$laddr', '%email', '$sex', '$dob', '$bloodgroup', '$mobile', '$rmobile', '$category', '$usn', '$branch', '$sem', '$eca', '$year', '$quota')";
if(mysql_query($que)){
// echo "<script>alert('You have registered successfully')</script>";
// echo "<script>window.open('http://www.ssit.edu.in')</script>";
header("Location:thankyou.html");
exit;
}
}
?>
In database the email field is taken as varchar(30)
You have a typo in your query, %email where you intended $email.
That being said, you should rip out all of this code and replace it with something that doesn't have gigantic SQL injection bugs in it. Either you must use mysql_real_escape_string on each and every $_POST value being inserted, or you should be using PDO.
Mistakes like this are a lot harder to make if you have parameterized queries. An example in PDO is:
# Using named data placeholders here
$pdo->prepare(
"INSERT INTO personal_details(name, fname, mname, raddr, laddr,
email, sex, dob, blood_group, mobile, rmobile, category, usn,
branch, sem, eca, year, quota)
VALUES (:fullname, :fname, :mname, :raddr, :laddr,
:email, :sex, :dob, :bloodgroup, :mobile, :rmobile, :category, :usn,
:branch, :sem, :eca, :year, :quota)";
# When executing you specify the data to be used. The same prepared statement can be
# executed many times with different data.
$pdo->execute(array('fullname' => $_POST['fullname'], 'fname' => $_POST['fname'], ...));
Try changing %email to $email in your SQL statement.
But, in addition, look into PDO, as this implementation is vulnerable to SQL Injection.
To elaborate on the PDO implementation, you could do something like this for your situation:
$username = "root";
$password = "";
$host = "localhost";
$dbname = "ssitdashboard";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}catch(PDOException $ex){
die("Failed to connect: ".$ex->getMessage());
}
Now you have a PDO connection stored in $db which you can query through. You may want to account for magic quotes if you're not using PHP 5.4, so keep that in mind.
Otherwise, create your query statement like so..
$query = "INSERT INTO personal_details ( name, fname, mname, raddr, laddr, email, sex, dob, blood_group, mobile, rmobile, category, usn, branch, sem, eca, year, quota ) VALUES ( :name, :fname, :mname, :raddr, :laddr, :email, :sex, :dob, :blood_group, :mobile, :rmobile, :category, :usn, :branch, :sem, :eca, :year, :quota )"
Afterwards, you want to bind the values from the $_POST variables to the parameters that have : in front of them (like :name). You do that like so:
$query_params = array( ':name' => $_POST['fullname'], ':fname' => $_POST['fname'], ':mname' => $_POST['mname'], ':raddr' => $_POST['raddr'], ':laddr' => $_POST['laddr'], ':email' => $_POST['email'], ':sex' => $_POST['sex'], ':dob' => $_POST['dob'], ':blood_group' => $_POST['bloodgroup'], ':mobile' => $_POST['mobile'], ':rmobile' => $_POST['rmobile'], ':category' => $_POST['category'], ':usn' => $_POST['usn'], ':branch' => $_POST['branch'], ':sem' => $_POST['sem'], ':eca' => $_POST['eca'], ':year' => $_POST['years'], ':quota' => $_POST['quota']);
Finally, now that you have the statement and the parameters, use the previously created $db variable to prepare and execute the statement.
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
Since we're just INSERTing variables into the database, that should be all that's needed. If you were SELECTing data though, you could do something like this AFTER you've done the above...
$rows = $statement->fetchAll();
And now you could refer to column headers within each $row of the database table by utilizing a foreach statement.
$bloodArray = array();
foreach($rows as $row){
if(isset($row['blood_group'])){
$bloodArray[] = $row['blood_group'];
}
}
Hope that helps out, sorry for the delay!
mistake is that i used %email in the query...

Categories