In a user creation form I have one element which is a drop down list where a role_type (i.e admin) can be assigned to the user.
Im not sure how to extract the value from the drop down and set it in the 'user' table because the table in the database takes a number however the user will select the value from the drop down.
The table the drop down is populated from only has two columns 'RoleTypeCode' which is auto incremented and 'Role_Title' which is the column used to populate the drop down.
The table i wish to update is referencing the RoleTypeCode.
USER: (UserRecordID(PK - AutoIncrement), Forename, Surname, Email, RoleTypeCode(FK))
Role_Type: (RoleTypeCode(PK - AutoIncrement), Role_Title)
So far i have:
$forename = $_POST['Forename'];
$surname = $_POST['Surname'];
$email = $_POST['Email'];
$role_title = $_POST['Role_Title'];
/*** connect to database ***/
include "db_conx.php";
try
{
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insertUser = $db_conx->prepare("INSERT INTO user (Forename, Surname, Email, Role_TypeCode ) VALUES (:forename, :surname, :email, :role_title )");
/*** bind the parameters ***/
$insertUser->bindParam(':forename', $forename, PDO::PARAM_STR);
$insertUser->bindParam(':surname', $surname, PDO::PARAM_STR);
$insertUser->bindParam(':email', $email, PDO::PARAM_STR);
$insertUser->bindParam(':role_title', $role_title, PDO::PARAM_STR);
/*** execute the prepared statement ***/
$insertUser->execute();
/*** success message ***/
$message = 'New user added';
}
catch(Exception $e)
{
/*** check if the email already exists ***/
if( $e->getCode() == 23000)
{
$message = 'This email has already been registered';
}
else
{
/*** fail message incase something went wrong ***/
$message = 'Unable to process your request. Please try again later';
}
}
not sure how to cater for role_title
any help would be much appreciated!! :)
UPDATE: the process I'm looking for is after a user hits the submit button. Trying to extract the information from the drop down and set it in the users table. The code above is for the submit file once a user has clicked 'submit'
Im not sure how to extract the value from the drop down and set it in the 'user' table because the table in the database takes a number however the user will select the value from the drop down.
The table the drop down is populated from only has two columns 'RoleTypeCode' which is auto incremented and 'Role_Title' which is the column used to populate the drop down.
You use the primary key of the RoleTypeCode as the dropdown value while you use the Role_Title as the display value. Then when you submit the form you just use the RoleTypeCode to set the FK value on the user.
So essentially you form would look like:
<?php
$stmt = $pdo->prepare('SELECT * FROM Role_Type');
$roles = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<form>
<label>First Name</label>
<input type="text" name="forename" />
<label>Last Name</label>
<input type="text" name="surname" />
<label>Email</label>
<input type="text" name="email" />
<label>Role</label>
<select name="role">
<?php foreach($roles as $role): ?>
<option value="<?php echo $role['RoleTypeCode'] ?>"><?php echo $role['Role_Title'] ?></option>
<?php endforeach; ?>
</select>
</form>
Then when you get your submit it would be something like:
$insertStmt = $pdo->prepare(prepare('INSERT INTO user (Forename, Surname, Email, Role_TypeCode ) VALUES (:forename, :surname, :email, :role )');
$insertStmt->execute(array(
':forname' => $_POST['forename'],
':surname' => $_POST['surname'],
':email' => $_POST['email'],
':role' => $_POST['role']
));
Use the following to populate drop down
<?php
//database connection
$sql = "SELECT * FROM Role_Type";
$db_conx->query($sql); //query as no parameters
//create html for drop down
$SelectHtml = "<select name='Role_Title' id='Role_Title'>\n";//Name and id to suit
while($row = $db_conx->fetch()) {
$SelectHtml .=<optionvalue='".$row[$RoleTypeCode]."'>".$row[$Role_Title]."</option>\n";
}
$SelectHtml .= "<select>\n";
?>
HTML to show drop down
<form action="xxx">
form stuff
<?php echo $SelectHtml ?>
more form stuff
Use to update using RoleTypeCode value which is FK to UserRecordID in USER
If I understand your question correctly, what you want can be accomplished using AJAX -- which sounds complicated, but isn't. However, it is handled on the front end.
Here are some good posts for getting the basics of AJAX:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
Related
I have a PHP PDO statement that queries a table in my database to return a list of users.
The form is used to log maintenance events, so the username is used to log the person that has done the maintenance.
However when the form is submitted - its submitting the value of the dropdown box instead of the ID of the row it's returning. The table its submitting it into has a column "engineer" the is referencing the engineers table e.g. John Doe id = 1.
I think I need it to post the ID and not the name.. Here's my code:
<form action="" method="post">
<label>Engineer Name:</label>
<br/><br/>
<select id="teamlist" name="teamlist">
<?php
$pdo = new PDO('mysql:host=localhost;dbname=frontier_maintlog', 'user', 'pass');
#Set Error Mode to ERRMODE_EXCEPTION.
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('Select name from engineers');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option>'.$row['name'].'</option>';
}
?>
</select>
<br/><br/>
<input type="submit" value=" Submit " name="submit"/><br />
</form>
and here's the bit that does the inserting into database:
$sql = "INSERT INTO log (engineer, description, fa_description)
VALUES ('".$_POST["engineer"]."','".$_POST["description"]."','".$_POST["fa_description"]."')";
The "log" table looks a bit like this:logtableimage
Thank you! Sorry if it doesn't make perfect sense.
Here's the error I receive SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'engineer' at row 1
Error is that you are inserting string to int datatype.
You should also select id value from engineers table, to use for options:
...
$stmt = $pdo->prepare('Select id,name from engineers');
$stmt->execute();
// and assign value to options
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<option value='$row[id]'>$row[name]</option>";
}
You have to assign a value to option. Every option needs to have it's own value. In you case you just echo the option.
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
Ask the user which row to delete based on the
value selected in the select list and the value from a textbox which contains
the matching data. For example, selected item = ‘city’ and the textbox =
‘Boston’. Include a button that removes the row from the table.
those are my instructions to follow. I am having two issues, the first issue is if I say.. select teamname and enter a team from the table I get an error saying:
DELETE FROM teams WHERE teamname = rockets
Column not found: 1054 Unknown column 'rockets' in 'where clause'
its trying to use rockets as the column name and not the row that's needs to be deleted. The second issue is if I select yearformed and enter in a correct year, it will delete the row/s with that year. If i enter a year that doesn't exist, my code says records deleted successfully, but nothing is actual deleted.
I think I have got somethings mixed up here, and not sure exactly how it halfway works for yearformed and doesn't for other columns....
html
<form method='post' action='phpfiles/deleteData.php'>
Select a column name, then enter which data to delete.
<br>
<br>
<label for='option1'>
<select name='selectColumn'>
<option value='teamname' id='team'>teamname</option>
<option value='city' id='city'>city</option>
<option value='bestplayer' id='best'>bestplayer</option>
<option value='yearformed' id='year'>year</option>
<option value='website' id='website'>website</option>
</select>
</label>
<label for='option2'>
Data to delete: <input type='text' name='dataDelete'>
</label>
<br><br>
<input type='submit' value='Submit Delete'>
</form>
php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$servername = "localhost";
$username = "root";
$password = "enigma";
$dbname = "program09";
$columnSelect = $_POST['selectColumn'];
$deleteData = $_POST['dataDelete'];
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to delete a record
$sql = "DELETE FROM teams WHERE $columnSelect = $deleteData";
// use exec() because no results are returned
$conn->exec($sql);
echo "Record deleted successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
You need single quotes:
$sql = "DELETE FROM teams WHERE $columnSelect = '$deleteData'";
But it's better to use prepared statements to avoid SQL Injection. Also use a whitelist for your column names.
$sql = "DELETE FROM teams WHERE $columnSelect = :value1";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':value1'=>$deleteData));
I'm a novice when it comes to mySQL, and even more so when it comes to PDO. I'm trying to create some simple insert code but I keep getting a server error. I have a feeling it has to do with defining $STH twice. Here's my code:
$dsn = "mysql:host=localhost;dbname=Menu_Items";
$user = "root";
$pass = "root";
// Connect to database
try{
$DBH = new pdo($dsn, $user, $pass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
// Define user input as $food
$name = $_POST['food'];
$STH->bindParam(':name', $name);
// Insert user input into table
$STH = $DBH->prepare("INSERT INTO foods ( name ) VALUES ( :name )");
$result = $DBH -> query($STH);
if($result){
echo("<br>Input data is succeed");
}else{
echo("<br>Input data is fail");
}
This php code is connected to a simple html form:
<form id="menu_input" name="menu_input" method="post" action="insert.php">
<table>
<thead>Enter a new item</thead>
<tr>
<th><label for="food">Food</label></th>
<td><input type="text" name="food" id="food" placeholder="Food Name" required></td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table>
</form>
I've been doing research but just having a little difficulty getting it to work. Thoughts?
First create/get the object/instance then use its methods; not the other way round.
// Insert user input into table
$STH = $DBH->prepare("INSERT INTO foods ( name ) VALUES ( :name )");
$STH->bindParam(':name', $name);
$STH->execute();
and (nit-picking mode: on) there's no need for the variable $name
// Insert user input into table
$STH = $DBH->prepare("INSERT INTO foods ( name ) VALUES ( :name )");
$STH->bindValue(':name', $_POST['food']);
$STH->execute();
will do, and so would
// Insert user input into table
$STH = $DBH->prepare("INSERT INTO foods ( name ) VALUES ( :name )");
$STH->execute(array('name'=>$_POST['food']));
Use bindValue instead of bindParam, because you are binding value, not parameter. Call bindValue after prepare statement:
...
$name = $_POST['food'];
// Insert user input into table
$STH = $DBH->prepare("INSERT INTO foods ( name ) VALUES ( :name )");
$STH->bindValue(':name', $name);
$result = $DBH->query($STH);
...
Named placeholders has nothing to do with your problem.
And they aren't "best bet". It's just a syntax sugar, quite unnecessary one.
Your problem is not a named placeholder but syntax which you have got out of nowhere.
Always read the manual page on the function you are using. query() method doesn't support placeholders.
Always read tag wiki before asking a question. There you can see the proper example.
Please read Stackoverflow tag wiki on PDO I linked above and use code from there. Both for connecting and query execution.
You have to set up error reporting to see the errors. Otherwise there is noway to know what is wrong with your code.
I have a page with 3 columns, the first 2 columns have forms while the third shows information.
Whenever the page is called, information corresponding to the first form will already exist, however the second form can be used to insert new data or update existing.
The code I have at the moment:
<?php
require_once 'connect.php';
$formType = $_POST['formType'];
$id = $_POST['id'];
$favColor= $_POST['favColor'];
$favFood= $_POST['favFood'];
$country = $_POST['country'];
if($_POST['formType'] == 'guestCosts'){
$sth = $dbh->prepare("INSERT INTO info (id, favColor, favFood, country)
VALUES ('$id', '$favColor', '$favFood', '$country')");
$sth->execute();
}elseif($_POST['formType'] == 'guestCosts'){
$sth = $dbh->prepare("UPDATE info SET favColor = '$favColor', favFood = '$favFood', country = '$country' WHERE id = '$id'");
$sth->execute();
}
$dbh =null;
?>
The problem I'm having is that I see now way to distinguish between when I should do an UPDATE vs when I should do an INSERT.
The page that generates the form does a query to populate the form with the values from the database. I thought of adding a hidden field if the database is empty for a particular id for example:
<input type = "hidden" name ="action" value="insert" />
However I'm not sure passing a variable between pages is the most efficient way. Is there a better way to do what I am trying to do?
Take a look at MySQL INSERT ON DUPLICATE KEY UPDATE
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Ok so essentially what I'm trying to do is add a q&a component to my website (first website, so my current php knowledge is minimal). I have the html page where the user's input is recorded, and added to the database, but then I'm having trouble pulling that specific info from the database.
My current php page is pulling info where the questiondetail = the question detail (detail='$detail') in the database, but that could potentially present a problem if two users enter the same information as their question details (unlikely, but still possible, especially if the same person accidentally submits the question twice). What I want to do is have the page load according to the database's question_id (primary key) which is the only thing that will always be unique.
HTML CODE:
<form id="question_outline" action="process.php" method="get">
<p><textarea name="title" id="title_layout" type="text" placeholder="Question Title" ></textarea> </p>
<textarea name="detail" id= "detail_layout" type="text" placeholder="Question Details" ></textarea>
<div id="break"> </div>
<input id="submit_form" name="submit_question" value="Submit Question" type="submit" />
</form>
PROCESS.PHP CODE:
$name2 = $_GET['name2'];
$title = $_GET['title'];
$detail = $_GET['detail'];
$query= "INSERT INTO questions (title, detail) VALUES ('$title', '$detail')";
$result = mysql_query("SELECT * FROM questions where detail='$detail' ")
or die(mysql_error());
The info is being stored correctly in the database, and is being pulled out successfully when detail=$detail, but what I'm looking to do is have it pulled out according to the question_id because that is the only value that will always be unique. Any response will be greatly appreciated!
Updated Version
QUESTION_EXAMPLE.PHP CODE
<?php
$server_name = "my_servername";
$db_user_name ="my_username";
$db_password = "my_password";
$database = "my_database";
$submit = $_GET['submit'];
$title = $_GET['title'];
$detail = $_GET['detail'];
$conn = mysql_connect($server_name, $db_user_name, $db_password);
mysql_select_db($database) or die( "Unable to select database");
$result = mysql_query("SELECT title, detail FROM questions WHERE id =" .
mysql_real_escape_string($_GET["id"]), $conn);
$row = mysql_fetch_assoc($result);
mysql_close($conn);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
Firstly, if that is code to be used in production, please make sure you are escaping your SQL parameters before plugging them in to your statement. Nobody enjoys a SQL injection attack. I would recommend using PDO instead as it supports prepared statements and parameter binding which is much much safer.
How can I prevent SQL injection in PHP?
So you have a form...
[title]
[details]
[submit]
And that gets inserted into your database...
INSERT INTO questions (title, details) VALUES (?, ?)
You can get the last insert id using mysql_insert_id, http://php.net/manual/en/function.mysql-insert-id.php.
$id = mysql_insert_id();
Then you can get the record...
SELECT title, details FROM questions WHERE id = ?
And output it in a preview page.
I have written an example using PDO instead of the basic mysql functions.
form.php:
<form action="process.php" method="post">
<label for="question_title">Title</label>
<input id="question_title" name="title"/>
<label for="question_detail">Detail</label>
<input id="question_detail" name="detail"/>
<button type="submit">Submit</button>
</form>
process.php:
<?php
// Create a database connection
$pdo = new PDO("mysql:dbname=test");
// Prepare the insert statement and bind parameters
$stmt = $pdo->prepare("INSERT INTO questions (title, detail) VALUES (?, ?)");
$stmt->bindValue(1, $_POST["title"], PDO::PARAM_STR);
$stmt->bindValue(2, $_POST["detail"], PDO::PARAM_STR);
// Execute the insert statement
$stmt->execute();
// Retrieve the id
$id = $stmt->lastInsertId();
// Prepare a select statement and bind the id parameter
$stmt = $pdo->prepare("SELECT title, detail FROM questions WHERE id = ?");
$stmt->bindValue(1, $id, PDO::PARAM_INT);
// Execute the select statement
$stmt->execute();
// Retrieve the record as an associative array
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
Without PDO...
form.php:
<form action="process.php" method="post">
<label for="question_title">Title</label>
<input id="question_title" name="title"/>
<label for="question_detail">Detail</label>
<input id="question_detail" name="detail"/>
<button type="submit">Submit</button>
</form>
process.php:
<?php
// Create a database connection
$conn = mysql_connect();
// Execute the insert statement safely
mysql_query("INSERT INTO questions (title, detail) VALUES ('" .
mysql_real_escape_string($_POST["title"]) . "','" .
mysql_real_escape_string($_POST["detail"]) . "')", $conn);
// Retrieve the id
$id = mysql_insert_id($conn);
// Close the connection
mysql_close($conn);
header("Location: question_preview.php?id=$id");
question_preview.php:
<?php
// Create a database connection
$conn = mysql_connect();
// Execute a select statement safely
$result = mysql_query("SELECT title, detail FROM questions WHERE id = " .
mysql_real_escape_string($_GET["id"]), $conn);
// Retrieve the record as an associative array
$row = mysql_fetch_assoc($result);
// Close the connection
mysql_close($conn);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
I assume you want to sort the questions according to the question_id. You could try using the ORDER BY command
example -
$result = mysql_query("SELECT * FROM questions where detail='$detail' ORDER BY question_id")
For these type of examples, you need to run Transaction within database
below are the
http://dev.mysql.com/doc/refman/5.0/en/commit.html
Or else
Create an random variable stored in session and also insert into database and you call it from database and you can preview it easily.
id | question_code | q_title
question_code is the random value generated before insertion into database,
and save the question_code in a session and again call it for preview.